一.写在前面
线性混合理论:
g(x)=(1-α)f0 (x)+αf1 (x)
可以理解为:
f0,f1是待混合的两张图片
g是混合后的图片
其中α的取值范围是0~1
二.相关API
CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
double beta, double gamma, OutputArray dst, int dtype = -1);
/** @brief Scales, calculates absolute values, and converts the result to 8-bit.
On each element of the input array, the function convertScaleAbs
performs three operations sequentially: scaling, taking an absolute
value, conversion to an unsigned 8-bit type:
\f[\texttt{dst} (I)= \texttt{saturate\_cast<uchar>} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f]
In case of multi-channel arrays, the function processes each channel
independently. When the output is not 8-bit, the operation can be
emulated by calling the Mat::convertTo method (or by using matrix
expressions) and then by calculating an absolute value of the result.
For example:
@code{.cpp}
Mat_<float> A(30,30);
randu(A, Scalar(-100), Scalar(100));
Mat_<float> B = A*5 + 3;
B = abs(B);
// Mat_<float> B = abs(A*5+3) will also do the job,
// but it will allocate a temporary matrix
@endcode
@param src input array.
@param dst output array.
@param alpha optional scale factor.
@param beta optional delta added to the scaled values.
@sa Mat::convertTo, cv::abs(const Mat&)
*/
参数1:输入图像Mat – src1
参数2:输入图像src1的alpha值
参数3:输入图像Mat – src2
参数4:输入图像src2的alpha值
参数5:gamma值
参数6:输出混合图像
注意点:两张图像的大小和类型必须一致才可以
三.代码实现
/*
OpenCV 图像混合学习
Michael Jiang <sencom1997@outlook.com>
2019年7月24日11:07:56
*/
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
int main()
{
//读取图像p1.png和p2.png
Mat p1 = imread("D:/p1.png", IMREAD_COLOR);
Mat p2 = imread("D:/p2.png", IMREAD_COLOR);
//判断是否读取成功
if (!p1.data) {
printf("p1 load failed!\n");
return -1;
}
if (!p2.data) {
printf("p2 load failed!\n");
return -1;
}
namedWindow("p1", WINDOW_AUTOSIZE);
namedWindow("p2", WINDOW_AUTOSIZE);
imshow("p1", p1);
imshow("p2", p2);
//判断图片尺寸,格式是否相同
if (p1.cols == p2.cols && p1.rows == p2.rows && p1.type() == p2.type()) {
Mat mix;
double alpha = 0.5;
namedWindow("mix", WINDOW_AUTOSIZE);
addWeighted(p1, alpha, p2, (1.0 - alpha), 1.0, mix);
imshow("mix", mix);
}
else {
printf("p1 p2 not same!\n");
return -1;
}
waitKey(0);
return 0;
}