Playback loop option in OpenCV videos

self.cap =cv2.VideoCapture(self.filename)       
while True:

    ret,frameset = self.cap.read()
             
    if self.cap.get(1)>self.cap.get(7)-2:#video loop
        self.cap.set(1,0)#if frame count > than total frame number, next frame will be zero
    cv2.imshow("G",frameset)
    key = cv2.waitKey(1)
    if key == 27:
        break
self.cap.release()
cv2.destroyAllWindows()

For python3, opencv3.1.0, raspberry pi 3

import numpy as np
import cv2
cap = cv2.VideoCapture('intro.mp4')
while(cap.isOpened()):
    
    ret, frame = cap.read() 
    #cv2.namedWindow("window", cv2.WND_PROP_FULLSCREEN)
    #cv2.setWindowProperty("window",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
    
    if ret:
        cv2.imshow("Image", frame)
    else:
       print('no video')
       cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
       continue
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
    
cap.release()
cv2.destroyAllWindows()

I partially solved it by replacing vidFile.set (cv2.cv.CV_CAP_PROP_POS_FRAMES, 1) by vidFile.set(cv2.cv.CV_CAP_PROP_POS_AVI_RATIO, 0), although this works for .avi files only.


I can get looped video playback by using an if statement for when the frame count reaches cap.get(cv2.CAP_PROP_FRAME_COUNT) and then resetting the frame count and cap.set(cv2.CAP_PROP_POS_FRAMES, num) to the same value. 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.CAP_PROP_FRAME_COUNT):
        frame_counter = 0 #Or whatever as long as it is the same as next line
        cap.set(cv2.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.CAP_PROP_FRAME_COUNT):
    frame_counter = 0
    cap = cv2.VideoCapture(video_name)

So at least it works for me to use cap.set(cv2.CAP_PROP_POS_FRAMES, num) to loop a video. What happens if you reset to the zeroth frame instead of the first (like with the avi method)?