创建一个python金字塔的代码
时间: 2023-10-12 20:19:24 浏览: 50
以下是一个简单的Python金字塔代码示例:
```python
height = int(input("请输入金字塔的高度:"))
for i in range(1, height+1):
print(" "*(height-i) + "* "*(i))
```
运行该代码,输入金字塔的高度,即可输出相应高度的金字塔。例如,输入高度为5,输出如下:
```
*
* *
* * *
* * * *
* * * * *
```
相关问题
python金字塔for循环完整代码
根据引用,在Python中,可以使用itertools模块的product函数来实现金字塔形的for循环。下面是一个完整的示例代码:
```
import itertools
rows = 5 # 金字塔的行数
for i in range(1, rows + 1):
# 创建一个列表,包含从1到i的数字
numbers = list(range(1, i + 1))
# 使用itertools.product生成所有可能的组合
combinations = list(itertools.product(numbers, repeat=i))
# 打印每个组合
for combination in combinations:
print(combination)
```
这段代码将打印出以下结果:
```
(1,)
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
(4, 4)
(4, 5)
(5, 1)
(5, 2)
(5, 3)
(5, 4)
(5, 5)
```
拉普拉斯金字塔加权融合python代码
以下是拉普拉斯金字塔加权融合的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` 函数来显示原始图像和融合后的图像。