Ask Your Question
0

OpenCV move to begin frame position fail

asked 2014-05-02 22:51:05 -0600

hackcv gravatar image

updated 2014-05-02 22:51:50 -0600

I am trying to use OpenCV VideoCapture to read some frames for training. After training, I would like to return to the beginning of the video and do processing. The problem is that OpenCV VideoCapture set(CV_CAP_PROP_POS_FRAMES, 0) cannot return to the beginning of the video.

VideoCapture cap("video1.mp4");
if( !cap.isOpened()){
    cout << "Cannot open the video file" << endl;
    return -1;
}

// read some frames here

int count = cap.get(CV_CAP_PROP_FRAME_COUNT); //get total frame count
cap.set(CV_CAP_PROP_POS_FRAMES, 0); //Set index to 0 (start frame)

int index = 1;
while(1)
{
   Mat frame;
   bool success = cap.read(frame);
   if (!success){
     cout << "Cannot read  frame " << endl;
     break;
   }
   cout << "the current frame: " << index << endl;
   index++;
}

In the program, the final index value would not be same as frame count. Say a sample running would be:

index = 3774 and count = 3786
index = 3764 and count = 3776

I also try to set frame index using CV_CAP_PROP_POS_MSEC (according to a post). But it didn't work.

My current solution is to reconstruct a VideoCapture and read from begin to end. Can anyone explain why set can even not return to the beginning of the video? I think it go nothing to do with the decompression algorithm.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2014-05-04 07:05:47 -0600

AR0x7E7 gravatar image

For me its working (remember videos are 0-based indexed):

using namespace std;
using namespace cv;


int main() {
    VideoCapture cap("test.mp4");
    if( !cap.isOpened()){
        cout << "Cannot open the video file" << endl;
        return -1;
    }

int count = (int) cap.get(CV_CAP_PROP_FRAME_COUNT); //get total frame count
cout<< "Max frames: "<< count << endl;

Mat frame;
int index = 0;
while(cap.read(frame))
{
    cout << "the current frame: " << index << endl;
    index++;
}
cout << "exit first loop" << endl;
cap.set(CV_CAP_PROP_POS_FRAMES, 0); //Set index to 0 (start frame)
int index2 = 0;
while(cap.read(frame))
{
    cout << "the current frame: " << index2 << endl;
    index2++;
}
cout << "exit second loop" << endl;
cout << "index1: "<< index << " / index2: "<< index2 <<endl;
}

Output (see attached mp4 file C:\fakepath\test.mp4.jpg for own test, rename it to .mp4 ;-) ):

Max frames: 145
..
index1: 145 / index2: 145
edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-05-02 22:51:05 -0600

Seen: 4,650 times

Last updated: May 04 '14