有疑问请联系作者邮箱:[email protected]
代码使用请遵循LGPL协议
输入:背景文件路径 logo文件路径 logo左上横坐标 纵坐标
#include<opencv2/opencv.hpp>
#include <iostream>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<string>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
string a1, b1;
cin >> a1 >> b1;
Mat srcImage1 = imread(a1);
Mat logoImage = imread(b1);
if (!srcImage1.data) { printf("background read error \n"); return false; }
if (!logoImage.data) { printf("logo read error \n"); return false; }
int x, y, width=0, hight=0,roix,roiy,maskx=0,masky=0;
cin >> x >> y;
roix = x; roiy = y;
if (x >= 0 && x + logoImage.cols <= srcImage1.cols) {
if (y < 0) {
roiy = 0;
width = logoImage.cols; hight = logoImage.rows + y;
}
else if (y + logoImage.rows > srcImage1.rows) {
width = logoImage.cols; hight = srcImage1.rows - y;
masky = -y;
}
else {
width = logoImage.cols; hight = logoImage.rows;
}
}
if (x + logoImage.cols > srcImage1.cols) {
if (y < 0) {
roiy = 0;
width = srcImage1.cols - x; hight = logoImage.rows + y;
}
else if (y + logoImage.rows > srcImage1.rows) {
width = srcImage1.cols - x; hight = srcImage1.rows - y;
masky = -y;
}
else {
width = srcImage1.cols - x; hight = logoImage.rows;
}
}
if (x<0 ) {
if (y < 0) {
roix = 0; roiy = 0;
width = x + logoImage.cols; hight = y+logoImage.rows;
maskx = -x; masky = -y;
}
else if (y + logoImage.rows > srcImage1.rows) {
roix = 0;
width = x + logoImage.cols; hight = srcImage1.rows - y;
maskx = -x;
}
else {
roix = 0;
width = x + logoImage.cols; hight = logoImage.rows;
maskx = -x;
}
}
Mat mask, imageROI = srcImage1(Rect(roix, roiy, width, hight));
mask = logoImage(Rect(maskx, masky, width, hight));
mask.copyTo(imageROI, mask);
namedWindow("合成图");
imshow("合成图", srcImage1);
system("mkdir c:\\save");
imwrite("C:/save/save.jpg", srcImage1);
waitKey();
return 0;
}
水一点文字
前六行头文件
七八行namespace(问就是懒)
8 69 70 主函数返回0清理内存
9 10定义两个string 分别是背景和logo的路径并且输入路径
11 12读取背景和路径
13 14判定图片是否存在(不存在报错并返回0)
15 16 定义并输入坐标
17-60处理坐标
61定义掩膜和roi并且裁剪roi
62裁剪掩膜
64-66定义窗口并显示
66开辟路径
67存储图片
68等待操作