从列表

时间:2017-02-12 03:28:22

标签: python python-imaging-library pillow

我试图在Python中创建一个包含1和0的列表的图像。

from PIL import Image

img1 = Image.open('Image1.gif') #the image is strictly black and white
img1_size = img1.size 
img1_k = []
for i in range(img1_size[0]): 
    for j in range(img1_size[1]): 
        tmp_pix = img1.getpixel((i,j))
        if (tmp_pix>127): 
            img1_k.append(1)
        else:
            img1_k.append(0)


img = Image.new('RGB', (img1_size[1],img1_size[0]), "white") 
cmap = {1: (255,255,255),
        0: (0,0,0)}
data = [cmap[i] for i in img1_k]
img.putdata(data)
img.show()             
img.save('Image2.png')

然而,而不是原始图像:

enter image description here

代码生成旋转和反转的图像:

enter image description here

我猜测putdata()的格式与我获取列表像素的方式不同。我怎样才能正确理解图片?

1 个答案:

答案 0 :(得分:2)

getpixelputpixel基于x-y坐标,getdataputdata基于行列。

首先,您需要基于img_k行列:

for j in range(img1_size[1]):     # row (y)
    for i in range(img1_size[0]): # column (x)
        tmp_pix = img1.getpixel((i,j))
        if tmp_pix > 127:
            img1_k.append(1)
        else:
            img1_k.append(0)

其次,您需要创建x * y大小的图像:

img = Image.new('RGB', (img1_size[0], img1_size[1]), "white")  # <--
# OR  Image.new('RGB', img1.size, "white") 
cmap = {1: (255,255,255),
        0: (0,0,0)}
data = [cmap[i] for i in img1_k]
img.putdata(data)
img.show()             
img.save('Image2.png')

顺便说一下,使用getpixelputdata代码可以更简单,而不是混合getdataputdata

from PIL import Image

img1 = Image.open('Image1.gif')
data = [(255, 255, 255) if pixel > 127 else (0, 0, 0) for pixel in img1.getdata()]
img = Image.new('RGB', img1.size, "white") 
img.putdata(data)
img.show()             
img.save('Image2.png')