gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:51 26 4
gpt4 key购买 nike

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

[
[(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com