Open CV中自带了addWeighted函数进行图像融合。
C++: void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray
dst, int dtype=-1)
Parameters
src1 – First source array.
经常选用Mat
alpha – Weight for the first array elements.
表示第一个数组的权重
src2 – Second source array of the same size and channel number as src1 .
与第一个数组有相同的尺寸和通道
beta – Weight for the second array elements.
第二个数组的权重
dst – Destination array that has the same size and number of channels as the input arrays.
输出数组
gamma – Scalar added to each sum.
一个标量值
dtype – Optional depth of the destination array. When both input arrays have the same
depth, dtype can be set to -1, which will be equivalent to src1.depth().
The function addWeighted calculates the weighted sum of two arrays as follows:
dst(I) = saturate(src1(I) alpha + src2(I) beta + gamma)
where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed
independently.
The function can be replaced with a matrix expression:
dst = src1*alpha + src2*beta + gamma;
ROI(感兴趣区域):
ROI(region of interest),感兴趣区域。机器视觉、图像处理中,从被处理的图像以方框、圆、椭圆、不规则多边形等方式勾勒出需要处理的区域,称为感兴趣区域,ROI。在图像处理领域,感兴趣区域(ROI) 是从图像中选择的一个图像区域,这个区域是你的图像分析所关注的重点。圈定该区域以便进行进一步处理。使用ROI圈定你想读的目标,可以减少处理时间,增加精度。
①提取感兴趣区,用预先制作的感兴趣区掩模与待处理图像相乘,得到感兴趣区图像,感兴趣区内图像值保持不变,而区外图像值都为0。
②屏蔽作用,用掩模对图像上某些区域作屏蔽,使其不参加处理或不参加处理参数的计算,或仅对屏蔽区作处理或统计。
③结构特征提取,用相似性变量或图像匹配方法检测和提取图像中与掩模相似的结构特征。
④特殊形状图像的制作。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
void ROI_LinearBlending(){
Mat img = imread("img.jpg");
Mat logo = imread("logo.jpg");
if(!img.data){
cout<<"input error!"<<endl;
return;
}
if(!logo.data){
cout<<"input error!"<<endl;
return;
}
imshow("原图1",img);
imshow("原图2",logo);
Mat ROI = img(Rect(10,120,logo.cols,logo.rows));//制作感兴趣区域
//Mat ROI = img(Range(100,100+logo.rows),Range(120,120+logo.cols));
addWeighted(ROI,0.3,logo,0.5,0.0,ROI);//图像叠加
imshow("ROI_LinearBlending",img);
}
void Add_Image(){
Mat img = imread("img.jpg");
Mat logo = imread("logo.jpg");
if(!img.data){
cout<<"input error!"<<endl;
return;
}
if(!logo.data){
cout<<"input error!"<<endl;
return;
}
Mat ROI = img(Range(10,10+logo.rows),Range(10,10+logo.cols));//制作感兴趣区域
Mat mask = imread("logo.jpg",0);//制作掩膜
//logo.copyTo(ROI);//注意区别
logo.copyTo(ROI,mask);
imshow("Add_Image",img);
//imshow("dd",logo);
}
void LinearBlending(){
Mat img1 = imread("mogu.jpg");
Mat img2 = imread("rain.jpg");
if(!img1.data){
cout<<"input error!"<<endl;
return;
}
if(!img2.data){
cout<<"input error!"<<endl;
return;
}
imshow("原图3",img1);
imshow("原图4",img2);
Mat dst;
dst.create(img1.size(),img1.type());
double alpha,beta;
alpha = 0.3;
beta = 1.0 - alpha;
addWeighted(img1,alpha,img2,beta,0.0,dst);//线性融合
imshow("LinearBlending",dst);
}
int main(int argc,char **argv){
ROI_LinearBlending();
Add_Image();
LinearBlending();
waitKey(0);
return 0;
}
运行结果: