Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Extract only few seconds in the beginning of video file

I want to extract frames from a video. But only 2 seconds at the beginning of the video. I want to work with raw video as much as I can, that why I don't want to cut the original video and then process it.

Here's my code to extract frame. But this will extract all frame from the video :

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
#include <sstream>

using namespace cv;
using namespace std;
int c = 0;
string int2str(int &);

int main(int argc, char **argv) {
    string s;

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

    double fps = cap.get(CV_CAP_PROP_FPS); 

    cout << "Frame per seconds : " << fps << endl;

    namedWindow("MyVideo", CV_WINDOW_NORMAL); 
    resizeWindow("MyVideo", 600, 600);
    while (1)
        Mat frame;
        Mat Gray_frame;
        bool bSuccess =; 

        if (!bSuccess) 
            cout << "Cannot read the frame from video file" << endl;
        s = int2str(c);
        //cout<<("%d\n",frame )<<endl;
        imshow("MyVideo", frame); 
        imwrite("frame" + s + ".jpg", frame);
        if (waitKey(30) == 27) 
            cout << "esc key is pressed by user" << endl;

    return 0;


string int2str(int &i) {
    string s;
    stringstream ss(s);
    ss << i;
    return ss.str();

Any advice ?