我正在尝试编写在 Python 3 中生成 Mandelbrot 分形图像的代码。该代码在不使用 numpy 数组的情况下工作,但速度很慢。为了加快速度,我尝试使用 numpy 和 numba。
当在 PIL 中的 3 元组 numpy 数组上使用 Image.fromarray() 时,生成的图像是一系列垂直线,而不是预期的 Mandelbrot 图像。 经过一些研究,我认为问题在于数据类型,并且可能在于有符号整数与无符号整数。如果我在 numpy 数组中存储 HSV 值的整数而不是 3 个元组,我就可以让事情正常工作。不幸的是,这给出了黑白图像,而我想要彩色图像。 另一个奇怪的事情是,每次运行代码时,代码生成的图像都会略有变化。我不确定这是一个相关的还是单独的问题。 下面是代码,经过调整以删除曼德尔布罗生成器并简单地创建一个渐变图像,这显示了问题:
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')
这是生成的图像。 Vertical Lines
当我对代码进行一些更改以便它存储整数并创建黑白图像时,它可以工作:
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')
最佳答案
根据 hpaulj 的建议,这里是回答问题的代码。 numpy 数组从 3 元组的 2d 数组更改为第三维长度为 3 的 3d 数组。dtype 在两个位置设置为“uint8”。
from PIL import Image, ImageDraw
from numba import jit
import numpy as np
@jit
def white_image(width,height):
n3 = np.empty((width, height, 3), dtype='uint8')
for i in range(width):
for j in range(height):
n3[i, j, 0] = min(j, 255)
n3[i, j, 1] = 255
n3[i, j, 2] = 255
return n3
arr = white_image(800, 600)
im = Image.new('HSV', (800, 600), (0, 0, 0))
im = Image.fromarray(arr.astype('uint8'), mode='HSV')
im.convert('RGB').save('output.png', 'PNG')
关于Python 3 PIL : Converting a Numpy array of 3-tuples to an image in HSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55107227/