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

标签 python python-3.x python-3.6 python-imaging-library

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

[
   [(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)]
]

最佳答案

PILnumpy 是你的 friend :

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)

关于python - 如何从 Python3 中的像素值列表创建图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923244/

相关文章:

python - PyQt:如何使用 QAxWidget 通过引用发送参数

Python 代码未执行

javascript - WebSocket onmessage 未触发

python - 是什么决定了这个 python 3 代码中集合元素的顺序?

python - 在 Python 3.6 中四舍五入到特定数字

python - 将 Pandas 面板转换为数据框

python - 如何并行文件下载?

python-3.x - flask 类型错误 : argument of type 'NoneType' is not iterable

python - Keras:将生成器用于带有 model.fit_generator 的多输出模型

python - Python 中的 MemoryView 和垃圾收集