考慮到python通過for循環實現加權平均融合效率比較低,本文采用矩陣運算的形式實現加權平均融合。其中加權平均融合的公式如下:
是融合圖像,是需要拼接的兩幅圖像,是漸入漸出法中的權重,權重的計算公式如下:
也就是上面的兩個公式,挺簡單的,相對於C++而言,用python實現加權平均融合的矩陣運算更加容易理解。直接上結果圖,以下是加權平均融合之前與融合之後的對比。
加權平均融合前對比融合後,拼接的摺痕消失了 ,這就是加權平均融合的作用所在。
具體上python代碼:
def removal_seam(self, img_trans, img_targ, transform_corners, threshold=20):
# img_trans warpPerspective image
# img_targ target image
# transform_corners the 4 corners of warpPerspective image
# corners_orig = np.array([[0, 0, 1],
# [0, img.shape[0], 1],
# [img.shape[1], 0, 1],
# [img.shape[1], img.shape[0], 1]])
# obtain 4 corners from T transform
pano = copy.deepcopy(img_trans)
pano[0:img_targ.shape[0], 0:img_targ.shape[1]] = img_targ
x_right = img_targ.shape[1]
x_left = int(min(transform_corners[0, 0], transform_corners[0, 1]))
rows = pano.shape[0]
# calculate weight matrix
alphas = np.array([x_right - np.arange(x_left, x_right)] * rows) / (x_right - x_left)
alpha_matrix = np.ones((alphas.shape[0], alphas.shape[1], 3))
alpha_matrix[:, :, 0] = alphas
alpha_matrix[:, :, 1] = alphas
alpha_matrix[:, :, 2] = alphas
# common area one image no pixels
alpha_matrix[img_trans[0:rows, x_left:x_right, :] <= threshold] = 1
img_targ = pano[:, 0:img_targ.shape[1]]
pano[0:rows, x_left:x_right] = img_targ[0:rows, x_left:x_right] * alpha_matrix \
+ img_trans[0:rows, x_left:x_right] * (1 - alpha_matrix)
retrun pano
爲了更好理解removal_seam函數,有必要繪製一個簡單的示意圖(關於img_trans, img_targ)。img_trans的變換需要通過特徵匹配計算變換矩陣T,特徵提取可以選擇爲SIFT、SURF、ORB等。