C++OPencv视频文件处理使用

1.视频读取

cv::VideoCapture capture(const string& filename); // 从视频文件读取
文件(.MPG或.AVI格式)中读取视频,**对象创建以后,OpenCV将会打开文件并做好准备读取它,如果打开成功,
我们将可以开始读取视频的帧,并且cv::VideoCapture的成员函数isOpened()将会返回true

2.视频保存

VideoWriter  video_writer;
video_writer.open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true);

参数意义:
filename:保存文件名称及路径;
fourcc:表示压缩帧的codec,一般用CV_FOURCC(‘M’,‘J’,‘P’,‘G’) = motion-jpeg codec;
fps:表示帧率,可用video_writer.get(CV_CAP_PROP_FPS);
frameSize:保存的视频大小;

示例代码:

void video_demo(Mat &image) {
	VideoCapture capture(0);  //读取摄像头,读取视频文件直接把0改为视频路径
	int frame_width = capture.get(CAP_PROP_FRAME_WIDTH);  //宽度
	int frame_height = capture.get(CAP_PROP_FRAME_HEIGHT);  //高度
	int count = capture.get(CAP_PROP_FRAME_COUNT);       //总的帧数
	double fps = capture.get(CAP_PROP_FPS);    //  每秒播放多少帧
	cout << "fps:" << fps << endl;
	//capture.get(CAP_PROP_FOURCC);  //视频编码方式
	//创建写入对象
	VideoWriter writer("D:/test.mp4", capture.get(CAP_PROP_FOURCC), fps, Size(frame_width, frame_height), 
		true);
	Mat frame;
	while (true)
	{
		capture.read(frame); //读取方式一
		//capture >> frame;  //读取方式二  
		flip(frame, frame, 1);  //镜像翻转
		if (frame.empty())
		{
			break;
		}
		imshow("frame", frame);
		writer.write(frame);
		int c = waitKey(50);
		if (c == 27) {
			break;
		}
	}
	//释放资源
	capture.release();
	writer.release();
}

void test1701()
{
	Mat image = imread("C:/Users/86156/Pictures/Saved Pictures/cwt.jpg");
	//imshow("图像", image);
	video_demo(image);
	waitKey(0);
}


int main()
{
	test1701();
	system("pause");
}

你可能感兴趣的:(Opencv(C++),opencv,c++,人工智能)