stapmoshun
stapmoshun

Reputation: 134

How can I save a julia set image as png in Python?

This link to mpi documentation saves a Julia set as .pgm

Is there any way to alter this code to save the image as .png file?

from mpi4py.futures import MPIPoolExecutor

x0, x1, w = -2.0, +2.0, 640*2
y0, y1, h = -1.5, +1.5, 480*2
dx = (x1 - x0) / w
dy = (y1 - y0) / h

c = complex(0, 0.65)

def julia(x, y):
    z = complex(x, y)
    n = 255
    while abs(z) < 3 and n > 1:
        z = z**2 + c
        n -= 1
    return n

def julia_line(k):
    line = bytearray(w)
    y = y1 - k * dy
    for j in range(w):
        x = x0 + j * dx
        line[j] = julia(x, y)
    return line

if __name__ == '__main__':

    with MPIPoolExecutor() as executor:
        image = executor.map(julia_line, range(h))
        with open('julia.pgm', 'wb') as f:
            f.write(b'P5 %d %d %d\n' % (w, h, 255))
            for line in image:
                f.write(line)

Thank you

Upvotes: 0

Views: 174

Answers (1)

franklinscudder
franklinscudder

Reputation: 111

First off, add: import matplotlib.pyplot as plt

Get rid of everything below the line image = executor.map(...) and replace it with:

plt.imsave("julia.png", image)

I'm pretty sure that'll do ya, but beware I haven't run your code!

UPDATE

OK, so I had a closer look at the code and I am guessing that the 'image' variable is a tuple of bytearrays representing each line in the image. Try:

image = np.array([list(l) for l in image])

just before the plt.imsave(...) line. This converts each bytearray to a list and then packs these into an outer list. You will now also need to import numpy as np as I believe this is needed to convert the nested lists into a nice ndarray that matplotlib can save.

Upvotes: 1

Related Questions