I am trying to write code that makes an image of the Mandelbrot fractal in Python 3. The code was working without use of numpy arrays but slowly. To speed it up, I've tried using numpy and numba.
When using Image.fromarray() in PIL on a numpy array of 3-tuples, the resulting image is a series of vertical lines rather than the expected Mandelbrot image. After some research, I think the issue is with data types and possibly with signed versus unsigned integers. I can get things to work if I store ints instead of 3 tuples for the HSV values in the numpy array. Unfortunately, this gives a black and white image and I want a colourful image. The other strange thing is that the image the code produces changes slightly each time I run it. I'm not sure if that is a related or separate issue. Here's code, adjusted to remove the mandelbrot generator and simply create a gradient image, that shows the problem:
from PIL import Image, ImageDraw
from numba import jit
import numpy as np
@jit
def simple_image(width,height):
n3 = np.empty((width, height), dtype=object)
for i in range(width):
for j in range(height):
n3[i, j] = (min(j, 255), 255, 255)
return n3
arr = simple_image(800, 600)
im = Image.new('HSV', (800, 600), (0, 0, 0))
im = Image.fromarray(arr.astype(object), mode='HSV')
im.convert('RGB').save('output.png', 'PNG')
Here is the image that is generated. Vertical Lines
When I make a few changes to the code so that it stores ints and creates a black and white image, it works:
from PIL import Image, ImageDraw
from numba import jit
import numpy as np
@jit
def simple_image(width,height):
n3 = np.empty((width, height))
for i in range(width):
for j in range(height):
n3[i, j] = min(j, 255)
return n3
arr = simple_image(800, 600)
im = Image.new('HSV', (800, 600), (0, 0, 0))
im = Image.fromarray(arr)
im.convert('RGB').save('output.png', 'PNG')