OpenCV Seek Function/Rewind

Cenoc picture Cenoc · Jun 4, 2010 · Viewed 30.6k times · Source

I've been trying to find/implement a seek and rewind function (for video (.avi)) using OpenCV in C++, but I cant find a way of doing it, other than going through the entire file once and saving each image. Is there any other way?

Any help would be much appreciated; Thanks ahead of time!

Answer

Adi picture Adi · Jun 5, 2010

Using cvSetCaptureProperty() you can cycle through frames, either in miliseconds or by ordinal frame number.

int cvSetCaptureProperty( CvCapture* capture, int property_id, double value );

property_id is a property you would need to use. It can be one of the following:

  1. CV_CAP_PROP_POS_MSEC - position in milliseconds from the file beginning
  2. CV_CAP_PROP_POS_FRAMES - position in frames
  3. CV_CAP_PROP_POS_AVI_RATIO - position in relative units (0 - start of the file, 1 - end of the file)
  4. CV_CAP_PROP_FRAME_WIDTH - width of frames in the video stream (only for cameras)
  5. CV_CAP_PROP_FRAME_HEIGHT - height of frames in the video stream (only for cameras)
  6. CV_CAP_PROP_FPS - frame rate (only for cameras)
  7. CV_CAP_PROP_FOURCC - 4-character code of codec (only for cameras).

The first two is of your interest.

EDIT: more info :)

You can cycle through frames just by repeatedly calling the mentioned function with various frame indices.

cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, frameIndex);

Example:

IplImage*  frame;
CvCapture* capture = cvCreateFileCapture("test.avi");

/* iterate through first 10 frames */
for (int i = 0; i < 10; i++)
{
   /* set pointer to frame index i */
   cvSetCaptureProperty(capture, CV_CAP_POS_FRAMES, i);

   /* capture the frame and do sth with it */
   frame = cvQueryFrame(capture);
}

You could put similar code to execute each time user clicks a button to forward/rewind the video.

The C++ method (OpenCV 2 and higher) would be to use this method instead with the same property_id and value.

bool VideoCapture::set(int property_id, double value)