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 .

Python | Serpino carpet File handling: Questions

Python | Serpino carpet NumPy: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method