Keshav Agarwal
Keshav Agarwal

Reputation: 821

Generate fractals with python

I want to generate fractals of an image like this using python. The code that I found generates normal fractals and I've been unable to find any help on how to replicate the fractals for an image. The code used for generating the fractals is -

from numpy import *

def mandel(n, m, itermax, xmin, xmax, ymin, ymax):

    ''' 
    (n, m) are the output image dimensions
    itermax is the maximum number of iterations to do
    xmin, xmax, ymin, ymax specify the region of the
    set to compute.
    '''

    ix, iy = mgrid[0:n, 0:m]
    x = linspace(xmin, xmax, n)[ix]
    y = linspace(ymin, ymax, m)[iy]
    c = x+complex(0,1)*y
    del x, y
    img = zeros(c.shape, dtype=int)
    ix.shape = n*m
    iy.shape = n*m
    c.shape = n*m
    z = copy(c)
    for i in xrange(itermax):
        if not len(z):
            break
        multiply(z, z, z)
        add(z, c, z)
        rem = abs(z)>2.0
        img[ix[rem], iy[rem]] = i+1
        rem = -rem
        z = z[rem]
        ix, iy = ix[rem], iy[rem]
        c = c[rem]
    return img

if __name__=='__main__':
    from pylab import *
    import time
    start = time.time()
    I = mandel(512, 512, 100, -2, .5, -1.25, 1.25)
    print 'Time taken:', time.time()-start
    I[I==0] = 101
    img = imshow(I.T, origin='lower left')
    img.write_png('../images/mandel.png')
    show()

I need to know how can I use a base image around which the fractals are to be built. Can someone please point me in the right direction?

Upvotes: 2

Views: 1924

Answers (1)

Searles
Searles

Reputation: 1817

It is called Orbit Trap. Basically, inside the loop you have the current orbit value z. For each value in the orbit (so, every value of z) check whether this value corresponds to some coordinate inside the image. If yes, then you return the corresponding color of this pixel. The rest is completely the same as for the normal escape time algorithm.

I use C++-alike pseudo code to illustrate the simplest case of it: scale(int x, int y) is a function that returns a complex number that corresponds to the coordinates of x, y, unscale is its counter part.

int getcolor(int x, int y, int maxiter) {
    complex z = 0;
    complex c = scaled(x, y)
    for(int i = 0; i < maxiter; ++i) {
        z = z * z + c;

        // these 3 lines are where the magic happens
        if(unscale(z) is within image bounds) { 
            color = image[unscale(z)];
            return color;
        }

        if(abs(z) > 2) return color based on i;
    }
    return 0; // lake
}

I can't really follow your python code with all the list comprehensions.

Once you got it running, there is plenty of things to discover and modify. Wikipedia has some more general information https://en.wikipedia.org/wiki/Orbit_trap Also, this blog might give you more insights: http://iquilezles.org/www/articles/ftrapsbitmap/ftrapsbitmap.htm

Upvotes: 1

Related Questions