opencv / opencv

Open Source Computer Vision Library
https://opencv.org
Apache License 2.0
79.46k stars 55.86k forks source link

Python cv2.VideoCapture.read() does not read all frames #4362

Closed opencv-pushbot closed 5 months ago

opencv-pushbot commented 9 years ago

Transferred from http://code.opencv.org/issues/1938

|| Dmitry Kit on 2012-05-15 16:14
|| Priority: Normal
|| Affected: None
|| Category: python bindings
|| Tracker: Bug
|| Difficulty: None
|| PR: None
|| Platform: None / None

Python cv2.VideoCapture.read() does not read all frames

I have some python code that tries to read all the frames from a video file (attached). However, using the following loop:
<pre>
g_capture = cv2.VideoCapture('fence.wmv')
ret = True
while ret:
   ret,im = g_capture.read()
   cv2.imshow("video", im)
   cv2.waitKey(2)
</pre>
results in only ~178 or so frames read before ret becomes False and things start failing. However, when I do:
<pre>
g_capture.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 201)
</pre>

I correctly get the frame 201. Furthermore the following C code works just fine:
<pre>
int main(int argc, char* argv[])
{
    CvCapture* capture = cvCaptureFromAVI("fence.wmv");

    IplImage* img = 0; 

    while(true) {
        if(!cvGrabFrame(capture)){              // capture a frame 
            printf("Could not grab a frame\n\7");
            cvWaitKey();
            exit(0);
        }

        img=cvRetrieveFrame(capture);           // retrieve the captured frame

        cvShowImage("mainWin", img); 
        cvWaitKey(20);           // wait 20 ms
    }
    cvReleaseCapture(&capture);
}
</pre>

I am using the svn version of opencv source code (from about 3 days ago) and I have tried to convert the original video to a supported avi format using the mencoder command found on http://opencv.willowgarage.com/wiki/VideoCodecs .

This bug might be a duplicate of http://code.opencv.org/issues/1690

History

Dmitry Kit on 2012-05-24 23:20
Realized I forgot to follow some instructions when I filed this bug:

The opencv build information is included below:
<pre>
General configuration for OpenCV 2.4.0 =====================================
Version control:                 svn:8335

  Platform:
    Host:                        Windows 6.1 x86
    CMake:                       2.8.8
    CMake generator:             Visual Studio 10
    CMake build tool:            /MICROS~1.0/Common7/IDE/devenv.com
    MSVC:                        1600

  C/C++:
    Built as dynamic libs?:      YES
    C++ Compiler:                cl
    C++ flags (Release):         /DWIN32 /D_WINDOWS /W4  /EHs /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE /arch:SSE2 /Oi /fp:fast /wd4251 /MP8  /MD /O2 /Ob2 /D NDEBUG   /Zi
    C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4  /EHs /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D_SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE /arch:SSE2 /Oi /fp:fast /wd4251 /MP8  /D_DEBUG /MDd /Zi /Ob0 /Od /RTC1
    C Compiler:                  cl
    C flags (Release):           /DWIN32 /D_WINDOWS /W3   /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE /arch:SSE2 /Oi /fp:fast   /MP8  /MD /O2 /Ob2 /D NDEBUG  /Zi
    C flags (Debug):             /DWIN32 /D_WINDOWS /W3   /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE /arch:SSE2 /Oi /fp:fast   /MP8  /D_DEBUG /MDd /Zi  /Ob0 /Od /RTC1
    Linker flags (Release):      /STACK:10000000 /machine:X86   /INCREMENTAL:NO /debug
    Linker flags (Debug):        /STACK:10000000 /machine:X86   /debug /INCREMENTAL

  OpenCV modules:
    To be built:                 calib3d contrib core features2d flann gpu highgui imgproc legacy ml nonfree objdetect photo python stitching ts video videostab

    Disabled by user:            world
    Disabled by dependency:      -
    Unavailable:                 androidcamera java

  GUI:
    QT 4.x:                      YES (ver 4.7.4 EDITION = OpenSource)
    QT OpenGL support:           YES (optimized /x32/qt/lib/QtOpenGL4.lib debug                   /x32/qt/lib/QtOpenGLd4.lib)
    OpenGL support:              YES (glu32 opengl32)

  Media I/O:
    ZLib:                        build (ver 1.2.6)
    JPEG:                        build (ver 62)
    PNG:                         build (ver 1.5.9)
    TIFF:                        build (ver 42)
    JPEG 2000:                   build (ver 1.900.1)
    OpenEXR:                     NO
    OpenNI:                      NO
    OpenNI PrimeSensor Modules:  NO
    XIMEA:                       NO

  Video I/O:                     DirectShow
    FFMPEG:                      YES (prebuilt binaries)
      codec:                     YES (ver 53.61.100)
      format:                    YES (ver 53.32.100)
      util:                      YES (ver 51.35.100)
      swscale:                   YES (ver 2.1.100)
      gentoo-style:              YES

  Other third-party libraries:
    Use IPP:                     NO
    Use TBB:                     YES (ver 4.0 interface 6004)
    Use Cuda:                    YES (ver 4.2)
    Use Eigen:                   NO
    Use Clp:                     NO

  NVIDIA CUDA:                   (ver 4.2)
    Use CUFFT:                   YES
    Use CUBLAS:                  YES
    NVIDIA GPU arch:             11 12 13 20 21 30
    NVIDIA PTX archs:            11 12 13 20 21 30
    NVIDIA GPU features:         11 12 13 20 20 30 20

  Python:
    Interpreter:                /Python27/python.exe (ver 2.7.2)
    Libraries:                   /Python27/libs/python27.lib (ver 2.7.2)
    numpy:                       /Python27/lib/site-packages/numpy/core/include (ver 1.6.1)
    packages path:               /Python27/Lib/site-packages

  Documentation:
    Build Documentation:         NO
    Sphinx:                      NO
    PdfLaTeX compiler:           /MiKTeX 2.9/miktex/bin/x64/pdflatex.exe

  Tests and samples:
    Tests:                       YES
    Performance tests:           YES
    Examples:                    NO

  Install path:                  /opencv_new/trunk/opencv/build32/install

  cvconfig.h is in:            /opencv_new/trunk/opencv/build32
