利用opencv库录制九宫格视频(C++实现)

利用opencv库录制九宫格视频(C++实现)

在项目开始之前,我的环境已配置完成,具体环境如何配置可参考网络教程。下面我们开始项目的实现

库的导入

#include
#include
#include
using namespace std;
using namespace cv;

这就不多说了

开启摄像头

	Mat frame;
	Mat newframe;
	string outputVideoPath = "F:\\C++language\\robocon.avi";
	VideoCapture capture(0);
	int frame_width = capture.get(CAP_PROP_FRAME_WIDTH);
	int frame_height = capture.get(CAP_PROP_FRAME_HEIGHT);
	VideoWriter writer;

开始摄像头,并获取摄像头的像素高度与宽度

定义所需变量

	int num = 3;//原图片长宽皆被划分为三份,共划分成九份
	int stepwidth;//划分后单个图片的宽度
	int stepheight;//划分后的那个图片的高度
	int space = 5;//九宫格中每张图片的间隔

捕获图片并生成视频

	capture >> frame;
	stepwidth = frame.cols / num;
	stepheight = frame.rows / num;
	resize(frame, frame, Size(stepwidth * num, stepheight * num), 1, 1, INTER_LINEAR);

	newframe = Mat(Size(frame.cols + (num - 1) * space, frame.rows + (num - 1) * space), CV_8UC3, Scalar(255, 255, 255));//新画布的生成
	writer.open(outputVideoPath, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 10, Size(frame.cols + (num - 1) * space, frame.rows + (num - 1) * space));
	if (!capture.isOpened())
	{
		cout << "The camera cannot be opened" << endl;
	}

	if (!writer.isOpened())
	{
		cout << "The video cannot be saved" << endl;
	}

根据九宫格各张图片以及间隔的大小生成新的画布,用于存放新的九宫格图片

实现图片的抓取、转换与保存


	int count = 1;

	while (count <= 60)
	{
		capture >> frame;
		stepwidth = frame.cols / num;
		stepheight = frame.rows / num;
		resize(frame, frame, Size(stepwidth * num, stepheight * num), 1, 1, INTER_LINEAR);

		Mat newframe = Mat(Size(frame.cols + (num - 1) * space, frame.rows + (num - 1) * space), CV_8UC3, Scalar(255, 255, 255));
		
		int i = 0;
		int j = 0;
		for (i = 0; i < num; i++)
		{
			for (j=0; j < num; j++)
			{
				int x = stepwidth * j;
				int y = stepheight * i;

				frame(Rect(x, y, stepwidth, stepheight)).copyTo(newframe(Rect(x + space * j, y + space * i, stepwidth, stepheight)));

			}

		
		}	
		imshow("output", newframe);
		waitKey(100);

		writer << newframe;
		count += 1;
	}
}

视频以10帧的形式呈现,共60帧图片。

你可能感兴趣的