OpenCV: how to restart a video when it finishes?
Solution 1
If you want to restart the video over and over again (aka looping it), you can do it by using an if statement for when the frame count reaches cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
and then resetting the frame count and cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, num)
to the same value. I'm using OpenCV 2.4.9 with Python 2.7.9 and the below example keeps looping the video for me.
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()
It also works to recapture the video instead of resetting the frame count:
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
frame_counter = 0
cap = cv2.VideoCapture(video_name)
Solution 2
You don't need to reopen the current capture. All you need to do is to reset position to the beginning of the file and to continue the cycle instead of breaking it.
if (!frame)
{
printf("!!! cvQueryFrame failed: no frame\n");
cvSetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO , 0);
continue;
}
Nevertheless there is a significant delay as if you were reopened it...
Solution 3
Easiest Way-:
cap = cv2.VideoCapture("path")
while True:
ret, image = cap.read()
if ret == False:
cap = cv2.VideoCapture("path")
ret, image = cap.read()
ziiweb
Ziiweb is a web agency on creating websites and web applications. We also offer marketing online services (SEO/PPC) to promote your business through search engines and social networks. We always bet for the last and best web technologies: HTML5, CSS3, jQuery, PHP5 and symfony (all releases).
Updated on July 12, 2022Comments
-
ziiweb almost 2 years
I'm playing a video file, but how to play it again when it finishes?
Javier
-
karlphillip about 12 yearsC? C++? Java? or what? Improve the tagging please.
-
karlphillip almost 12 yearsIf this question has been successfully answered, consider selecting the official answer by clicking on the checkbox near it. If not, consider adding your own answer.
-
-
noio about 10 yearsWeirdly, after the first reset like this, the feed keeps returning the last frame.
-
Darky WC almost 4 yearsif anybody is using OpenCV version 4.2.0, just substitute
cv2.cv.CV_CAP_PROP_FRAME_COUNT
tocv2.CAP_PROP_FRAME_COUNT
andcv2.cv.CV_CAP_PROP_POS_FRAMES
tocv2.CAP_PROP_POS_FRAMES
. This works for me. -
Surya Tej over 3 yearsIf you are using opencv python 4.2 the
CAP_PROP_FRAME_COUNT
doesn't have a prefixCV_