1. 程式人生 > >Python-OpenCV 影象疊加or影象混合加權(cv2.addWeighted)

Python-OpenCV 影象疊加or影象混合加權(cv2.addWeighted)

Python-OpenCV 影象疊加or影象混合加權實現

函式說明

cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]]) → dst

引數說明

  • src1 – first input array.
  • alpha – weight of the first array elements.
  • src2 – second input array of the same size and channel number as src1.
  • beta – weight of the second array elements.
  • dst – output 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 output array; when both input arrays have the same depth, dtype can be set to -1, which will be equivalent to src1.depth().

此函式可以用一下矩陣表示式來代替:

dst = src1 * alpha + src2 * beta + gamma;

注意:由引數說明可以看出,被疊加的兩幅影象必須是尺寸相同、型別相同的;並且,當輸出影象array的深度為CV_32S時,這個函式就不適用了,這時候就會記憶體溢位或者算出的結果壓根不對。

CV_32S is a signed 32bit integer value for each pixel

程式碼示範

def addImage(img1_path, img2_path):
    img1 = cv2.imread(img1_path)
    img = cv2.imread(img2_path)
    h, w, _ = img1.shape
    # 函式要求兩張圖必須是同一個size
img2 = cv2.resize(img, (w,h), interpolation=cv2.INTER_AREA) #print img1.shape, img2.shape #alpha,beta,gamma可調 alpha = 0.7 beta = 1-alpha gamma = 0 img_add = cv2.addWeighted(img1, alpha, img2, beta, gamma) cv2.namedWindow('addImage') cv2.imshow('img_add',img_add) cv2.waitKey() cv2.destroyAllWindows()

圖示

原圖1:

img

原圖2:
timg

疊加後結果:

(1)圖1的權重為0.7,圖二的權重為0.3, gamma為0 的結果:
img_add1

(2)圖1的權重為0.7,圖二的權重為0.3, gamma為100 的結果:

img_add2

(3)圖1的權重為0.3,圖二的權重為0.7, gamma為0 的結果:

img_add3