使用php代码实现7行金字塔,如何用PHP代码生成金字塔

对于很多PHP初学者来说,初期阶段培养逻辑思维能力是非常有必要的。用PHP代码来生成金字塔的这个过程,就可以很好的培养初学者的逻辑思维能力。下面我们来详细讲解一下PHP生成金字塔的整个过程。

1、生成金字塔的效果图:

734e331e461e80992fc6c679727f2ed3.png

2、代码实现过程:

for($i=1;$i<=5;$i++){

for($n=1;$n<=(5-$i);$n++) //控制输出空格

echo ' ';

for($s=1;$s<=(2*$i-1);$s++) //控制输出星号

echo '*';

echo '
';

}

?>

3、逻辑:

(1)星号左右的空格如何实现:

空格的话用 &nbsp 代表。以5层来说空格是4 》 3 》 2 》1 》 0

第1层 空格是 4 (总层数-第几层)(5-1)

第2层 空格是 3 (总层数-第几层)(5-2)

第3层 空格是 2 (总层数-第几层)(5-3)

第4层 空格是 1 (总层数-第几层)(5-4)

第5层 空格是 0 (总层数-第几层)(5-5)

那么可以用for循环来for($n=1;$n<=(总层数-第几层);$n++) echo ' ';

(2)输出星号:

星号的话以5层来说:1 》 3 》5 》7 》9

发现是奇数那么可以用2(n)的次方来表示

1 = 2*1 -1

3 = 2*2 -1

5 = 2*3 -1

7 = 2*4 -1

9 = 2*5 -1

这里的乘以1 2 3 4 5是层数,那么输出星号for($s=0;$s<=(层数);$s++) echo '*';

以上就是PHP代码生成金字塔的整个过程。当然,既然能生成正立的金字塔,那么倒立的金字塔肯定也是可以实现的,有兴趣的朋友可以自行研究。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用OpenCV库实现的图像融合代码,其中包括了高斯金字塔实现: ```python import cv2 import numpy as np def pyramid_blending(img1, img2, levels): # generate Gaussian pyramid for img1 G1 = img1.copy() gp1 = [G1] for i in range(levels): G1 = cv2.pyrDown(G1) gp1.append(G1) # generate Gaussian pyramid for img2 G2 = img2.copy() gp2 = [G2] for i in range(levels): G2 = cv2.pyrDown(G2) gp2.append(G2) # generate Laplacian Pyramid for img1 lp1 = [gp1[levels-1]] for i in range(levels-1,0,-1): GE = cv2.pyrUp(gp1[i]) L = cv2.subtract(gp1[i-1],GE) lp1.append(L) # generate Laplacian Pyramid for img2 lp2 = [gp2[levels-1]] for i in range(levels-1,0,-1): GE = cv2.pyrUp(gp2[i]) L = cv2.subtract(gp2[i-1],GE) lp2.append(L) # join the left and right halves of the images in each level of Laplacian Pyramid LS = [] for l1,l2 in zip(lp1,lp2): rows,cols,dpt = l1.shape ls = np.hstack((l1[:,0:cols//2], l2[:,cols//2:])) LS.append(ls) # reconstruct the blended image using the Laplacian Pyramid blended = LS[0] for i in range(1,levels): blended = cv2.pyrUp(blended) blended = cv2.add(blended, LS[i]) return blended # load images img1 = cv2.imread('image1.jpg') img2 = cv2.imread('image2.jpg') # set the number of levels for the pyramid levels = 4 # perform pyramid blending blended = pyramid_blending(img1, img2, levels) # display the blended image cv2.imshow('Blended Image', blended) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在此代码中,`pyramid_blending` 函数使用高斯金字塔实现图像融合,可以通过 `levels` 参数来控制金字塔的层数。函数首先生成两个图像的高斯金字塔,然后使用这些图像生成拉普拉斯金字塔,将这些金字塔的左右两侧进合并,最后使用拉普拉斯金字塔重建混合图像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值