2014-11-23 26 views
1

我有一堆地圖文件,我從Google地圖以png格式下載,我想將其轉換爲單個較大圖像。當我導入一個,我看着像素,我看到像素是一個單一的數字,範圍在0..256而不是三個值列表。這裏發生了什麼?PIL導入png像素作爲單個值而不是3個值向量

我使用

from PIL import Image 

print open('b1.png').load()[0,0] 

,我得到153而非[R,G,B]

我的圖像文件是enter image description here

回答

4

這樣的結果(在[0,0]值153)的原因是,圖像模式被設定爲P(8位PIX els,使用調色板映射到任何其他模式)。如果您要設置不同的模式(例如RGB),則可以在調用方法load()之前執行此操作。

這裏是如何做到這一點的例子:

from PIL import Image 
file_data = Image.open('b1.png') 
file_data = file_data.convert('RGB') # conversion to RGB 
data = file_data.load() 
print data[0,0] 

和打印的結果是

(240, 237, 229) 

有關圖像模式,請訪問the documentation更多信息。

+0

謝謝。我可以在不使用''file_data = Image.open('b1.png')。'convert('RGB')''的情況下直接在''RGB''模式下讀取png文件嗎? – Yotam 2014-11-24 08:29:59

+1

你好,我不知道是否有可能,並且如果可以爲所有圖像設置默認模式。在這種情況下,這個.png圖像的顏色空間設置爲索引顏色,這就是爲什麼它在P模式下加載並需要轉換爲RGB模式才能獲得(r,g,b)元組。 – dropp 2014-11-24 11:36:57

2

你的圖像是mode=P。它具有在調色板中定義的顏色。

>>> Image.open('b1.png') 
<PIL.PngImagePlugin.PngImageFile image mode=P size=640x640 at 0x101856B48> 

你想要一個RGB值。第一轉換爲RGB:

>>> im = Image.open('b1.png') 
>>> im = im.convert('RGB') 
>>> im.getpixel((1,1)) 
(240, 237, 229) 

從文檔:http://pillow.readthedocs.org/en/latest/handbook/concepts.html?highlight=mode

P(8比特象素,映射到使用調色板任何其他模式)
...
RGB(3×8位像素,真彩色)

相關問題