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

Gra*_*ray 11 python python-imaging-library python-3.x pillow python-3.6

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

[
   [(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)]
]
Run Code Online (Sandbox Code Playgroud)

Jeb*_*bby 13

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')
Run Code Online (Sandbox Code Playgroud)

编辑:

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)
Run Code Online (Sandbox Code Playgroud)

  • 伟大的!编辑我的帖子以获得一些列表理解的乐趣,以制作具有随机像素值的图像。 (2认同)
  • 很好注意到。我会为遇到此问题的其他人更新我的答案。 (2认同)