4

我正在播放一个视频文件,但播放完后如何再次播放?

哈维尔

4

4 回答 4

9

如果您想一遍又一遍地重新启动视频(也就是循环播放),您可以使用 if 语句来判断帧数何时达到cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT),然后将帧数重置cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, num)为相同的值。我将 OpenCV 2.4.9 与 Python 2.7.9 一起使用,下面的示例不断为我循环播放视频。

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()

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

if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
    frame_counter = 0
    cap = cv2.VideoCapture(video_name)
于 2015-01-11T18:24:23.967 回答
2

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

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

于 2013-09-25T15:55:02.393 回答
2

最简单的方法-:

cap = cv2.VideoCapture("path")
while True:
  ret, image = cap.read()
  if ret == False:
         cap = cv2.VideoCapture("path")
          ret, image = cap.read()
于 2021-06-22T12:19:00.250 回答
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);
}

此代码不完整,尚未经过测试。它仅用于说明目的。

于 2012-04-07T18:47:54.530 回答