opencv c++ 图片拼接,读取地址处理

最近学校里有个活动,要求把几张截图拼接成一张长图,但是我在手机上没找到这个功能,于是打算用opencv写一个程序。

这个程序有两个功能,第一个是将图片路径变成opencv支持的格式(去掉前后引号,将“\”改为“/”),第二个是拼接图片。

此函数实现整理图片地址的格式,用于opencv的imread

string process(string str){
    for(int i=0;i<str.size();i++){
        char text_tmp=str[i];
        if(text_tmp=='\\'){ //"\\"代表一个"\"字符
            str[i]='/';
        }
        if(text_tmp=='"'){
            str[i]=' ';
        }
    }
    str.erase(0, str.find_first_not_of(" "));   //删除0到第一个不是空格的字符
    str.erase(str.find_last_not_of(" ")+1, str.length());//删除最后一个不是空格的字符到字符串结尾
    return str;
}
此代码实现opencv图片拼接

Mat img1=imread(first_path);
Mat img2=imread(second_path);
int w1=img1.cols; int h1=img1.rows;
int w2=img2.cols; int h2=img2.rows;
int height=h1+h2;
int width=max(w1,w2);
Mat img(height,width,CV_8UC3,Scalar::all(0));   //注意这里(height,width)
Mat roi_1=img(Rect(0,0,w1,h1));
Mat roi_2=img(Rect(0,h1,w2,h2));    //注意这里(0,h1,w2,h2),不是(0,h1,w2,h1+h2) ROI
img1.copyTo(roi_1);
img2.copyTo(roi_2);
imshow("img",img);
imwrite("img.jpg", img);
waitKey(0);
这是最终代码

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
string process(string str){
    for(int i=0;i<str.size();i++){
        char text_tmp=str[i];
        if(text_tmp=='\\'){         //"\\"代表一个"\"字符
            str[i]='/';
        }
        if(text_tmp=='"'){
            str[i]=' ';
        }
    }

    str.erase(0, str.find_first_not_of(" "));   
    //删除0到第一个不是空格的字符

    str.erase(str.find_last_not_of(" ")+1, str.length());
    //删除最后一个不是空格的字符到字符串结尾
    return str;
}
int main()
{
    string first_path,second_path;
    cin>>first_path;
    cin>>second_path;
    first_path=process(first_path);      //处理后不带前后的双引号。且用“/”
    second_path=process(second_path);

    Mat img1=imread(first_path);
    Mat img2=imread(second_path);
    int w1=img1.cols; int h1=img1.rows;
    int w2=img2.cols; int h2=img2.rows;
    int height=h1+h2;
    int width=max(w1,w2);
    Mat img(height,width,CV_8UC3,Scalar::all(0));   //注意这里(height,width)
    Mat roi_1=img(Rect(0,0,w1,h1));    
    Mat roi_2=img(Rect(0,h1,w2,h2));     //注意这里(0,h1,w2,h2),不是(0,h1,w2,h1+h2) ROI
    img1.copyTo(roi_1);
    img2.copyTo(roi_2);
    imshow("img",img);
    imwrite("img.jpg", img);
    waitKey(0);
    return 0;
}

这是拼接完的图片(截图)

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值