使用Pillow和Python3从RGB列表创建图像

2024-04-27 07:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个RGB数据列表:

cdata=[R1, G1, B1, R2, G2, B2,..., Rn, Gn, Bn]

其中每个值都包含在0到255之间。在

我正在尝试使用Pillow5.0.0将此阵列重建为图像。 在Python 2下,我可以通过以下方式将值列表转换为字节字符串:

^{pr2}$

然后在base64中重新编码“im”,并在HTML模板中显示为PNG。在

不幸的是,这在Python 3中不起作用,我遇到了如下错误:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 42099-42101: character maps to <undefined>

此外,Pillow5文档现在建议使用

im = Image.open(StringIO(data))

但不能让我的绳子在上面工作。有没有比这更聪明的方法呢?提前非常感谢你的帮助。在


Tags: 数据图像列表rgbrnb2b1r2
3条回答

如果您想拥有与Python2和Python3兼容的代码,可以使用struct或array module:

# Works from Python 2.5 (maybe earlier) to Python 3.x
import struct
cdata = [...]
bindata = struct.pack("<%dB" % len(cdata), *cdata)
# And then use PIL's Image.frombytes() to construct the Image() from bindata

或者:

^{pr2}$

使用^{}Image.open用于打开编码图像(如jpg或png),而不是原始RGB数据。在


使用bytes构造函数构造所需的字节数据非常简单:

img_bytes = bytes([R1, G1, B1, R2, G2, B2,..., Rn, Gn, Bn])

然后我们可以创建这样的图像:

^{pr2}$

下面是一个使用frombytes的示例。这只是使用纯Python,而不是Numpy。如果使用Numpy创建RGB值,那么可以使用Image.fromarray方法将Numpy数据转换为PIL图像。在

这里的重要步骤是将RGB值列表转换为bytes对象,这很容易通过将其传递给bytes构造函数来完成。在

from colorsys import hsv_to_rgb
from PIL import Image

# Make some RGB values. 
# Cycle through hue vertically & saturation horizontally
colors = []
for hue in range(360):
    for sat in range(100):
        # Convert color from HSV to RGB
        rgb = hsv_to_rgb(hue/360, sat/100, 1)
        rgb = [int(0.5 + 255*u) for u in rgb]
        colors.extend(rgb)

# Convert list to bytes
colors = bytes(colors)
img = Image.frombytes('RGB', (100, 360), colors)
img.show()
img.save('hues.png')

输出

hue & saturation demo image

相关问题 更多 >