OpenCV videoInput.h Capture speed different than write speed
I am trying to write recording software that would write a video stream coming in the computer to an avi file. I am using OpenCV and accompanied videoInput.h to handle the directshow code. Just in case it matters I am using Visual Studio 2010 as a compiler.
The problem I am having is the recorded file plays faster than the previewed file. Not by alot, but just enough to be noticable. EXAMPLE: 10 second preview is roughly 7 second file so everyone moves just a little bit too fast.
if( bWriteVideo )
{
writer=cvCreateVideoWriter(szFileName,CV_FOURCC('D','I','V','X'),
fps,cvSize(width, height),isColor);
if( !writer ) return 1;
}
if( bDisplayVideo )
cvNamedWindow("video", 0);
while( key != 'q')
{
if(VI.isFrameNew(nSource))
{
VI.getPixels(nSource, yourBuffer1, false, true);
frame = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
frame->imageData = (char*)yourBuffer1;
frame->imageDataOrigin = frame->imageData;
if( !frame ) break;
// Display Image to Screen
if( bDisplayVideo )
cvShowImage( "video" , frame );
if( bWriteVideo )
cvWriteFrame( writer, frame 开发者_StackOverflow中文版);
}
key = cvWaitKey ( 1000 / fps );
}
Let's suppose the frames are coming in with 30 FPS. Your code does the following:
- if a new frame arrived, then save it and then wait 1000/fps ms (that's ~33.3 ms).
- if not... then just wait.
Let's suppose saving a frame takes 10ms. So one loop-run takes either 33.3 ms (no incoming frame) or 44.3 ms (if we had to save one). So we aren't going to save all of them (sometimes we'll have two incoming frames in a 44.3 ms period, but we save only one).
So the output video will have less than 30 frames per real second. If we play that with 30 FPS... that is faster than reality!
So try to avoid waiting a lot at the end of the loop. For example, by decreasing the amount of time the cvWaitKey calls take up. (For example, by replacing 1000 with 100.) The loop will run several times for every frame, waiting 3.3 milliseconds at a time, then checking for a new frame (and if there is one, saving it). That's 10 (saving) + 3.3 (waiting) ms in the worst case, so we won't miss any new frames during that time.
精彩评论