提示:本文中视频拼接指的是将多张图像按空间合并在一张图像上,而不是将多张图像按时间顺序拼接成一个多帧片段。
C++版拼接视频不如Python版简洁。
Python版:Python OpenCV【视频合并:多个图像拼接在一张图像】_IT.Husky的博客-CSDN博客
为了实现C++版拼接视频,首先复习一下OpenCV相关知识。
- Mat img;//读取图像
-
- cv::Rect rect(x, y, WIDTH, HEIGHT);//定义坐标(x,y)为矩形的左上角起点,宽高为WIDTH和HEIGHT的矩形
-
- Mat tmp = img(rect);//将img上矩形框住的部分赋给tmp
- cv::Mat src;//读取图像
-
- cv::Mat image;//定义一个存放图像的Mat
-
- cv::Rect rect(0, 0, src.cols, src.rows);//定义坐标(0,0)为矩形的左上角起点,宽高为src.cols, src.rows的矩形
-
- src.copyTo(image(rect));//把src的内容复制到image指定的Rect框中
代码如下(带注释):
- #include
- #include
- using namespace std;
-
- int main()
- {
- //读视频
- cv::VideoCapture videoLeftUp("kll.mp4");
- cv::VideoCapture videoRightUp("kll.mp4");
- cv::VideoCapture videoLeftDown("kll.mp4");
- cv::VideoCapture videoRightDown("kll.mp4");
- int fps = videoLeftUp.get(5);
- cv::Size size = cv::Size(videoLeftUp.get(3), videoLeftUp.get(4));
- //写视频
- cv::VideoWriter writer("kllHeBing.mp4", CV_FOURCC('m', 'p', '4', 'v'), fps, size, true);
- cv::Mat frameLeftUp, frameRightUp, frameLeftDown, frameRightDown;
- //读视频帧
- while (videoLeftUp.read(frameLeftUp) && videoRightUp.read(frameRightUp) &&
- videoLeftDown.read(frameLeftDown) && videoRightDown.read(frameRightDown))
- {
- //调整帧尺寸
- cv::Mat frameLeftUpNew, frameRightUpNew, frameLeftDownNew, frameRightDownNew;
- resize(frameLeftUp, frameLeftUpNew, cv::Size(frameLeftUp.cols / 2, frameLeftUp.rows / 2));
- resize(frameRightUp, frameRightUpNew, cv::Size(frameRightUp.cols / 2, frameRightUp.rows / 2));
- resize(frameLeftDown, frameLeftDownNew, cv::Size(frameLeftDown.cols / 2, frameLeftDown.rows / 2));
- resize(frameRightDown, frameRightDownNew, cv::Size(frameRightDown.cols / 2, frameRightDown.rows / 2));
- //新建Mat 用于图像合并
- cv::Mat frameOut = cv::Mat::zeros(frameLeftUp.rows, frameLeftUp.cols, frameLeftUp.type());
- //定义图像放的位置
- cv::Rect rectLeftUp = cvRect(0, 0, frameLeftUpNew.cols, frameLeftUpNew.rows);
- cv::Rect rectRightUp = cvRect(frameRightUpNew.cols, 0, frameRightUpNew.cols, frameRightUpNew.rows);
- cv::Rect rectLeftDown = cvRect(0, frameLeftDownNew.rows, frameLeftDownNew.cols, frameLeftDown.rows);
- cv::Rect rectRightDown = cvRect(frameRightDownNew.cols, frameRightDownNew.rows, frameRightDownNew.cols, frameRightDownNew.rows);
- //将调整尺寸的帧图像放置新建Mat的指定位置
- frameLeftUpNew.copyTo(frameOut(rectLeftUp));
- frameRightUpNew.copyTo(frameOut(rectRightUp));
- frameLeftDownNew.copyTo(frameOut(rectLeftDown));
- frameRightDownNew.copyTo(frameOut(rectRightDown));
- /*cv::imshow("frameOut.jpg", frameOut);
- cv::waitKey(0);*/
- //写入帧图像
- writer.write(frameOut);
- }
- //释放内存
- writer.release();
- videoLeftUp.release();
- videoRightUp.release();
- videoLeftDown.release();
- videoRightDown.release();
-
- system("pause");
- return 0;
- }
源视频图像首帧:
拼接视频图像首帧:
留作业:请尝试以下合并结果↓