Opencv中VideoCapture是专门用来处理视频文件或者摄像头视频流的类,详细的说明和用法可以参考Opencv2.4.13的说明文档:点击打开链接
使用VideoCapture打开内置摄像头的例子:
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> using namespace cv; int main(int argc,char *argv[]) { VideoCapture cap(0);//打开默认的摄像头 if(!cap.isOpened()) { return -1; } Mat frame; bool stop = false; while(!stop) { cap.read(frame); // 或cap>>frame; imshow("Video",frame); if(waitKey(30)==27) //Esc键退出 { stop = true; } } return 0; } 效果图(拍摄了一张明信片):
VideoCapture cap(0)中参数0代表默认的摄像头的ID,一般内置摄像头是系统默认的摄像头,通过Mat类型的frame获取到摄像头的输入流之后就可以对每一幅frame做一常规的图像处理工作了。
下边这个例子生成一个大小为原图像三分之一的图像,并叠加后输出:
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> using namespace cv; int main(int argc,char *argv[]) { VideoCapture cap(0);//打开默认的摄像头 if(!cap.isOpened()) { return -1; } Mat frame; //接收视频输入流 Mat embedFrame; cap.read(frame); // 或cap>>frame; int hight=frame.rows; int width=frame.cols; embedFrame=Mat::ones(Size(width/3,hight/3),CV_8UC3); bool stop = false; while(!stop) { cap.read(frame); // 或cap>>frame; for(int i=0;i<embedFrame.rows;i++) { for(int j=0;j<embedFrame.cols;j++) { embedFrame.at<Vec3b>(i,j)[0]=frame.at<Vec3b>(i*3,j*3)[0]; embedFrame.at<Vec3b>(i,j)[1]=frame.at<Vec3b>(i*3,j*3)[1]; embedFrame.at<Vec3b>(i,j)[2]=frame.at<Vec3b>(i*3,j*3)[2]; } } Mat roi=frame(Rect(0,0,embedFrame.cols,embedFrame.rows)); addWeighted(roi,0,embedFrame,1,0,roi,-1); imshow("Video",frame); if(waitKey(30)==27) //Esc键退出 { stop = true; } } return 0; }
效果(拍摄的另一张明信片):
右上角有一个小窗,是原图大小的三分之一。
记录一下VideoCapture类中最常用的Get和Set方法的参数含义:
bool VideoCapture::set(int propId, double value) 和 double VideoCapture::get(int propId)
propId取值:
CV_CAP_PROP_POS_MSEC 视频当前点的毫秒值或视频捕捉的时间戳
CV_CAP_PROP_POS_FRAMES 下次将被捕获的0基索引的帧 CV_CAP_PROP_POS_AVI_RATIO 视频文件的相关位置: 0 - start of the film, 1 - end of the film. CV_CAP_PROP_FRAME_WIDTH 视频流帧的宽度 CV_CAP_PROP_FRAME_HEIGHT 视频流帧的高. CV_CAP_PROP_FPS 帧率. CV_CAP_PROP_FOURCC 4字符编码的编码器. CV_CAP_PROP_FRAME_COUNT 视频文件的帧数. CV_CAP_PROP_FORMAT 由retrieve()返回矩阵对象的格式 . CV_CAP_PROP_MODE 后端指定值指示当前捕捉的模式. CV_CAP_PROP_BRIGHTNESS 图像亮度 (只对摄像头). CV_CAP_PROP_CONTRAST 图像对比度 (only for cameras). CV_CAP_PROP_SATURATION 图像饱和度 (only for cameras). CV_CAP_PROP_HUE 色调 (only for cameras). CV_CAP_PROP_GAIN 增益(only for cameras). CV_CAP_PROP_EXPOSURE 曝光(only for cameras). CV_CAP_PROP_CONVERT_RGB 布尔型标记图像是否应该被转换为RGB. CV_CAP_PROP_WHITE_BALANCE 白平衡(目前不支持) CV_CAP_PROP_RECTIFICATION 立体相机的矫正标记(note: only supported by DC1394 v 2.x backend currently)