I'm playing a video file, but how to play it again when it finishes?
Javier
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With