Python | Serpino carpet



How does it work?
The Sierpinski carpet begins with a square. This square is divided into nine equal parts. The smallest smaller square is removed from the original larger square. Then the remaining squares are again divided into nine equal parts, and the most central square from each square is removed. When this process is repeated, a beautiful Sierpinski carpet pattern is observed.

Suppose we start with a black square. 

Divide it into 9 equal parts and remove the central square. 

Repeating the process further leads to something like this. 

We can visualize this phenomenon in detail in this video .

Let`s see how its code looks like:

# import required modules

import numpy as np

from PIL import Image

 
# total number of process repetitions

total  = 7

 
# image size

size = 3 * * total

 
# create image

square = np.empty ([size, size, 3 ], dtype = np.uint8)

color = np.array ([ 255 , 255 , 255 ], dtype = np.uint8)

  
# filling this with black

square.fill ( 0 )

 

for i in range ( 0 , total + 1 ):

  stepdown = 3 * * (total - i)

for x in range ( 0 , 3 * * i):

  

# checking the central square

if x % 3 = = 1 :

for y in range ( 0 , 3 * * i):

if y % 3 = = 1 :

 

# change your color

square [y * stepdown: (y + 1 ) * stepdown, x * stepdown: (x + 1 ) * stepdown] = color

 
# save the resulting image

save_file = "sierpinski.jpg"

Image.fromarray (square) .save (save_file)

 
# display it in the console

i = Image. open ( " sierpinski.jpg " )

i.show ()

Output:

This is a Sierpinski carpet after 7 repetitions. You can get its code for other languages ​​at rosettacode .