首页 > 解决方案 > 在命令行返回状态,而 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) 作为我的控制台

标签: pythonpython-3.xopencv

解决方案


乍一看,这是因为您的代码中可能有控制流指令(如breakcontinue等),这会阻止解释器到达该行。

因此,您应该确保在这些指令之前打印,我们可以简单地在顶部打印,例如:

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.


推荐阅读