如何将 png 图像转换为 RGBA 颜色列表列表?

时间:2021-05-16 15:58:15

标签: python list image python-imaging-library pixel

我搜索了一种读取 png 文件的方法,并制作了一个二维列表矩阵,表示图像中每个像素的颜色。 类似的东西:

import image #image library dosen't exist just for example

myimage = image.load("/document/pycharm_projects/images/pixel_avatar.png") #5x6 px image

size = myimage.size.get() #return (5, 6)
width = size[0]  # 5
height = size[1] # 6

result = []

for y in range(height):
    result.append([])
    for x in range(width):
        pixel_color = myimage.pixel((x, y)).get_rgba() # get the color of the pixel
        result[y].append(pixel_color)

获得:

[
    ["#00000000", "#000000FF", "#00000000", "#000000FF", "#00000000"],
    ["#00000000", "#000000FF", "#00000000", "#000000FF", "#00000000"],
    ["#00000000", "#000000FF", "#00000000", "#000000FF", "#00000000"],
    ["#00000000", "#00000000", "#00000000", "#00000000", "#00000000"],
    ["#000000FF", "#00000000", "#00000000", "#00000000", "#000000FF"],
    ["#00000000", "#000000FF", "#000000FF", "#000000FF", "#00000000"]
]

示例图片(大 100 倍):pixel_avatar.png

我该怎么做?

附加信息:
使用最新版本的python 3.7。
在这个表示中可以是颜色(255, 255, 255, 100)我不在乎。
结果将转换为json文件。

1 个答案:

答案 0 :(得分:1)

以下是如何使用 Pillow fork of the PIL(Python 成像库)进行操作 - 对于您不熟悉的实例,我不相信。

from PIL import Image
from pprint import pprint

image_filepath = 'pixel_avatar.png'

print('image file:', image_filepath)
myimage = Image.open(image_filepath)

width, height = myimage.size
print(f'size: {width} x {height}')

pixels = [['#' + bytearray(myimage.getpixel((x, y))).hex() for x in range(width)]
              for y in range(height)]
print('data:')
pprint(pixels)

打印输出:

image file: pixel_avatar.png
size: 5 x 6
data:
[['#00000000', '#000000ff', '#00000000', '#000000ff', '#00000000'],
 ['#00000000', '#000000ff', '#00000000', '#000000ff', '#00000000'],
 ['#00000000', '#000000ff', '#00000000', '#000000ff', '#00000000'],
 ['#00000000', '#00000000', '#00000000', '#00000000', '#00000000'],
 ['#000000ff', '#00000000', '#00000000', '#00000000', '#000000ff'],
 ['#00000000', '#000000ff', '#000000ff', '#000000ff', '#00000000']]

相关问题