如何使用 Python2 PIL 将每个单独 RGB 值的 .json 列表转换为 PNG



我的列表包含这样的值。

[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0], [2, 0, 1], [3, 1, 2], [6, 3, 5], [9, 6, 8], [12, 9, 11], [13, 9, 12], [13, 10, 13], [13, 10, 14], [13, 11, 14], [13, 11, 15], [12, 11, 15]]

例如。。

如何循环浏览它们并查看每个 RGB 值,然后将每个值输出到 Python 中的 PNG 中?

import json
with open('average.json') as json_data:
    d = json.load(json_data)
    print(d)

到目前为止,我已经设法做到了这一点。我是否添加 while 循环?还是循环?

按@DIEGO提供的解决方案:

from PIL import Image
import json
with open('average.json') as json_data:
    d = json.load(json_data)
OUTPUT_IMAGE_SIZE = (1280, 720)
# Then we iterate over the color (and the frame numbers, that's the role of enumerate)
for frame_number, color in enumerate(d):
    # PIL wants tuples for colors, not lists
    color = tuple(color)
    # we create a new RGB image with a default color, ie. the full image will be the color we want
    image = Image.new('RGB', OUTPUT_IMAGE_SIZE, color=color)
    # we save it 
    image.save(str(frame_number) + '.png')

由于最后@Ico条评论而编辑

在python中操作图像的一种方法是使用PIL模块

from PIL import Image
d = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0],
     [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0], [2, 0, 1], [3, 1, 2], [6, 3, 5], [9, 6, 8], [12, 9, 11],
     [13, 9, 12], [13, 10, 13], [13, 10, 14], [13, 11, 14], [13, 11, 15], [12, 11, 15]]
OUTPUT_IMAGE_SIZE = (1280, 72)
# Then we iterate over the color (and the frame numbers, that's the role of enumerate)
for frame_number, color in enumerate(d):
    # PIL wants tuples for colors, not lists
    color = tuple(color)
    # we create a new RGB image with a default color, ie. the full image will be the color we want
    image = Image.new('RGB', (len(d), 1), color=color)
    # we save it 
    image.save(str(frame_number) + '.png')    

评论是不言自明的。
因此,您将平均颜色的所有图像保存为 [数字帧].png

也许你应该编辑你的问题,这不是很清楚! :)

最新更新