OpenCV capture loops video/Does not detect last fr

2020-07-22 19:02发布

问题:

I am capturing an avi file and processing it. My code has worked for sometime without problem but now it does not seem to stop after the last frame of the video is captured. Instead it keeps looping back to the beginning of the video. I do not understand why this is happening and I can not think of anything changing with regards to Eclipse or OpenCV. I have tried the same code on my Ubuntu pc with the same video and it works without problems. I have even tried as much as reinstalling the OS and apps without success.

Sample code:

#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;



int main(int argc, char** argv)
{
Mat frame;
VideoCapture capture;
const string inputVideo = argv[1];


char buff[PATH_MAX];
getcwd( buff, PATH_MAX );
std::string fileName( buff );
fileName.append("/");
fileName.append(inputVideo);


capture.open(inputVideo);

while(true)
{
    capture >> frame;

    if(!frame.empty())
    {
        imshow("frame", frame);
    }
    else
    {
        printf(" --(!) No captured frame -- Break!");
        break;
    }

    int key = waitKey(10);
    if((char)key == 'c')
    {
        break;
    }
}

return 0;
}

I am running this on a Mac OS X (10.8.2), Eclipse Juno, and OpenCV 2.4.3.

Any advice or comments are appreciated. Thanks in advance

回答1:

The solution that I used was posted as a comment by @G B. I am creating a solution so that it may be marked as one.

I used capture.get(CV_CAP_PROP_POS_FRAMES) before and after frame grabbing, if the value "after" is less than the value "before", then I've reached the end of the video.



回答2:

Get the frame count like below,

int frameCnt = capture.get(CV_CAP_PROP_FRAME_COUNT);

And check to exit the loop when the frame count exceeds..