-----------------------------------------------------------------
</pre>
ZhangXinNan commented 5 years ago

I have the same question. There is a video of 2 minutes, but frame is None after 1 minutes.

ThatAIGeek commented 5 years ago

Same issue

NathanWendt commented 5 years ago

Any update on this? I am having this issue now.

ItsByteMe commented 5 years ago

Yes, I found a fix for this, you need to convert the file to another file type before reading. I was using this to make a deep learning model that checked how long an object was in motion for. I used another library called ffmpy. The whole file is n my time measurer repo but you should have no troubles figuring it out from the snippet. (odds are this wont run if you just copy paste since I was lazy with making sure you only had what you needed)

import cv2
import time
import ffmpy

#file = "test2.mp4"

def convert(inputted_file):
    current_time = time.strftime("%Y%m%d-%H%M%S")
    video_name = str(current_time) + ".avi"
    ff = ffmpy.FFmpeg(inputs={inputted_file : None}, outputs={video_name: ' -c:a mp3 -c:v mpeg4'})
    ff.cmd
    ff.run()
    return video_name

def getFrame(current_frame, move_frame, col_frame, cap):
    cap.set(cv2.CAP_PROP_POS_MSEC,current_frame*1000)
    hasFrames,image = cap.read()
    return hasFrames

def checkTime(video_name):
    cap = cv2.VideoCapture(video_name)
    fps = cap.get(cv2.CAP_PROP_FPS)
    print(fps)
    frameRate = 0.01

    move_frame = 0
    col_frame = 0

    current_frame = 0
    count = 1
    success = getFrame(current_frame, move_frame, col_frame, cap)

    while success:
        count = count + 1
        current_frame = current_frame + frameRate
        success, move_frame, col_frame = getFrame(current_frame, move_frame, col_frame, cap)

    cap.release()
    cv2.destroyAllWindows()

    return move_frame, col_frame, fps

def tellTime(move_frame, col_frame, fps):
    col_frame -= 0.01
    seconds = ((col_frame - move_frame)*fps)
    col_mins = seconds // 60
    col_secs = seconds % 60
    result_message = ("{:02}:{:02}".format(col_mins, col_secs))
    print(result_message)
    return result_message

#vname = convert(file)
#move_frame, col_frame = checkTime(vname)
#time = tellTime(move_frame, col_frame)
ghost commented 3 years ago

lazy solution: load your *.mp4 file with VLC media player. Then chose "Covert/Save" from Media menu and at the bottom of that dialog choose "Convert" from drop down. In the Convert dialog export it to MPEG4 format selected from the "Profile" drop down.

Works with zero code and VLC is the video playback king so who doesn't already have it installed? ;)

CorbanSwain commented 1 year ago

I have the same issue; the .read() method is only reading about half the frames before returning None when reading from .avi file. Package version: opencv-python-headless v4.1.2.30