繁体   English   中英

Python 3 PIL:将 3 元组的 Numpy 数组转换为 HSV 中的图像

[英]Python 3 PIL: Converting a Numpy array of 3-tuples to an image in HSV

我正在尝试编写代码来制作 Python 3 中的 Mandelbrot 分形图像。该代码在不使用 numpy arrays 的情况下工作,但速度很慢。 为了加快速度,我尝试使用 numpy 和 numba。

在 PIL 中的 Image.fromarray() 中使用 numpy 数组的 3 元组时,生成的图像是一系列垂直线,而不是预期的 Mandelbrot 图像。 经过一些研究,我认为问题出在数据类型上,并且可能与有符号整数和无符号整数有关。 如果我在 numpy 数组中存储 HSV 值的整数而不是 3 个元组,我可以让事情正常工作。 不幸的是,这给出了一个黑白图像,我想要一个彩色图像。 另一个奇怪的事情是,每次运行代码时,代码生成的图像都会略有变化。 我不确定这是一个相关的还是单独的问题。 这是代码,经过调整以删除 mandelbrot 生成器并简单地创建一个渐变图像,它显示了问题:

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')

这是生成的图像。 垂直线

当我对代码进行一些更改以存储整数并创建黑白图像时,它可以工作:

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')

这个问题正在解决一个特定于将 numba 与 PIL 一起使用的问题

如果有人从谷歌那里被引导到这篇文章,寻找一种从数组创建 HSV 图像的简单方法,这里有一个修改后的解决方案,它删除了使用 numba 所特别需要的东西:

from PIL import Image, ImageDraw
import numpy as np 

def color_image(width,height):
    img = np.empty((height, width, 3), dtype='uint8')
    for y in range(height):
        for x in range(width):
            img[y, x, 0] = int(255*x/width)
            img[y, x, 1] = int(255*y/height)
            img[y, x, 2] = 255
    return img 

arr = color_image(800, 600) 

im = Image.fromarray(arr, mode='HSV')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM