[小程序系列] C++ Opencv 视频格式转换

[小程序系列] C++ Opencv 视频格式转换

    • 引言
    • 代码
    • 参考文献

引言

小项目需求,需要对大一点的视频做格式转换,用一个小程序实现。

代码

执行文件 test.cpp。

#include 
#include 
#include 
#include 
#include 

int main(int argc, char ** argv){
	if (argc != 3) {
		std::cerr << "usage: main \n";
		return -1;
	}
	cv::VideoCapture video_cap(0);// default open camera
	if (std::string(argv[1]) != "0"){
		video_cap = cv::VideoCapture(argv[1]);
	}
	if (!video_cap.isOpened()) {
		std::cerr << "Unable to open video, Please enter the correct video path! \n";
		return -1;
	}
	std::cout << "video frame FPS:		" << video_cap.get(cv::CAP_PROP_FPS) << std::endl; 
	std::cout << "video frame width:	" << video_cap.get(cv::CAP_PROP_FRAME_WIDTH) << std::endl;
	std::cout << "video frame height:	" << video_cap.get(cv::CAP_PROP_FRAME_HEIGHT) << std::endl;

	cv::Mat video_image;		// define video image
	video_cap >> video_image;
	if (video_image.empty()) {
		std::cerr << "blank frame grabbed!\n";
		return -1;
	}
	bool is_color = (video_image.type() == CV_8UC3);
	cv::VideoWriter writer;
	double video_fps = 15.0;
	if (video_cap.get(cv::CAP_PROP_FPS) > 0) {
		video_fps = video_cap.get(cv::CAP_PROP_FPS);
	}
	int codec = cv::VideoWriter::fourcc('X', 'V', 'I', 'D');
	writer.open(argv[2], codec, video_fps, video_image.size(), is_color);
	if (!writer.isOpened()) {
		std::cerr << "Could not open the output video file for write !\n";
		return -1;
	}
	for (;;){
		if (!video_cap.read(video_image)) {
			std::cerr << " blank frame grabbed\n";
			break;
		}
		writer.write(video_image);
		cv::imshow("video_image", video_image);
		if (cv::waitKey(5) >= 0)
			break;
	}
	return 1;
}

参考文献

感谢各位大佬的分享
jackwangcumt–OpenCV C++简单的视频读取和保存
胵恦–OpenCV初尝试

你可能感兴趣的:(小程序系列,opencv,计算机视觉,人工智能)