相关文章推荐
俊逸的卡布奇诺  ·  Apache ...·  4 月前    · 

当cap.isOpened()在命令行时,返回状态

2 人关注

我用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

不幸的是,它只在视频文件完全处理完后才打印出所有的内容。 我怎样才能打印出当前帧的 "实时 "状态?

我使用MINGW64(Windows)作为我的控制台。

1 个评论
你的代码中是否有 continue 的变化(在 print 部分之前)?
python
python-3.x
opencv
PrimuS
PrimuS
发布于 2018-06-17
2 个回答
Willem Van Onsem
Willem Van Onsem
发布于 2019-07-25
已采纳
0 人赞同

乍一看,这是由于你可能有 control flow 你的代码中的指令(如 break continue 等),阻止解释器到达该行。

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

while cap.isOpened():
    ret, frame = cap.read()
    print("Frame %s/%s" % (count, length))
    count += 1
    if ret:
        # Calculation stuff
        # ...

既然如此,我们可以把这个捕获程序变成一个发电机打印数值,并有一个漂亮的进度条,如。

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

它将显示一个进度条,就像图中展示的那样GitHub repository of tqdm.

没有控制流,最后是Windows下的MINGW的问题,但我最后还是用了你的代码,所以谢谢你。
Bharath Kumar
Bharath Kumar
发布于 2019-07-25
0 人赞同

OpenCV writer in tqdm

import numpy as np
import cv2
from tqdm import tqdm
cap = cv2.VideoCapture("input.MP4")
outcap = cv2.VideoWriter("output.MP4",     cv2.VideoWriter_fourcc('H','2','6','4'), 30, (int(cap.get(3)),int(cap.get(4))))
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(int(inpcap.get(3)),int(inpcap.get(4)))
print("total frames :",crame_count)
i = 1
pbar = tqdm(total = frame_count)
while(cap.isOpened()):
    pbar.update(i)
    ret, frame = cap.read()
    if frame is None:
       print('completed...!')