c++(opencv)拼接两幅尺寸不同的图像

#include <iostream>  
#include <fstream>  
#include "opencv2/highgui/highgui.hpp"  
#include "opencv2/stitching/stitcher.hpp"  
#include "opencv2/opencv.hpp"


using namespace std;
using namespace cv;
//按行拼接图像A和B
Mat mergeRows(Mat A, Mat B)
{
    //CV_ASSERT(A.cols == B.cols&&A.type() == B.type());
    int totalRows = A.rows + B.rows;

    Mat mergedDescriptors(totalRows, A.cols, A.type());
    Mat submat = mergedDescriptors.rowRange(0, A.rows);
    A.copyTo(submat);
    submat = mergedDescriptors.rowRange(A.rows, totalRows);
    B.copyTo(submat);
    return mergedDescriptors;
}


void main()
{
    Mat image_one = imread("E:\\testpictures\\0\\1\\12.jpg");//待拼接左图
    Mat image_two = imread("E:\\testpictures\\0\\1\\18.jpg");//待拼接右图
    if (image_one.rows >= image_two.rows)
    {    //创建一个image_one.rows-image_two.rows行image_two.cols列的黑色图像
        #define HEIGHT image_one.rows-image_two.rows //行rows
        #define WIDTH image_two.cols  //列cols 
        //Scalar()是向量,表示初始化每个像素值是多少,向量长度与通道数目(深度)一致
        cv::Mat image(HEIGHT, WIDTH, image_two.type(), cv::Scalar(0));
        Mat outimage;
        //将黑色图像与image_two按行拼接成outimage,黑色图像放下面,因为c++的原点在左上角
        outimage=mergeRows(mage_two, image);
        //将image_one和outimage按列拼接为result并保存
        Mat result(image_one.rows, image_one.cols + outimage.cols, image_one.type());
        //colRange(int x,int y)  取图像的第x~y-1行
        image_one.colRange(0, image_one.cols).copyTo(result.colRange(0, image_one.cols));
        outimage.colRange(0, outimage.cols).copyTo(result.colRange(image_one.cols, result.cols));
        imwrite("result.jpg", result);
        waitKey(0);
    }
    else
    {    //创建一个image_two.rows-image_one.rows行image_one.cols列的黑色图像
        #define HEIGHT image_two.rows-image_one.rows //行rows
        #define WIDTH image_one.cols  //列cols 
        //Scalar()是向量,表示初始化每个像素值是多少,向量长度与通道数目(深度)一致
        cv::Mat image(HEIGHT, WIDTH, image_one.type(), cv::Scalar(0));
        Mat outimage;
        //将黑色图像与image_one按行拼接成outimage,黑色图像放下面,因为c++的原点在左上角
        outimage=mergeRows(image_one,image);
        //将image_two和outimage按列拼接为result并保存
        Mat result(image_two.rows, outimage.cols + image_two.cols, image_two.type());
        //colRange(int x,int y)  取图像的第x~y-1行
        outimage.colRange(0, outimage.cols).copyTo(result.colRange(0, outimage.cols));
        image_two.colRange(0, image_two.cols).copyTo(result.colRange(outimage.cols, result.cols));
        imwrite("result.jpg", result);
        waitKey(0);
    }
    return ;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值