''' Python code for Mandelbrot Fractal. Notice that functions can be defined inside a main program. Adapted from site GeeksforGeeks.org ''' from PIL import Image from numpy import complex, array import colorsys # setting the width of the output image as 1024 WIDTH = W = 1024 # return a tuple of colors as integer values of rgb color index def rgb_conv(i): color = 255 * array(colorsys.hsv_to_rgb(i/255., 1.0, 0.5)) return tuple(color.astype(int)) # function computing one Mandelbrot fractal's pixel def mandelbrot(x, y): c0 = complex(x, y) c = 0 for i in range(1, 1000): if abs(c) > 2: return rgb_conv(i) c = c*c + c0 return (0, 0, 0) # creating the new image in RGB mode img = Image.new('RGB', (WIDTH, WIDTH//2)) pixels = img.load() # double loop over pixels for x in range(img.size[0]): # img.size[0] is the x dimension # displaying the progress as percentage every 25th x if (x%25==0): print("%.2f %%" %(x/W*100.)) for y in range(img.size[1]): # img.size[1] is the y dimension pixels[x, y] = mandelbrot((x-0.75*W)/(W/4), (y-(W/4))/(W/4)) # array filled, show the map img.show()