//使用OpenCV实现获取摄像头数据并毫秒级(在我的机上70ms左右保存一张,连续保存)保存成一张jpg图片,jpg图片的大小可调。
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<time.h>
#include <sys/timeb.h>
#include<stdlib.h>
#include<cv.h>
#include<cxcore.h>
#include<highgui.h>
int main( int argc,char ** argv )
{
//声明IplImage指针
IplImage* pFrame=NULL;
IplImage* pSaveFrame=NULL;
CvCapture* pCapture=NULL;
static char filename[40];
struct tm * tm_ptr;
struct timeb tp;
//创建窗口
cvNamedWindow("video",1);
//打开摄像头
if( !(pCapture=cvCaptureFromCAM(-1)) )
{
fprintf(stderr,"Can not open camera.\n");
return -1;
}
if(mkdir("./Alert",0755)==-1)
{
//创建时存在该目录会返回错误码,如不存在则创建它,但由于我们需要该目录,则出错也不处理
}
//逐帧读取视频
while(pFrame=cvQueryFrame(pCapture))
{
cvShowImage("video",pFrame);
if(cvWaitKey(2)>=0) break;
pSaveFrame=cvCreateImage(cvSize(320,240),pFrame->depth,pFrame->nChannels);
//get file name
ftime(&tp);
tm_ptr=localtime(&tp.time);
snprintf(filename, 40, "./Alert/%04d%02d%02d%02d%02d%02d%04d.jpg",tm_ptr->tm_year-100+2000, tm_ptr->tm_mon + 1, tm_ptr->tm_mday, tm_ptr->tm_hour,tm_ptr->tm_min, tm_ptr->tm_sec,tp.millitm);
cvResize(pFrame,pSaveFrame,CV_INTER_LINEAR);
cvSaveImage(filename,pSaveFrame);
cvReleaseImage(&pSaveFrame);
}
cvDestroyWindow("video");
cvReleaseCapture(&pCapture);
return 0;
} |