简体   繁体   中英

Frame Extraction Only few seconds in the beginning of video file using OpenCV

Following my previous question , 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();
}

And advice ? Thanks.

It seems like you already know the FPS of the video. So isn't it just a matter of counting how many frames you have extracted and breaking after you reach FPS * 2?

double fps = cap.get(CV_CAP_PROP_FPS); 
int framesToExtract = fps * 2;
for (int frames = 0; frames < framesToExtract; ++frames)
{
    ... // your processing here
}

Also, I looked at your previous question and it seems like you have a misunderstanding of FPS?

FPS = Frames Per Second, this means how many frames there are every second of the video. So let's say your video is 120 FPS. This means there are 120 frames in one second of video, 240 in two seconds and so on.

So (VIDEO_FPS * x) gets you the amount of frames in x seconds of the video.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM