我是OpenCV的初学者,我希望在OpenCV中播放视频。我做了一个代码,但它只显示一个图像。我使用的是OpenCV 2.1和Visual Studio 2008。如果有人指引我哪里走错了,我会非常感激。下面是我粘贴的代码:
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
int main()
{
CvCapture* capture = cvCaptureFromAVI("C:/OpenCV2.1/samples/c/tree.avi");
IplImage* img = 0;
if(!cvGrabFrame(capture)){ // capture a frame
printf("Could not grab a framen7");
exit(0);}
cvQueryFrame(capture); // this call is necessary to get correct
// capture properties
int frameH = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
int frameW = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
///numFrames=total number of frames
printf("Number of rows %dn",frameH);
printf("Number of columns %dn",frameW,"n");
printf("frames per second %dn",fps,"n");
printf("Number of frames %dn",numFrames,"n");
for(int i=0;i<numFrames;i++)
{
IplImage* img = 0;
img=cvRetrieveFrame(capture);
cvNamedWindow( "img" );
cvShowImage("img", img);
}
cvWaitKey(0);
cvDestroyWindow( "img" );
cvReleaseImage( &img );
cvReleaseCapture(&capture);
return 0;
}
您必须使用cvQueryFrame
而不是cvRetrieveFrame
。正如@Chipmunk指出的那样,你必须在cvShowImage
之后添加延迟。
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
cvNamedWindow( "img" );
for(int i=0;i<numFrames;i++)
{
IplImage* img = cvQueryFrame(capture);
cvShowImage("img", img);
cvWaitKey(10);
}
下面是使用OpenCV播放视频的完整方法:
int main()
{
CvCapture* capture = cvCreateFileCapture("C:/OpenCV2.1/samples/c/tree.avi");
IplImage* frame = NULL;
if(!capture)
{
printf("Video Not Openedn");
return -1;
}
int width = (int)cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_WIDTH);
int height = (int)cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_HEIGHT);
double fps = cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
int frame_count = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
printf("Video Size = %d x %dn",width,height);
printf("FPS = %fnTotal Frames = %dn",fps,frame_count);
while(1)
{
frame = cvQueryFrame(capture);
if(!frame)
{
printf("Capture Finishedn");
break;
}
cvShowImage("video",frame);
cvWaitKey(10);
}
cvReleaseCapture(&capture);
return 0;
}
在窗口上显示图像后,必须延迟或等待下一个图像才能显示,我想你可以猜到为什么会这样。对于延迟,我们用cvWaitKey()
。这就是我在循环代码中添加的内容。
cvNamedWindow( "img" );
for(int i=0;i<numFrames;i++)
{
IplImage* img = 0;
img=cvRetrieveFrame(capture);
cvShowImage("img", img);
cvWaitKey(10);
}