1 addWeighted函数
在OpenCV 里,addWeighted
函数的作用是对两个图像进行加权求和,常用于图像融合、图像过渡等场景。函数如下:
cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
2 参数解释
src1
:第一个输入图像。alpha
:第一个输入图像的权重,取值范围是 0 到 1。src2
:第二个输入图像,它的大小和通道数必须与src1
相同。beta
:第二个输入图像的权重,取值范围是 0 到 1。gamma
:标量值,添加到加权和中(通常用于亮度调整)。dst
:输出图像(可选参数,直接通过返回值获取)。dtype
:输出图像的可选深度,若未指定,则使用输入图像的深度。
该函数将两个图像按权重相加,实现图像的线性混合,其数学公式为:
d s t = α ∗ s r c 1 + β ∗ s r c 2 + γ dst = \alpha * src1 + \beta * src2 + \gamma dst=α∗src1+β∗src2+γ
3 注意
- 图像尺寸和通道数:
src1
和src2
必须具有相同的尺寸和通道数,否则会报错。 - 权重和:
alpha + beta
不需要等于 1,但若想实现透明度混合(如alpha + beta = 1
),需自行控制。 - 数据类型:若输入为
uint8
类型,结果会自动截断到 [0, 255] 范围(饱和操作)。 - gamma 的作用:用于调整输出图像的亮度(例如,
gamma=10
会使整体亮度增加)。- 若 alpha + beta > 1,图像可能过曝(值被截断到 255)。
- 若 gamma > 0,整体亮度增加;若 gamma < 0,亮度降低。
- 与
cv2.add()
的区别:cv2.add()
是直接相加(无权重),而addWeighted()
允许更灵活的线性组合。
4 函数原型
def addWeighted(src1: Mat, alpha, src2: Mat, beta, gamma, dts: Mat = ..., dtype=...)
from __doc__"""'addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]]) -> dst . @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'"""pass
5 函数应用
-
图像叠加:例如,在制作幻灯片过渡效果时,就可以使用该函数实现图像的平滑过渡:通过调整
alpha
和beta
实现淡入淡出效果。 -
ROI 混合:结合掩码(mask)对局部区域进行混合:
roi = img1[y:y+h, x:x+w]
blended_roi = cv2.addWeighted(roi, 0.5, img2_roi, 0.5, 0)
img1[y:y+h, x:x+w] = blended_roi
6 示例代码
代码如下:
import cv2# 读取两张图像
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.png')# 定义权重
alpha = 0.7
beta = 0.3
gamma = 0# 进行加权求和
result = cv2.addWeighted(image1, alpha, image2, beta, gamma)# 显示结果
cv2.imshow("Touxiang", image1)
cv2.imshow("Zi", image2)
cv2.imshow('Weighted Image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
通过以上代码,可以将两张图片融合,配置不同的alpha和beta值,可以得到不同融合效果。
融合前:
融合后: