Python OpenCV pause without ending on error

I am reading a video using OpenCV:

def get_frames(video_path):
    # Generate frames
    cap = cv2.VideoCapture(video_path)
    while(cap.isOpened()):
        try:
            ret, frame = cap.read()
            if ret is True:
                yield frame
        except Exception as e:
            print(e)

for _ in get_frames(input_video_path_1):
    # do stuff

When running my process I got the following errors:

[mpeg4 @ 0x7feec69d4400] ac-tex damaged at 21 17
[mpeg4 @ 0x7feec69d4400] Error at MB: 1398

The problem is that no python error is raised and therefore I cannot catch the error. The code seems to pause without ending. It just stops there. How can I at least catch the error?

...
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened(): return
    while True:
        ret, frame = cap.read()
        if not ret: break
        yield frame
...

isOpened is checked once, at the beginning. that is sufficient.

you HAVE TO stop reading frames when ret becomes false. that’s how you know the video file has ended. NOT via isOpened

your code “freezes” because you keep reading frames, but ret is false, and you never break the loop.

some very bad advice out there on the internet. unfortunately, some of it is also in the official OpenCV docs… since someone contributed it back in 2013/2014.

1 Like

Thank you. This makes the code end. That was one of two problem. Now, how can I skip "damaged"frames? Because this way I am not reading the entire video, probably because the following error is thrown:

mpeg4 @ 0x7fa87c877a00] ac-tex damaged at 78 17
[mpeg4 @ 0x7fa87c877a00] Error at MB: 1455

I can confirm that I see the video on VLC and that with the same code I have processed, on the same machine, another video with the same format and encoding (I know it because I generated both video on another machine).

OpenCV is not a media handling library. it isn’t supposed to deal with broken video files.

you can either ignore those warnings and let them scroll by (they come from ffmpeg), or you can use ffmpeg’s libraries directly. have a look at “PyAV”.