python - 在命令行返回状态,而 cap.isOpened()
问题描述
我使用 Python 3.6.5 和 OpenCV 3.4.1 阅读了一个 mp4 视频,并对每一帧进行了一些(资源密集型)计算。
我当然有帧总数 ( length
) 和当前帧 ( ) count
,所以我想在命令行中提供进度更新,但不幸的是,它仅在整个过程完成后才显示所有内容。
while cap.isOpened():
ret, frame = cap.read()
if ret:
# Calculation stuff
...
# Print the current status
print("Frame %s/%s" % (count, length))
count = count + 1
不幸的是,它仅在视频文件完全处理后才打印 ALL。如何打印当前帧的“实时”状态?
我使用 MINGW64 (Windows) 作为我的控制台
解决方案
乍一看,这是因为您的代码中可能有控制流指令(如break
、continue
等),这会阻止解释器到达该行。
因此,您应该确保在这些指令之前打印,我们可以简单地在顶部打印,例如:
while cap.isOpened():
ret, frame = cap.read()
print("Frame %s/%s" % (count, length))
count += 1
if ret:
# Calculation stuff
# ...
pass
话虽如此,我们可以将这个捕获过程变成一个打印值的生成器,并带有一个漂亮的进度条,例如:
from tqdm import tqdm
from cv2 import CAP_PROP_FRAME_COUNT
def frame_iter(capture, description):
def _itertor():
while capture.grab():
yield capture.retrieve()[1]
return tqdm(
_iterator(),
desc=description,
total=int(capture.get(CAP_PROP_FRAME_COUNT)),
)
然后我们可以像这样使用它:
for frame in frame_iter(capture, 'some description'):
# process the frame
pass
它将显示一个进度条,如tqdm
.
推荐阅读
- testing - 故事书和冒烟测试:有没有办法自动验证故事书中的所有故事?
- html - 带骨架的快速 LCP
- delphi - FireDAC 的 GetTableNames() 方法存在问题
- javascript - 如何编写将类组件作为功能组件返回的 React 组件?
- git - Github 网站提交作者用户名与 git log 中显示的用户名不同
- sql - 如何选择与其他属性无关的所有属性
- reactjs - 使用 react 和 next.js 导入 geojson
- java - Jersey 3.0.1 - 无法从 FormDataBodyPart 获取 MediaType
- android - Android 10 / API 29 Kotlin - 将视频下载到图片中的子目录
- angular - 允许从本地主机外部访问 - Angular