NewLearner
NewLearner

Reputation: 53

How to select two frames from a video? opencv c++

I want to select two frames from a video. The following is my code, but it can only select the first frame. Could someone help me? Thanks~

long frameOne = 2130;
long frameTwo = 2160;
long currentFrame = frameOne;
bool stop = false;
while(!stop)
{
    if(!capture.read(frame))
    {
        cout << "Failed to read the video!" << endl;
        return -1;
    }

    // select the first image
    if(currentFrame == frameOne)
    {
        frame1 = frame;
    }
    if(currentFrame == frameTwo)
    {
        frame2 = frame;
    }

    if(currentFrame>frameTwo)
    {
          stop = true;
    }
    currentFrame++;
}

Upvotes: 1

Views: 1180

Answers (2)

Algold
Algold

Reputation: 1003

If you just need to get the frames without watching the video you can just jump to the frame you are looking for with:

cv::Mat frame,frame1,frame2; 
capture = cv::VideoCapture(videoFname);
if( !capture.isOpened( ) ) 
{
    std::cout<<"Cannot open video file";
    exit( -1 );
}
capture.set(CV_CAP_PROP_POS_FRAMES,frameOne);
capture >> frame;
frame1 = frame.clone();
capture.set(CV_CAP_PROP_POS_FRAMES,frameTwo);
capture >> frame;
frame2 = frame.clone();

It works with OpenCV 2.4.6, I am not sure for previous versions.

Upvotes: 1

OpenMinded
OpenMinded

Reputation: 1175

The problem here is that

long currentFrame = frameOne;

should be

long currentFrame = 1;

Code:

long frameOne = 2130;
long frameTwo = 2160;
long currentFrame = 1;
bool stop = false;
while(!stop)
{    

    if(!capture.read(frame))
    {
        cout << "Failed to read the video!" << endl;
        return -1;
    }

    // select the first image
    if(currentFrame == frameOne)
    {
        // it needs a deep copy, since frame points to the static capture mem
        frame1 = frame.clone();
    }
    if(currentFrame == frameTwo)
    {
        frame2 = frame.clone();
    }

    if(currentFrame>frameTwo)
    {
          stop = true;
    }
    currentFrame++;
}

Upvotes: 3

Related Questions