Monday 21 August 2023

Implementing smooth colouring in mandelbrot set

I am trying to colour MandelBrot using HSV values and the PIL Library.

Even after multiple tries fiddling with HSV values, I could not achieve the desired effect.

here is what I currently have

Current.png

Here is the desired effect

Desired.png

This is the code that I am trying, It could also be beneficial if you could add some tips to optimise the below code to compute the set faster, I am new to python

from PIL import Image
import random
import math
from decimal import Decimal


# Size of the Image Canvas
HEIGHT = 500

ZOOM = 0.0
Y_PAN = 0.0


# Range of the Complex Plane
MIN_X = -2.0 + ZOOM
MAX_X = 2.0 - ZOOM


MAX_Y = 2.0 + Y_PAN - ZOOM
MIN_Y = -2.0 + Y_PAN + ZOOM

DATA = []


def map_to_scale_d(x, in_min, in_max, out_min, out_max):
    # returns float
    return float((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)


def map_to_scale(x, in_min, in_max, out_min, out_max):
    # returns int
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min


# Max iterations till Zn
ITER = 200

# loop to traverse every single point in Canvas
for y in xrange(HEIGHT):
    for x in xrange(HEIGHT):

        # convert to complex plane scale
        a = map_to_scale_d(x, 0, HEIGHT, MIN_X, MAX_X)
        b = map_to_scale_d(y, 0, HEIGHT, MAX_Y, MIN_Y)

        # original values
        _a = a  
        _b = b  

        counter = 0
        # start the iteration at (a,b) in complex plane
        # calculate z^2 + c
        while(counter < ITER):

            aa = a * a - b * b
            bb = 2 * a * b

            a = aa + _a
            b = bb + _b

            if((abs(aa + bb)) > 4):
                break

            counter = counter + 1

        # initialise color
        h = 0
        s = map_to_scale(counter, 0, ITER, 0, 100)
        v = map_to_scale(counter, 0, ITER, 0, 100)

        if(counter == ITER):
            h = 0
            s = 0
            v = 0

        # convert to 8-bit
        h = map_to_scale(h, 0, 360, 0, 255)
        s = map_to_scale(s, 0, 100, 0, 255)
        v = map_to_scale(v, 0, 100, 0, 255)

        DATA.append((h, s, v))

img = Image.new('HSV', (HEIGHT, HEIGHT))

img.putdata(DATA)
img.show()
img.convert('RGB').save('test.png')


from Implementing smooth colouring in mandelbrot set

No comments:

Post a Comment