2017-02-12 48 views
3

我試圖從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的格式( )不同於我爲列表獲取像素的方式。我怎樣才能得到正確的圖片?

回答

2

getpixel,putpixel基於x-y座標,而getdata,putdata基於行列爲基礎。

首先,你需要做基於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') 

BTW,而不是混合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') 
+0

謝謝。有用。 –

+0

@CaiphasKain,不客氣。快樂的Python編程。 – falsetru