Search code examples
pythonpython-3.xopencvvideo

Repeating a video on loop using OpenCV and Python


I am trying to create a simple program that will play a video using OpenCV on repeat until the waitKey is pressed. The video will play once and then give an error message "(-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'". I was getting this message earlier but fixed it by changing the file location. I'm almost positive that the issue comes from the fact that when the video ends the next frame is nonexistent so it cant be read, as breaking the while loop when the frame is None doesn't give an error. Every solution I have tried has failed. Any help?

import cv2
import numpy as np 

cap = cv2.VideoCapture('video_file_location')


while True:

     _, frame = cap.read()

     cv2.imshow('frame',frame)
     if cv2.waitKey(1) == 27:
         break



cap.release()
cv2.destroyAllWindows()

Solution

  • Try putting the cv2.VideoCapture() into the loop and the frame should only show when the return is True and that is your problem in your code

    import cv2
    import numpy as np 
    
    
    
    
    while True:
        #This is to check whether to break the first loop
        isclosed=0
        cap = cv2.VideoCapture('videoplayback.mp4')
        while (True):
    
            ret, frame = cap.read()
            # It should only show the frame when the ret is true
            if ret == True:
    
                cv2.imshow('frame',frame)
                if cv2.waitKey(1) == 27:
                    # When esc is pressed isclosed is 1
                    isclosed=1
                    break
            else:
                break
        # To break the loop if it is closed manually
        if isclosed:
            break
    
    
    
    cap.release()
    cv2.destroyAllWindows()