Created
November 9, 2017 12:23
-
-
Save njanakiev/7ca262c55d41eb715de377ba636758c0 to your computer and use it in GitHub Desktop.
Mandelbrot and Julia Set with PIL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from PIL import Image | |
output_image = 'fractal.png' | |
def evalMandelbrot(x, y, n=20): | |
c = x + 1j*y | |
out, count = 0, 0 | |
for i in range(n): | |
if abs(out) <= 2: | |
out = out ** 7 + c | |
count += 1 | |
else: | |
return count | |
return count | |
def evalJuliaSet(x, y, c, n=20): | |
out = x + 1j*y | |
count = 0 | |
for i in range(n): | |
if abs(out) <= 2: | |
out = out ** 7 + c | |
count += 1 | |
else: | |
return count | |
return count | |
w, h = 600, 600 | |
# Apply antialiasing filtering through resizing the image | |
w, h = 2*w, 2*h | |
im = Image.new('RGB', (w, h), (255, 255, 255)) | |
pixels = im.load() | |
buffer = np.zeros((w, h)) | |
maxVal = 0 | |
# Calculate the Mandelbrot or Julia set | |
for i in range(w): | |
for j in range(h): | |
x, y = 2.5*(float(i)/float(w) - 0.5), 2.5*(float(j)/float(h) - 0.5) | |
# Evaluate Mandelbrot set fractal | |
val = evalMandelbrot(x, y) | |
# Evaluate Julia set fractal | |
#val = evalJuliaSet(x, y, -0.798 + 0.225j) | |
if val > maxVal: maxVal = val | |
buffer[i, j] = val | |
# Apply scaled buffer to image | |
for i in range(w): | |
for j in range(h): | |
val = buffer[i, j] | |
pixels[i, j] = tuple(int(255*(1 - val/maxVal)) for i in range(3)) | |
# Shrink to apply antialiasing to the image | |
im = im.resize((int(w/2), int(h/2)), resample=Image.ANTIALIAS) | |
im.save(output_image, 'PNG') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment