Ask Your Question
1

Extract only few seconds in the beginning of video file

asked 2018-07-09 20:41:07 -0600

raisa_ gravatar image

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 = cap.read(frame); 

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

    return 0;

}

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

Any advice ?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-07-09 21:51:55 -0600

sjhalayka gravatar image

You need to read in a certain number of frames. Like this:

#pragma comment(lib, "opencv_world340.lib")

#include <opencv2/opencv.hpp>
using namespace cv;

#include <iostream>
#include <vector>
using namespace std;


int main(void)
{
    VideoCapture vid_in;
    vid_in.open("test.avi");

    long unsigned int fps = static_cast<long unsigned int>(vid_in.get(CV_CAP_PROP_FPS));
    long unsigned int seconds = 3;
    long unsigned int total_frames = fps*seconds;

    vector<Mat> mat_vector;

    for (long unsigned int i = 0; i < total_frames; i++)
    {
        Mat frame;
        vid_in >> frame;

        if (frame.empty())
        {
            cout << "Frame read error" << endl;
            return 0;
        }

        mat_vector.push_back(frame);
    }

    cout << mat_vector.size() << endl;

    return 0;
}
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2018-07-09 20:41:07 -0600

Seen: 2,047 times

Last updated: Jul 09 '18