【Opencv笔记】利用VideoCapture和VideoWriter函数读取和写入视频文件

本程序旨在使用电脑默认摄像头作为捕捉设备,来抓取帧,并进行图像处理。将处理后的视频帧作为一个新的文件保存。

同时创建两个窗口同时显示原始帧和处理过的帧。代码如下:

之前一直报错,看网上教程,尝试了很多解决办法,包括加载Microsoft符号库、修改写入的方式MP42 MJPG等,都是不行,最后发现是对读取的视频帧进行灰度化的时候,参数选择错误,注意是COLOR_BGR2GRAY而不是Bayer2GRAY. Opencv默认的通道是BGR。

#include <iostream>
#include <opencv2/opencv.hpp>


using namespace std;
using namespace cv;


int main(int,char **)
{
	Mat in_frame, out_frame;
	const char win1[] = "Grabbing...", win2[] = "Recording...";
	double fps = 30;
	char file_out[] = "recorded.avi";


	VideoCapture cap(0); //打开默认摄像机,videocapture函数还可以用来打开视频文件:VideoCapture(const string &filename)
	if (!cap.isOpened())
	{
		cout << "Can not open a capture object." << endl;
		return -1;
	}


	//获取输入视频每一帧的宽度和高度
	int width =(int)cap.get(CAP_PROP_FRAME_WIDTH);
	int height =(int)cap.get(CAP_PROP_FRAME_HEIGHT);
	VideoWriter recVid(file_out, VideoWriter::fourcc('M', 'P', '4', '2'), fps, Size(width, height));
	 // MSVC是微软视频,仅可在Windows上解码使用,还可选择MJPG,PIM1,FLV1等
	if (!recVid.isOpened())
	{
		cout << "Error!Video File is not open...\n";
		return -1;
	}
	namedWindow(win1);
	namedWindow(win2);
	while (true)
	{
		cap >> in_frame;   // 读取视频的每一帧
		cvtColor(in_frame, out_frame, COLOR_BGR2GRAY);
		recVid << out_frame; // 将转换后的灰度图写入视频文件
		imshow(win1, in_frame);
		imshow(win2, out_frame);
		if (waitKey(1000/fps) >= 0)
			break;
	}
	cap.release();
	return 0;
}


VideoCapture函数不仅可以打开摄像头,还可以读取视频文件VideoCapture(const string &filename)


猜你喜欢

转载自blog.csdn.net/lukaslong/article/details/53672126