Contents
  1. 1. How to Read from a Camera
  2. 2. Saving Video

1. How to Read from a Camera

  In image processing, reading and processing video is essential. In OpenCV, the main function used to read camera video is capture().   ① Constructors of the VideoCapture class:

VideoCapture::VideoCapture()
VideoCapture::VideoCapture(const string& filename)
VideoCapture::VideoCapture(int device)

  ② Function for reading camera video:


VideoCapture& capture.read(Mat& image)

This function captures each video frame and returns the frame just captured. If no video frame is captured, it returns false.      An example program for reading camera video is shown below:

void MyDemo::video_Demo(Mat& image) {
	VideoCapture capture(0);	//创建VideoCapture类
	Mat frame;					//定义Mat对象用于存储每一帧数据
	while (true) {
		capture.read(frame);	//逐帧读取视频
		flip(frame, frame, 1);	//将读取的视频左右反转
		if (frame.empty()) {	//如果视频结束或未检测到摄像头则跳出循环
			break;
		}
		imshow("Video", frame);	//每次循环显示一帧图像
		char k = waitKey(10);	//两帧读取的间隔时间
		if (k == 'q') {			//按下q键退出循环
			break;
		}
	}
	capture.release();			//释放视频
}

2. Saving Video

  Video is saved using the VideoWriter class. Its class properties and methods are as follows:

bool open(
	const string& 	filename,		//文件路径
	int 			fourcc,			//四个字符用来表示压缩帧的codec
	double 			fps,			//被创建视频流的帧率
	Size 			frameSize,		//视频流的大小
	bool 			isColor=true	//True则每一帧为彩色图,否则为灰度图
);

The available encoding-format options for fourcc are as follows:

ParameterEncoding format
CV_FOURCC(‘P’,‘I’,‘M’,‘1’)MPEG-1
CV_FOURCC(‘M’,‘J’,‘P’,‘G’)motion-jpeg
CV_FOURCC(‘M’, ‘P’, ‘4’, ‘2’)MPEG-4.2
CV_FOURCC(‘D’, ‘I’, ‘V’, ‘3’)MPEG-4.3
CV_FOURCC(‘D’, ‘I’, ‘V’, ‘X’)MPEG-4
CV_FOURCC(‘U’, ‘2’, ‘6’, ‘3’)H263
CV_FOURCC(‘I’, ‘2’, ‘6’, ‘3’)H263I
CV_FOURCC(‘F’, ‘L’, ‘V’, ‘1’)FLV1
-1Displays a codec selection dialog box

Program for saving camera video:

void MyDemo::video_Demo(Mat& image) {
	VideoCapture capture(0);	//创建VideoCapture类
	int frame_width = capture.get(CAP_PROP_FRAME_WIDTH);	//获取摄像头的宽、高
	int frame_height = capture.get(CAP_PROP_FRAME_HEIGHT);

	VideoWriter writer;		//创建VideoWriter类
	int fourcc = writer.fourcc('D', 'I', 'V', 'X');	//定义编码格式
	writer.open("E:/Program/OpenCV/vcworkspaces/opencv_452/img/test.mp4", fourcc, 30, Size(frame_width, frame_height), true);	//保存视频

	Mat frame;					//定义Mat对象用于存储每一帧数据
	while (capture.isOpened()) {
		capture.read(frame);	//逐帧读取视频
		flip(frame, frame, 1);	//将读取的视频左右反转
		if (frame.empty()) {	//如果视频结束或未检测到摄像头则跳出循环
			break;
		}
		writer.write(frame);
		imshow("Video", frame);	//每次循环显示一帧图像
		char k = waitKey(33);	//两帧读取的间隔时间 1s/30fps=33ms
		if (k == 'q') {			//按下q键退出循环
			break;
		}
	}
	capture.release();			//释放视频
	writer.release();
}

Saving Video