拉普拉斯金字塔加权融合python代码
时间: 2023-07-09 10:05:43 浏览: 64
以下是拉普拉斯金字塔加权融合的Python代码示例:
```python
import cv2
import numpy as np
def laplacian_pyramid(img, levels):
pyramid = []
for i in range(levels):
blurred = cv2.pyrDown(img)
pyramid.append(img - cv2.pyrUp(blurred))
img = blurred
pyramid.append(img)
return pyramid
def gaussian_pyramid(img, levels):
pyramid = [img]
for i in range(levels-1):
pyramid.append(cv2.pyrDown(pyramid[-1]))
return pyramid
def weighted_fusion(laplacian_pyr_1, laplacian_pyr_2, gaussian_pyr_mask):
fused_pyr = []
for i in range(len(gaussian_pyr_mask)):
lp_1 = laplacian_pyr_1[i]
lp_2 = laplacian_pyr_2[i]
gp_mask = gaussian_pyr_mask[i]
fused_pyr.append(gp_mask * lp_1 + (1 - gp_mask) * lp_2)
return fused_pyr
def reconstruct_image(pyramid):
img = pyramid[-1]
for i in range(len(pyramid)-2, -1, -1):
img = cv2.pyrUp(img)
img += pyramid[i]
return img
# Load images
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# Create masks
mask1 = np.zeros_like(img1)
mask1[:, :img1.shape[1]//2] = 255
mask2 = 255 - mask1
# Build Laplacian pyramids
levels = 4
lap_pyr_1 = laplacian_pyramid(img1, levels)
lap_pyr_2 = laplacian_pyramid(img2, levels)
gauss_pyr_mask1 = gaussian_pyramid(mask1.astype(np.float32)/255, levels)
gauss_pyr_mask2 = gaussian_pyramid(mask2.astype(np.float32)/255, levels)
# Weighted fusion
fused_pyr = weighted_fusion(lap_pyr_1, lap_pyr_2, gauss_pyr_mask1)
# Reconstruct image
fused_img = np.clip(reconstruct_image(fused_pyr), 0, 255).astype(np.uint8)
# Show result
cv2.imshow('Image 1', img1)
cv2.imshow('Image 2', img2)
cv2.imshow('Fused Image', fused_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先加载两张图像,并创建两个掩膜,使其分别覆盖图像的左半部分和右半部分。然后,我们使用上面定义的 `laplacian_pyramid` 和 `gaussian_pyramid` 函数来为两个图像构建拉普拉斯金字塔和高斯金字塔。最后,我们使用 `weighted_fusion` 函数将两个拉普拉斯金字塔进行加权融合,并使用 `reconstruct_image` 函数重建融合后的图像。我们使用 `cv2.imshow` 函数来显示原始图像和融合后的图像。