Reputation: 5023
How to record a video in opencv only for 30 seconds. I used the below code but it records video only for 24 seconds? What is the issue?
#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;
}
Upvotes: 2
Views: 2048
Reputation: 39806
2 things here:
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;
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
.
Upvotes: 11