如何从Python3中的像素值列表创建图像?

问题描述 投票:3回答:2

如果我有以下格式的图像像素行列表,如何获取图像?

[
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]
python python-3.x python-imaging-library python-3.6 pillow
2个回答
3
投票

PILnumpy是你的朋友:

from PIL import Image
import numpy as np


pixels = [
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]

# Convert the pixels into an array using numpy
array = np.array(pixels, dtype=np.uint8)

# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array)
new_image.save('new.png')

编辑:

使用numpy制作随机像素图像有点乐趣:

from PIL import Image
import numpy as np

def random_img(output, width, height):

    array = np.random.random_integers(0,255, (height,width,3))  

    array = np.array(array, dtype=np.uint8)
    img = Image.fromarray(array)
    img.save(output)


random_img('random.png', 100, 50)

0
投票

我自己没有使用PIL,但最好的方法是使用PIL打开一个实际的图像文件。然后探索打开所述图像所涉及的API和对象,并查看像素值如何存储在与API相关的特定对象中。

然后,您可以使用提取的RGB值构造有效的PIL图像对象。

编辑:请参阅以下帖子:How do I create an image in PIL using a list of RGB tuples?

另外,访问PIL中的像素值:https://pillow.readthedocs.io/en/4.3.x/reference/PixelAccess.html

© www.soinside.com 2019 - 2024. All rights reserved.