python上的cv2.VideoCapture

时间:2015-12-27 14:27:06

标签: python loops opencv video ffmpeg

我正在运行以下代码:

import numpy as np
import cv2
import os

count = 0

cap = cv2.VideoCapture("/home/simon/PROJECT/real_data/00000020.mp4")

while not cap.isOpened():
    cap = cv2.VideoCapture("./00000020.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) & 0xFF == 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


if ret == True:
    frame = cv2.VideoCapture.grab()
    frame = 'frame%d' % count 

    cv2.imwrite('frame%d.png', frame)

    count += 1
else:
    print 'stopped at' + count
    break

每当我运行它时,它会循环while而不是循环,打印“wait for header”。 从来没有错误代码或类似的东西。

我试图将它作为一个更简单的代码运行,它没有进行所有这些检查,并且再次没有抛出任何错误。

我正在尝试运行此代码来打开视频,然后将整个视频中的帧保存为png文件。

有没有人发现代码的任何特殊问题? 或者也许有人知道一段代码可以做我想要更高效的事情,因为我最近搜索了谷歌搜索和堆栈溢出很多并且没有找到任何东西

提前致谢 熊猫

1 个答案:

答案 0 :(得分:0)

您需要在python目录中包含几个DLL才能播放视频。有关详细信息,请参阅此处:

https://li8bot.wordpress.com/2014/07/09/opencvpython-part-1-working-with-videos/