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值,可以得到不同融合效果。
融合前:
融合后: