Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python opencv cv2.cv.CV_CAP_PROP_FRAME_COUNT get wrong numbers

Tags:

import os
import cv2
path='/home/nlpr4/video-data/UCF-101/GolfSwing/v_GolfSwing_g24_c06.avi'
cap=cv2.VideoCapture(path)
video_length=int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))

success=True
count=0
while success:
    success,image=cap.read()
    if success==False:
        break
    count=count+1

print video_length,count

output:

149 
146

why the two numbers different? what's wrong?

like image 698
kli_nlpr Avatar asked Jul 17 '15 09:07

kli_nlpr


People also ask

Is CV and cv2 same?

cv2 (old interface in old OpenCV versions was named as cv ) is the name that OpenCV developers chose when they created the binding generators. This is kept as the import name to be consistent with different kind of tutorials around the internet.

What does .read do OpenCV?

. read() in OpenCV returns 2 things, boolean and data. If there are not 2 variables, a tuple will be assigned to one variable. The boolean is mostly used for error catching.

Is cv2 same as OpenCV Python?

CV2 is OpenCV. OpenCV and PIL both have image processing tools such as: Image filters (blur, sharpen, etc.)


2 Answers

The get() for CAP_PROP_FRAME_COUNT is never supposed to be accurate! If you check the opencv source code. You can find this:

int64_t CvCapture_FFMPEG::get_total_frames() const
{
    int64_t nbf = ic->streams[video_stream]->nb_frames;

    if (nbf == 0)
    {
        nbf = (int64_t)floor(get_duration_sec() * get_fps() + 0.5);
    }
    return nbf;
}

This means it will first look into the stream header for nb_frames, which you can check with ffprobe. If there is no such field, then there is no better way to get frame number than directly decoding the video. The opencv did a rough estimation by get_duration_sec() * get_fps() + 0.5 which surely not mean for accuracy.

Thus, to obtain the correct frame number you have to decode and read through the entire stream, or you have to ask the video generator to generate correct stream header with nb_frames field.

like image 58
Wang Avatar answered Sep 28 '22 08:09

Wang


CV_CAP_PROP_FRAME_COUNT gives the property of 'number of frames', that comes from the video header. The other number is basically "How many frames can I read from this video file?".

If the video contains frames that cannot be read/decoded (e.g., due to being corrupted), OpenCV skips those frames (after trying to read them) and gives you the next valid frame. So the difference between your two numbers is the number of frames that couldn't be read.

Also, if your video header is corrupted and/or cannot be parsed by the underlying codecs that OpenCV uses, then those numbers can be different too.

like image 43
ilke444 Avatar answered Sep 28 '22 08:09

ilke444