提示:本文中视频拼接指的是将多张图像按空间合并在一张图像上,而不是将多张图像按时间顺序拼接成一个多帧片段。
文章目录
前言
一、OpenCV知识点
1.OpenCV裁剪矩形区域赋值
2.OpenCV将Mat粘贴到指定位置
二、程序样例
1.程序源码
2.运行结果
前言
C++版拼接视频不如Python版简洁。
Python版:Python OpenCV【视频合并:多个图像拼接在一张图像】_IT.Husky的博客-CSDN博客
为了实现C++版拼接视频,首先复习一下OpenCV相关知识。
一、OpenCV知识点
1.OpenCV裁剪矩形区域赋值
Mat img;//读取图像cv::Rect rect(x, y, WIDTH, HEIGHT);//定义坐标(x,y)为矩形的左上角起点,宽高为WIDTH和HEIGHT的矩形Mat tmp = img(rect);//将img上矩形框住的部分赋给tmp
2.OpenCV将Mat粘贴到指定位置
cv::Mat src;//读取图像cv::Mat image;//定义一个存放图像的Matcv::Rect rect(0, 0, src.cols, src.rows);//定义坐标(0,0)为矩形的左上角起点,宽高为src.cols, src.rows的矩形src.copyTo(image(rect));//把src的内容复制到image指定的Rect框中
二、程序样例
1.程序源码
代码如下(带注释):
#include <iostream>
#include <opencv.hpp>
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;
}
2.运行结果
源视频图像首帧:
拼接视频图像首帧:
留作业:请尝试以下合并结果↓