2

如何在 opencv 中仅录制 30 秒的视频。我使用了下面的代码,但它只录制了 24 秒的视频?问题是什么?

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/contrib/contrib.hpp"
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <time.h>

using namespace cv;
using namespace std;

int ex = 1734701162;

int main( int argc, const char** argv )
{

    VideoCapture cap(0);
    int i_fps = 15;
    time_t start = time(0);

    string OutputVideoPath = "output.mov";
    VideoWriter outputVideo(OutputVideoPath, ex, i_fps, Size(640,480), true);


    if(!cap.isOpened())  {
        cout << "Not opened" << endl; // check if we succeeded
        return -1;
    }

    while ( 1 ) {

        Mat frame;
        cap >> frame;
        outputVideo << frame;
        if ( difftime( time(0), start) == 30) break;

    }

    outputVideo.release();
    cap.release();


    return 0;
}
4

1 回答 1

11

2 things here:

  1. You're checking the walltime. difftime returns a double, so it's highly unlikely that you ever get exactly 30 as the outcome. Make it like this instead:
    if ( difftime( time(0), start) >= 30) break;

  2. You specify 15fps for the VideoWriter, but the time you measure is the time spent playing (and writing) the video. (that's totally arbitrary)

If your input video was recorded with a different framerate than 15fps, you've got to take care of that ratio yourself by either dropping or duplicating frames.

You might be better off counting frames and stopping if you reach 30 * 15.

于 2013-05-22T14:38:04.297 回答