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);

}

 

三、演示图片

 

posted on 2022-05-10 23:38  飘杨......  阅读(2237)  评论(0编辑  收藏  举报