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

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

利用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帧图片。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/914583.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存