OpenCV之视频文件编解码 ---20170811

时间:2025-03-15 08:14:28
#include "opencv2/core/"
#include ""
#include <iostream>
#include <>
using namespace cv;
using namespace std;


class videoHandler{
public:
	static int playVideo(const string& filename){
		VideoCapture capture(filename);
		if (!()){
			cout << "Error : video loaded failed" << endl;
			return 0;
		}
		double rate = (CV_CAP_PROP_FPS);//获取帧率
		Mat frame;
		int delay = 1000 / rate;


		while ((frame))
		{
			imshow("this is my girl", frame);
			waitKey(delay);
		}
		();
		return 1;
	}


	static int showCamera(){
		VideoCapture capture(0);
		if (!()){
			cout << "Error : camera loaded failed" << endl;
			return 0;
		}
		Mat frame;

		//----------这里有个坑,由于摄像头加载需要时间,所以务必要确保摄像头完全开启,再执行下面的动作
		//摄像头延迟加载
		while (true)
		{
			if ((frame))
				break;
			Sleep(10);
		}

		Size size((CV_CAP_PROP_FRAME_WIDTH), (CV_CAP_PROP_FRAME_HEIGHT));
		//----------这里有个坑,直接获取摄像头的帧率都是0,会导致保存下来的文件是空
		VideoWriter write("", CV_FOURCC('D', 'I', 'V', 'X'), 20, size);
		if (!())
		{
			cout << "Error : fail to open video writer\n" << endl;
			return -1;
		}
		//逐帧读取视频
		while ((frame))
		{
			imshow("load camera video", frame);
			(frame);//CV_WRAP virtual void write(const Mat& image);
			if (waitKey(30) == VK_ESCAPE){//如果用户输入esc,就退出摄像头录制
				break;
			}
		}
		cout << "Success :  saved successfully..." << endl;
		();
		();
		return 1;
	}
};