Search code examples
videoopencvsampling

Select from a video stream all images separated by a given sampling interval OPENCV


I'm using OpenCV for a project, but am a total beginner.

I have a video file on my mass storage repository, and want to write a method to access all the frames of the video stream that are separated by a given sampling interval in input.

Videos can be in multiple formats (AVI – WMV – MPEG-2 – MPEG-4).

I was thinking that the method should work like this:

1. Have as input a desired sampling interval
2. Access the video at timestamp corresponding to the sampling interval
3. Save selected frame of video as an image
4. Go to next frame as determined from sampling frequency.

Can you please help me providing some code, or at least indications on a way to implement such a method with OpenCV methods?


Solution

  • You can take a look at VideoCapture::set method and use CV_CAP_PROP_POS_MSEC to get specific frames from the video file. Although I didn't tested this code, it would be something like this:

    cv::VideoCapture vc(video_file_name);
    cv::Mat frame;
    
    //How you will get the interval is up to you
    float interval = getInterval();
    float cur_interval = 0;
    
    while(1)
    {
       vc.set(CV_CAP_PROP_POS_MSEC, cur_interval);
    
       //The operator>> will return a NULL pointer if the next frame isn't valid
       if(vc >> frame)
         cv::imwrite("filename.jpg", frame);
       else
         break;
    
       cur_interval += interval;
    }