📜  Python|谢尔宾斯基地毯

📅  最后修改于: 2022-05-13 01:55:52.019000             🧑  作者: Mango

Python|谢尔宾斯基地毯

谢尔宾斯基地毯是平面分形曲线,即与平面子空间同胚的曲线。它由 Waclaw Sierpinski 于 1916 年首次描述。在这些类型的分形中,一个形状被分割成一个较小的自身副本,移除一些新副本并按照特定顺序留下剩余的副本以形成新的分形形状。

它是如何构建的?
谢尔宾斯基地毯从一个正方形开始。这个正方形被分成九等份。最中心的小方块从原来的大方块中移除。然后将剩余的正方形块再次分成九等份,并从每个正方形中移除最中心的正方形。重复这个过程,可以看到美丽的谢尔宾斯基地毯图案。

假设我们从一个黑色方块开始。

我们将它分成 9 等份并移除中心正方形。

在进一步重复该过程时,会产生类似这样的结果。

我们可以在这个视频中详细地想象这种现象。

让我们看看它的代码是什么样的:

# importing necessary modules
import numpy as np
from PIL import Image
  
# total number of times the process will be repeated
total = 7
  
# size of the image
size = 3**total
  
# creating an image
square = np.empty([size, size, 3], dtype = np.uint8)
color = np.array([255, 255, 255], dtype = np.uint8)
  
# filling it black
square.fill(0)
  
for i in range(0, total + 1):
    stepdown = 3**(total - i)
    for x in range(0, 3**i):
          
        # checking for the centremost square
        if x % 3 == 1:
            for y in range(0, 3**i):
                if y % 3 == 1:
                      
                    # changing its color
                    square[y * stepdown:(y + 1)*stepdown, x * stepdown:(x + 1)*stepdown] = color
  
# saving the image produced
save_file = "sierpinski.jpg"
Image.fromarray(square).save(save_file)
  
# displaying it in console
i = Image.open("sierpinski.jpg")
i.show()

输出 :

这是 7 次重复后的谢尔宾斯基地毯。您可以在 rosettacode 上获取其他语言的代码。