Title: Draw a Sierpinski carpet fractal in Python and PIL
These earlier posts described shapes described by Wacław Sierpiński (1882 - 1969).
Sierpiński did a lot of other interesting things including defining the Sierpiński gasket and the Sierpiński carpet. This post explains how you can draw the Sierpiński carpet in Python and PIL.
As is usually the case, much of the program's code is dedicated to controlling the user interface and arranging things nicely. You can download the example to see those details. This post focuses on the fractal-drawing code.
The following make_carpet function creates the carpet image.
def make_carpet(self, depth, wid, hgt, fg, bg):
'''Make the carpet image.'''
# Make the image, initially filled with the fg color.
image = Image.new('RGB', (wid, hgt), fg)
dr = ImageDraw.Draw(image)
# Recursively draw the carpet.
self.remove_center(depth, dr, bg, 0, 0, wid, wid)
return image
This code creates an image of the desired size and fills it with the indicated foreground color fg. It then calls the following remove_center method to remove the rectangle's middle.
def remove_center(self, depth, dr, fill, xmin, ymin, xmax, ymax):
'''Clear the center of this area.'''
# Divide the area into 9 pieces.
x3 = (xmax - xmin) / 3 # 1/3 of the width and height.
y3 = (ymax - ymin) / 3
# Clear the center.
dr.rectangle(xy=(xmin + x3, ymin + y3, xmin + 2 * x3, ymin + 2 * y3),
fill=fill)
# See if should recurse.
depth -= 1
if depth >= 0:
for r in range(3):
for c in range(3):
if r != 1 or c != 1:
self.remove_center(depth, dr, fill,
xmin + x3 * c, ymin + y3 * r,
xmin + x3 * (c + 1), ymin + y3 * (r + 1))
The remove_center method calculates X and Y coordinates needed to divide the rectangle into nine pieces. It fills the middle piece with the given fill color.
Next, the code subtracts one from the depth parameter. If that value is still at least 0, the code uses two nested loops to recursively call itself for the rectangle's non-middle pieces.
Like many recursive fractals, the code for this one is deceptively simple but it can generate very complicated results.
The following pictures show Sierpinski carpets with depths 0 through 3.
Download the example to experiment with it and to see additional details.
|
The picture on the left is a three-dimensional version of the Sierpinski carpet called the Menger sponge, named after Karl Menger (1902 - 1985) who first described it in 1926.
This picture was generated by techniques described in my book Build Your Own Ray Tracer With Python.
|
|
|