home

Generating the Barnsley Fern using Python

Generating fractals in python is very fun, especially if you dont concern yourself too much with performance.

Here is a very simple script to generate the Barnsley Fern using Python:

import numpy as np
import random
from PIL import Image

random.seed("burkhardt.dev")

f1a = np.array([[0, 0], [0, 0.16]])

f2a = np.array([[0.85, 0.04], [-0.04, 0.85]])
f2e = np.array([[0, 1.6]]).T

f3a = np.array([[0.2, -0.26], [0.23, 0.22]])
f3e = np.array([[0, 1.6]]).T

f4a = np.array([[-0.15, 0.28], [0.26, 0.24]])
f4e = np.array([[0, 0.44]]).T


def transform(pos: np.array) -> np.array:
    r = random.random()
    if r <= 0.01:
        return f1a @ pos
    elif r <= 0.86:
        return f2a @ pos + f2e
    elif r <= 0.93:
        return f3a @ pos + f3e
    else:
        return f4a @ pos + f4e


if __name__ == "__main__":
    img = Image.new("RGBA", (700, 700), (255, 255, 255, 255))
    pixels = img.load()

    pos = np.array([[0, 0]]).T

    for i in range(250_000):
        pos = transform(pos)
        img.putpixel((int((pos[0] + 2.5) * 130), abs(700 - int(pos[1] * 65))), (40, 120, 70, 255))

    img.show()
    img.save("fern.png")

This code results in the following image:

Render of Barnsley Fern