OpenCV:完成后如何重启视频?

时间:2012-04-07 18:38:23

标签: opencv

我正在播放视频文件,但完成后又如何播放?

哈维尔

4 个答案:

答案 0 :(得分:3)

如果你想一遍又一遍地重启视频(也就是循环播放),你可以通过使用if语句来实现,当帧数达到cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)然后重置帧数并{{1相同的值。我正在使用OpenCV 2.4.9和Python 2.7.9,下面的例子为我保留了循环视频。

cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, num)

它还可以重新捕捉视频,而不是重置帧数:

import cv2

cap = cv2.VideoCapture('path/to/video') 
frame_counter = 0
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    frame_counter += 1
    #If the last frame is reached, reset the capture and the frame_counter
    if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
        frame_counter = 0 #Or whatever as long as it is the same as next line
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 0)
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

答案 1 :(得分:1)

您无需重新打开当前捕获。您需要做的就是将位置重置到文件的开头并继续循环而不是破坏它。

if (!frame) 
{
    printf("!!! cvQueryFrame failed: no frame\n");
    cvSetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO , 0);
    continue;
}  

然而,如果重新打开它会有明显的延迟...

请参阅http://docs.opencv.org/2.4.6/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=cvqueryframe#videocapture-set

答案 2 :(得分:0)

关闭当前捕获并再次打开:

// play video in a loop
while (1)
{
    CvCapture *capture = cvCaptureFromAVI("video.avi");
    if(!capture) 
    {
        printf("!!! cvCaptureFromAVI failed (file not found?)\n");
        return -1; 
    }

    IplImage* frame = NULL;
    char key = 0;   
    while (key != 'q') 
    {
        frame = cvQueryFrame(capture);       
        if (!frame) 
        {
            printf("!!! cvQueryFrame failed: no frame\n");
            break;
        }     

        cvShowImage("window", frame);

        key = cvWaitKey(10);  
    }

    cvReleaseImage(&frame);
    cvReleaseCapture(&capture);
}

此代码尚未完成且尚未经过测试。它仅用于说明目的。

答案 3 :(得分:0)

最简单的方法-:

while True:
  ret, image = cap.read()
  if ret == False:
         cap = cv2.VideoCapture("path")
          ret, image = cap.read()