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

Zeb*_*lon 5 python image stringio python-imaging-library pillow

我有一个RGB数据列表:

cdata=[R1, G1, B1, R2, G2, B2,..., Rn, Gn, Bn]
Run Code Online (Sandbox Code Playgroud)

其中每个值都介于0到255之间。

我正在尝试使用Pillow 5.0.0将这个数组重建为图像。在Python 2下,我能够通过以下方式将值列表转换为字节字符串:

        cdata2 = []
        gidx = len(cdata)//3
        bidx = len(cdata)//3*2
        for i in range(len(cdata)//3):
            cdata2.append(cdata[i])
            cdata2.append(cdata[i+gidx])
            cdata2.append(cdata[i+bidx])

        data = ""
        for c in cdata2:
            data += chr(c)

        im = Image.frombytes("RGB", (420, 560), data)
Run Code Online (Sandbox Code Playgroud)

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

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

UnicodeEncodeError: 'charmap' codec can't encode characters in position 42099-42101: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

此外,Pillow 5文档现在建议使用

im = Image.open(StringIO(data))
Run Code Online (Sandbox Code Playgroud)

但无法使其与上面构建的我的字符串一起使用。还有其他更聪明的方法吗?在此先感谢您的帮助。

PM *_*ing 6

这是使用的示例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')
Run Code Online (Sandbox Code Playgroud)

输出

色相和饱和度演示图像