Python Pillow/NumPy: Make a Mandelbrot Zoom Animation (Blog Tutorial)

andreasPython Code2 weeks ago35 Views

Level: Beginner → Intermediate
You’ll learn: How the Mandelbrot set works, pixel-by-pixel image generation, fast NumPy loops, and exporting an animated GIF.

What is the Mandelbrot set?

The Mandelbrot set is the set of complex numbers c for which the sequence
z₀ = 0, zₙ₊₁ = zₙ² + c
does not escape to infinity. We color each pixel by how fast it escapes (iteration count).


Quickstart (single image)

from PIL import Image
import numpy as np

W, H = 800, 600
max_iter = 200

# Plot window (classic view)
RE_START, RE_END = -2.5, 1.0
IM_START, IM_END = -1.2, 1.2

# Create coordinate grid
re = np.linspace(RE_START, RE_END, W)
im = np.linspace(IM_START, IM_END, H)
C = re[np.newaxis, :] + 1j*im[:, np.newaxis]

Z = np.zeros_like(C)
it = np.zeros(C.shape, dtype=np.int32)

for i in range(max_iter):
    # Where still inside the radius-2 circle, iterate
    mask = np.less(np.abs(Z), 2.0)
    Z[mask] = Z[mask] * Z[mask] + C[mask]
    it[mask & (np.abs(Z) >= 2.0)] = i

# Simple color mapping
norm = it / it.max()
img = (255 * np.dstack([
    0.5 + 0.5*np.sin(6.28*(norm + 0.00)),
    0.5 + 0.5*np.sin(6.28*(norm + 0.33)),
    0.5 + 0.5*np.sin(6.28*(norm + 0.66)),
])).astype("uint8")

Image.fromarray(img).save("mandelbrot.png")
print("Saved mandelbrot.png")

What the code does (high level):

  • Builds a complex plane grid (C) matching image pixels.
  • Iterates Z = Z² + C while tracking the escape iteration in it.
  • Maps iteration counts to RGB with a quick sinusoidal palette.

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Loading Next Post...
Loading

Signing-in 3 seconds...