|
| 1 | +import numpy as np |
| 2 | +from PIL import Image |
| 3 | +from scipy.interpolate import interp1d |
| 4 | + |
| 5 | +from mandelbrot_03 import MandelbrotSet |
| 6 | +from viewport import Viewport |
| 7 | + |
| 8 | + |
| 9 | +def paint(mandelbrot_set, viewport, palette, smooth): |
| 10 | + for pixel in viewport: |
| 11 | + stability = mandelbrot_set.stability(complex(pixel), smooth) |
| 12 | + index = int(min(stability * len(palette), len(palette) - 1)) |
| 13 | + pixel.color = palette[index % len(palette)] |
| 14 | + |
| 15 | + |
| 16 | +def denormalize(palette): |
| 17 | + return [ |
| 18 | + tuple(int(channel * 255) for channel in color) for color in palette |
| 19 | + ] |
| 20 | + |
| 21 | + |
| 22 | +def make_gradient(colors, interpolation="linear"): |
| 23 | + X = [i / (len(colors) - 1) for i in range(len(colors))] |
| 24 | + Y = [[color[i] for color in colors] for i in range(3)] |
| 25 | + channels = [interp1d(X, y, kind=interpolation) for y in Y] |
| 26 | + return lambda x: [np.clip(channel(x), 0, 1) for channel in channels] |
| 27 | + |
| 28 | + |
| 29 | +if __name__ == "__main__": |
| 30 | + print("This might take a while...") |
| 31 | + |
| 32 | + black = (0, 0, 0) |
| 33 | + blue = (0, 0, 1) |
| 34 | + maroon = (0.5, 0, 0) |
| 35 | + navy = (0, 0, 0.5) |
| 36 | + red = (1, 0, 0) |
| 37 | + |
| 38 | + colors = [black, navy, blue, maroon, red, black] |
| 39 | + gradient = make_gradient(colors, interpolation="cubic") |
| 40 | + |
| 41 | + num_colors = 256 |
| 42 | + palette = denormalize( |
| 43 | + [gradient(i / num_colors) for i in range(num_colors)] |
| 44 | + ) |
| 45 | + |
| 46 | + mandelbrot_set = MandelbrotSet(max_iterations=20, escape_radius=1000) |
| 47 | + image = Image.new(mode="RGB", size=(512, 512)) |
| 48 | + viewport = Viewport(image, center=-0.75, width=3.5) |
| 49 | + paint(mandelbrot_set, viewport, palette, smooth=True) |
| 50 | + image.show() |
0 commit comments