Set other video on video end (cv2)

Question:

I am trying to set other video on video end in cv2.

I expected it to set other video (that i provided), and the actual results was none. The window just closes and displays an error in the command line.

The error is:

cv2.error: OpenCV(4.6.0) D:aopencv-pythonopencv-pythonopencvmoduleshighguisrcwindow.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

I tried to do it by re-defining the cap variable.
Here is the code:

import numpy as np
import cv2 as cv
cap = cv.VideoCapture('video.mp4')
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        cap = cv.VideoCapture('video2.mp4')
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()
Asked By: coder228

||

Answers:

After you set the the cap for video2.mp4 you will need to read the first frame of video2.
The frame object is still the same (invalid one) from the previous cap.read()
You shuld also release the old capture object before opening the new one.
Try the following code:

import numpy as np
import cv2 as cv
cap = cv.VideoCapture('video.mp4')
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        cap.release() # release old Capture object
        cap = cv.VideoCapture('video2.mp4')
        ret, frame = cap.read() # read first frame of new video
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()
Answered By: Andi R
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.