您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用OpenCV和Python在视频流中逐帧处理视频图像

如何使用OpenCV和Python在视频流中逐帧处理视频图像

阅读完的文档后VideoCapture。我发现您可以告诉VideoCapture,下次调用VideoCapture.read()(或VideoCapture.grab())要处理哪个帧。

问题是,当您要准备read()一个尚未准备就绪的框架时,该VideoCapture对象会卡在该框架上而永远无法进行。因此,您必须强制其从上一帧重新开始。

这是代码

import cv2

cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
    cap = cv2.VideoCapture("./out.mp4")
    cv2.waitKey(1000)
    print "Wait for the header"

pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
    flag, frame = cap.read()
    if flag:
        # The frame is ready and already captured
        cv2.imshow('video', frame)
        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
        print str(pos_frame)+" frames"
    else:
        # The next frame is not ready, so we try to read it again
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
        print "frame is not ready"
        # It is better to wait for a while for the next frame to be ready
        cv2.waitKey(1000)

    if cv2.waitKey(10) == 27:
        break
    if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
        # If the number of captured frames is equal to the total number of frames,
        # we stop
        break
python 2022/1/1 18:28:35 有518人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