摘自:http://www.aiseminar.cn/bbs/thread-325-1-1.html
1 从视频序列获得一帧
OpenCV支持从摄像头或视频文件(AVI)中获取图像,方法如下。
摄像头采集初始化:
- CvCapture* capture = cvCaptureFromCAM(0); //从视频设备#0采集
- CvCapture* capture = cvCaptureFromAVI("infile.avi");
- IplImage* img = 0;
- if (! cvGrabFrame(capture)) { //采集一帧
- printf("Could not grab a frame/n/7");
- exit(0);
- }
- img = cvRetrieveFrame(capture); //提取采集到的帧
释放采集源:
- cvReleaseCapture(&capture);
2 获得或设置帧信息
获得采集设备属性:
- cvQueryFrame(capture); // 此调用是获得正确的采集属性所必需的
- 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);
获得帧信息:
- float posMsec = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_MSEC);
- int posFrames = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES);
- float posRatio = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO);
3 保存到视频文件
初始化视频写对象:
- CvVideoWriter* writer = 0;
- int isColor = 1;
- int fps = 25; // 或30
- int frameW = 640; // 744 for firewire cameras
- int frameH = 480; // 480 for firewire cameras
- writer = cvCreateVideoWriter("out.avi", CV_FOURCC('P', 'I', 'M', '1'), fps, cvSize(frameW, frameH), isColor);
- CV_FOURCC('P','I','M','1') = MPEG-1 codec
- CV_FOURCC('M','J','P','G') = motion-jpeg codec (does not work well)
- CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
- CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
- CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
- CV_FOURCC('U', '2', '6', '3') = H263 codec
- CV_FOURCC('I', '2', '6', '3') = H263I codec
- CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec
写视频文件:
- IplImage* img = 0;
- int nFrames = 50;
- for (i = 0; i < nFrames; i++) {
- cvGrabFrame(capture); // 采集一帧
- img = cvRetrieveFrame(capture); // 提取获得帧
- cvWriteFrame(writer, img); // 加入此帧到文件
- }
- cvShowImage("mainWin", img);
- key = cvWaitKey(20); // 等待20ms
释放视频写对象:
- cvReleaseVideoWriter(&writer);
PS:Introduction to Programming with OpenCV : http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/index.html