我一直在尝试将RGB值的整数数组转换为PNG图像。如何从以下整数数组生成以下图像?
'''This is a 3D integer array. Each 1D array inside this array is an RGBA value'''
'''Now how can I convert this RGB array to the PNG image shown above?'''
rgbArray = [
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
]
答案 0 :(得分:5)
您可以使用Python Imaging Library将RGB数据点转换为大多数标准格式。
from PIL import Image
newimage = Image.new('RGB', (len(rgbArray[0]), len(rgbArray))) # type, size
newimage.putdata([tuple(p) for row in rgbArray for p in row])
newimage.save("filename.png") # takes type from filename extension
产生:
.save()
方法也可以采用格式参数,PNG
会将输出修复为PNG。
(我建议您安装Pillow fork,因为它更积极地维护并添加适当的打包和Python 3支持。)
答案 1 :(得分:1)
Python Imaging Library (PIL)对于Python中的大多数成像需求都很方便。 Image module包含fromstring
函数和save
函数,它应该完全符合您的要求。