2011-01-10 49 views
4

Python中如何獲取一個圖像Python中如何獲取一個圖像

我用PIL,我想有顏色的字典,在用於使用的顏色列表顏色列表此圖像包括其使用的顏色(鍵)和像素點的數量。

如何做到這一點?

回答

3

我已經使用類似下面的幾次來分析圖:

>>> from PIL import Image 
>>> im = Image.open('polar-bear-cub.jpg') 
>>> from collections import defaultdict 
>>> by_color = defaultdict(int) 
>>> for pixel in im.getdata(): 
...  by_color[pixel] += 1 
>>> by_color 
defaultdict(<type 'int'>, {(11, 24, 41): 8, (53, 52, 58): 8, (142, 147, 117): 1, (121, 111, 119): 1, (234, 228, 216): 4 

即,有8個像素與RBG值(11,24,41),等等。

21

getcolors方法應該做的伎倆。請參閱the docs

Image.open('file.jpg').getcolors() => a list of (count, color) tuples or None 
+3

嘿嘿,我得到一種怪異的結果:它返回(int數組, int)元組..我怎麼能得到r,g,b從一個單一的int? PS:我有一個GIF文件 – nkint 2011-02-27 14:39:05

+3

你可能有一個調色板圖像 - 你可以做im.convert()通過調色板的顏色轉換成一個模式,讓你看到所有的樂隊 – jlivni 2012-07-16 18:55:56

+0

鏈接文檔被打破了。 – 2018-02-13 00:33:09

6

我想補充一點,.getcolors()函數只適用於圖像處於某種類型的RGB模式。

我有這個問題,它會返回一個元組列表(顏色只是一個數字)的元組列表。花了我一段時間才找到它,但這固定了它。

from PIL import Image 
img = Image.open('image.png') 
colors = img.convert('RGB').getcolors() #this converts the mode to RGB 
0

https://github.com/fengsp/color-thief-py「抓鬥從圖像中主色或者代表色調色板使用Python和枕頭」

from colorthief import ColorThief 

color_thief = ColorThief('/path/to/imagefile') 
# get the dominant color 
dominant_color = color_thief.get_color(quality=1) 
# build a color palette 
palette = color_thief.get_palette(color_count=6)