Python opencv cv2.cv.CV_CAP_PROP_FRAME_COUNT get invalid numbers

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 are two numbers different? what's wrong?

+4
source share
3 answers

Try this code:

#!/usr/bin/env python

import numpy as np
import cv2

video = "../videos/sample.avi"

video_capture = cv2.VideoCapture(video)
video_length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))

count = 0
while(True):
        # Capture frame-by-frame
        ret, frame = video_capture.read()
        if not ret:
            break

        count += 1

print video_length, count
# When everything done, release the capture
video_capture.release()
cv2.destroyAllWindows()

On my machine, this gives me:

$ ./openstack_video_frames.py 
1232 1232
0
source

CV_CAP_PROP_FRAME_COUNTgives the "number of frames" property that comes from the video title. Another number is basically "How many frames can I read from this video?".

If you cannot read / decode a frame, then your code will stop counting. And this will lead to different numbers. For example, it may be due to a damaged frame.

In addition, if your video title is damaged and / or cannot be analyzed by the underlying codecs that OpenCV uses, these numbers may be different.

0

get() CAP_PROP_FRAME_COUNT ! opencv. :

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 that it will first consider 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 the frame number than direct video decoding. Opencv made a rough estimate get_duration_sec() * get_fps() + 0.5, which, of course, does not mean accuracy.

Thus, in order to get the correct frame number, you must decode and read the entire stream, or you must ask the video generator to generate the correct stream header with a field nb_frames.

0
source

Source: https://habr.com/ru/post/1598344/


All Articles