Opencv学习获取视频每一帧
目的:将视频逐帧提取保存在本地。涉及到一个保存图片名的问题,关键是用sprintf函数将图片文件名组装。
函数细节:
int sprintf( char *buffer, const char *format, [ argument] … ) ;
cvSaveImage( const char* filename, const CvArr* image, const int* params CV_DEFAULT(0) );
实现代码:
#include"stdafx.h"
#include
#include
int main()
{
CvCapture* capture =cvCaptureFromFile("c:\\testv.avi");
IplImage* image=NULL;
//char* savepath=NULL;
char savepath[100];
int i=0;
if(capture)
{
while(1)
{
image=cvQueryFrame(capture);
if(image)//不加这个if判断的话,所有保存完毕后跳出一个报错窗口,因为所有帧读完后image指针为NULL,进行后续操作就出问题了
{
i++;
printf("i=%d\n",i);
sprintf(savepath,"c:\\frame\\%d.jpg",i);
cvSaveImage(savepath,image);
}
else//只有if判断而此处不加else选项则所有帧读取完后会进行死循环
{
return 0;
}
}
}
}
Ok,让我们尝试用另外一种定义savepath的方式,用char*来定义savepath时。。。。。。
int main()
{
CvCapture* capture =cvCaptureFromFile("c:\\testv.avi");
IplImage* image=NULL;
char* savepath;
savepath=new char[100];//用char* savepath=NULL代替该句和上句时,则会报错,因为没有分配内存空间
int i=0;
if(capture)
{
while(1)
{
image=cvQueryFrame(capture);
if(image)//不加这个if判断的话,所有保存完毕后跳出一个报错窗口,因为所有帧读完后image指针为NULL,进行后续操作就出问题了
{
i++;
printf("i=%d\n",i);
sprintf(savepath,"c:\\frame\\%d.jpg",i);
cvSaveImage(savepath,image);
}
else//只有if判断而此处不加else选项则所有帧读取完后会进行死循环
{
free(savepath);
return 0;
}
}
}
}