OpenCV拼接两张图片
一、概述
案例:使用OpenCV将两张图片拼接成一张图片
实现步骤:
1.准备两张图片
2.判断两张图片大小,使其高度一致(通过等比例缩放)
3.创建一个空白的Mat矩阵,使其宽度=两张图片的宽度只和,高度=最小图片的高度
4.将两张图片分别copy进新建的大图中
5.完成
二、代码示例
Video_Player_Splicing_Image::Video_Player_Splicing_Image(QWidget *parent) : QWidget{parent} { this->setWindowTitle("图像拼接"); this->setFixedSize(320,480); QPushButton * chooseOneImageBtn = new QPushButton(this); chooseOneImageBtn->setText("选择第一张图片"); QPushButton * chooseTwoImageBtn = new QPushButton(this); chooseTwoImageBtn->move(chooseOneImageBtn->x()+chooseOneImageBtn->width()+20,0); chooseTwoImageBtn->setText("选择第二张图片"); QPushButton * submitBtn = new QPushButton(this); submitBtn->move(0,chooseOneImageBtn->y()+chooseOneImageBtn->height()); submitBtn->setText("开始拼接"); connect(chooseOneImageBtn,&QPushButton::clicked,[=](){ chooseOneImage(); }); connect(chooseTwoImageBtn,&QPushButton::clicked,[=](){ chooseTwoImage(); }); connect(submitBtn,&QPushButton::clicked,[=](){ showResultImage(); }); } void Video_Player_Splicing_Image::chooseOneImage(){ oneImagePath = QFileDialog::getOpenFileName(this,"选择图像","/Users/yangwei/Downloads/","Image File(*.jpg *.jpeg *.png *.bmp)"); qDebug()<<oneImagePath; } void Video_Player_Splicing_Image::chooseTwoImage(){ twoImagePath = QFileDialog::getOpenFileName(this,"选择图像","/Users/yangwei/Downloads/","Image File(*.jpg *.jpeg *.png *.bmp)"); qDebug()<<twoImagePath; } void Video_Player_Splicing_Image::showResultImage(){ Mat oneMat = imread(oneImagePath.toStdString().c_str()); Mat twoMat = imread(twoImagePath.toStdString().c_str()); if(oneMat.empty()){ qDebug()<<"第一张图片不能为空"; return; } if(twoMat.empty()){ qDebug()<<"第二张图片不能为空"; return; } imshow("src_one",oneMat); imshow("src_two",twoMat); int width = oneMat.cols; int height = oneMat.rows; int width2 = width; //等比缩放图片 if(oneMat.rows>twoMat.rows){//如果第一张图片比第二章图片高 height = twoMat.rows; width = oneMat.rows*((float)twoMat.cols/(float)oneMat.cols);//等比缩放 cv::resize(oneMat,oneMat,Size(width,height)); }else if(oneMat.rows<twoMat.rows){//第一张图片比第二章图片低 width2 = twoMat.cols*((float)oneMat.rows/(float)twoMat.rows);//等比缩放 cv::resize(twoMat,twoMat,Size(width2,height)); } //开始拼接图片 Mat dst; dst.create(height,width+width2,oneMat.type());//创建一个大的矩阵用于存放两张图像 //将第一张图和第二张图摆放在合适的位置 Mat roi1 = dst(Rect(0,0,width,height)); oneMat.copyTo(roi1); Mat roi2 = dst(Rect(width,0,width2,height)); twoMat.copyTo(roi2); imshow("dst",dst); }
三、演示图片
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库