opencv 图像添加掩膜层 addWeighted

发布时间 2023-08-23 10:28:41作者: 哈库拉

接口: from   opencv2/core.hpp

/** @brief Calculates the weighted sum of two arrays.

The function addWeighted calculates the weighted sum of two arrays as follows:
\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} +  \texttt{src2} (I)* \texttt{beta} +  \texttt{gamma} )\f]
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:
@code{.cpp}
    dst = src1*alpha + src2*beta + gamma;
@endcode
@note Saturation is not applied when the output array has the depth CV_32S. You may even get
result of an incorrect sign in the case of overflow.
@param src1 first input array.
@param alpha weight of the first array elements.
@param src2 second input array of the same size and channel number as src1.
@param beta weight of the second array elements.
@param gamma scalar added to each sum.
@param dst output array that has the same size and number of channels as the input arrays.
@param dtype optional depth of the output array; when both input arrays have the same depth, dtype
can be set to -1, which will be equivalent to src1.depth().
@sa  add, subtract, scaleAdd, Mat::convertTo
*/
CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
                              double beta, double gamma, OutputArray dst, int dtype = -1);

使用:

Mat img = imread("d:/Image/bit.png", 1);
Mat output;
Mat overlay = img.clone();
rectangle(overlay, Rect(50, 150, 230, 130), Scalar(0, 0, 200), -1);
std::vector<Point> pts;
pts.push_back(Point(10, 20));
pts.push_back(Point(100, 120));
pts.push_back(Point(50, 200));
pts.push_back(Point(0, 100));
std::vector<std::vector<Point>> contours;
contours.push_back(pts);
drawContours(overlay, contours, -1, Scalar(0, 0, 200), -1);
//Mat ppts = cv::Mat(pts);
//fillPoly(overlay, pts, Scalar(0, 0, 200),8,0);
double alpha = 0.5;
addWeighted(overlay, alpha, img, 1 - alpha,0, output); // 掩膜区域为颜色值与原始值的线性和