将列表另存为python中的图像

问题描述 投票:0回答:2

我正在尝试将2D列表另存为python中的图像(灰度图像),因此数组中的0值为黑色,而255为白色。例如:

255 255 255
255  0  255
255  0  255
255  0  255
255 255 255 

将保存类似l的形状。我已经尝试过使用PIL库的以下代码,如栈溢出的其他问题所建议:

WIDTH, HEIGHT = img.size
imgData = list(img.getdata()) 
imgData = [imgData[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]
#to print the image 
for row in data:
    print(' '.join('{:3}'.format(value) for value in row))
imgData = np.array(imgData)
**IMG VALUES AUGMENTED HERE**
newimg = Image.new('L', (WIDTH, HEIGHT), 'white')
newimg.putdata(imgData)
newimg.save('C:/File/Name.png')

但是,此创建的图像完全不反映列表。如果我要将0和255放在不同的位置,则会创建相同的图像。有人知道解决方案吗?

python image-processing python-imaging-library
2个回答
0
投票

而不是:

newimg.putdata(imgData)

您需要此行:

newimg.putdata([j[0] for i in imgData for j in i])

灰度数据是在1d列表中指定的,而不是在2d列表中指定的。

这将创建列表:

>>> [j[0] for i in imgData for j in i]
[255, 255, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 255, 255]

哪个是:

[255, 255, 255,
 255,  0 , 255, 
 255,  0 , 255, 
 255,  0 , 255, 
 255, 255, 255]

编辑如果用imgData编辑imgData[0][0] = [0, 0, 0, 255],则上述解决方案有效。如果您要使用imgData编辑imgData[0][0] = 0,则需要将其设置为:

[j[0] if hasattr(j, '__iter__') else j for i in imgData for j in i]

或者,您可以通过以下方法使它更好:

imgData = np.array([[j[0] for j in i] for i in imgData])
imgData[0][0] = 0
newimg.putdata(imgData.flatten())

0
投票

由于您的示例缺少任何输入数据,因此我按照您的描述将其键入,制作了图像,然后将其放大。我还人为地添加了一个红色边框,以便您可以在StackOverflow的白色背景上看到它的程度:

#!/usr/bin/env python3

from PIL import Image
import numpy as np

pixels = [[255,255,255],
          [255,0,255],
          [255,0,255],
          [255,0,255],
          [255,255,255]]

# Make list of pixels into Image
im = Image.fromarray(np.array(pixels,dtype=np.uint8))
im.save('result.png')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.