0

I am trying to read a video file using openCV in python. I was using a simple test to check if there is a returned frame:

vid = cv.VideoCapture(video_path)
ok, image = vid.read()
if not ok:
  break

Well, this seemed to be working fine until I discovered a few videos that have some difficulties reading some frames in the middle of the video. I am able to read the same videos using imageio for example so I guess there is a way to read them. I have counted the number of "corrupted" frames using:

for video_path in videos_list:
    vid = cv.VideoCapture(video_path)
    fr = 1
    counter = 0
    max_corrupted_frames = 20
    while True:
        ok, image = vid.read()
        if not ok:
            counter += 1
        else:
            if counter:
                print('{} consecutive frames were not able to be read before frame {} in video {}'.format(
                    counter, fr, video_path))
            counter = 0
        if counter > max_corrupted_frames:
            break
        fr += 1

which is between 1 and 4 for my case. Using a bigger threshold I can decide if the video has ended or I just have some trouble reading the frame but it seems error-prone as approach.

So, a couple question arose:

  • Is there any other way to determine if the video has ended using openCV (the method using cap.isOpened() for some reason it does not work on me)?
  • Why openCV fails in my case to read those frames but imageio does not? The frame seems normal (when extracted with imageio).

I am using openCV 3.4.1 in Ubuntu 16.04 with python 3.5.2 if that makes any difference.

Eypros
  • 5,370
  • 6
  • 42
  • 75
  • 1
    I have never tried to open a corrupted video, but you can check if you are at the end with the properties `CV_CAP_PROP_FRAME_COUNT` to get the total amount of frames and `CV_CAP_PROP_POS_FRAMES` to get the next frame to be read... OpenCV uses in the backend FFMPEG or GStreamer (some more in the latest versions) and they fail, because the lib fail to do it, probably a buggy codec. You may try to use the other backends to see if you get a better result – api55 Jul 17 '18 at 13:33
  • Please go through these resources: [StackOverFlow post](https://stackoverflow.com/questions/25359288/how-to-know-total-number-of-frame-in-a-file-with-cv2-in-python) and [Videocapture Docs](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=get#videocapture-get) – ZdaR Jul 17 '18 at 13:48

0 Answers0