2010-02-16 125 views
15

從網站下載圖像後,我需要檢測下載的圖像的顏色。我成功下載了圖像,但我需要檢測相應圖像的顏色並將其保存在名稱中使用的代碼如下。請告訴我如何從當前位置實現它。使用Python的圖像顏色檢測

imageurl='http://www.example.com/' 
opener1 = urllib2.build_opener() 
page1=opener1.open(imageurl) 
my_picture=page1.read() 
fout = open('images/tony'+image[s], "wb") 
fout.write(my_picture) 
fout.close() 
+0

你是什麼意思的圖像的顏色 - 圖像完全是一種顏色? –

+0

雅形象完全是一種顏色...... – user244470

+0

目前還不清楚 - 你想要平均顏色還是最常見的顏色? –

回答

9

正如其他人所提到的,PIL是合適的庫。這是一個打開圖像並查找主要顏色的功能。

def get_main_color(file): 
    img = Image.open(file) 
    colors = img.getcolors(256) #put a higher value if there are many colors in your image 
    max_occurence, most_present = 0, 0 
    try: 
     for c in colors: 
      if c[0] > max_occurence: 
       (max_occurence, most_present) = c 
     return most_present 
    except TypeError: 
     raise Exception("Too many colors in the image") 

我希望它能幫助

更新:經過256 getcolors是確定的非常小的圖像,但可能不會在大多數情況下工作。對於更大的圖像,此值必須增加。例如,對於400像素×300像素圖像,1024×1024是可以的。

5

您應該使用ImageFile類中的PIL的Parser從url中讀取文件。那麼生活是很容易的,因爲你說整個圖像是相同的顏色。下面是一些代碼,建立在你的代碼:

import urllib2 
import ImageFile 

image_url = "http://plainview.files.wordpress.com/2009/06/black.jpg" 
opener1 = urllib2.build_opener() 
page1=opener1.open(image_url) 

p = ImageFile.Parser() 

while 1: 
    s = page1.read(1024) 
    if not s: 
     break 
    p.feed(s) 

im = p.close() 
r,g,b = im.getpixel((0,0)) 

fout = open('images/tony'+image[s]+"%d%_d%_d"%(r,g,b), "wb") 
fout.write(my_picture) 
fout.close() 

這應該圖像的第一個像素的顏色的紅,綠和藍色值追加到圖像名稱末尾。我測試了所有東西,直到fout線。

+0

感謝賈斯汀你的回覆真的幫了很多。實際上,我得到了文件名紅綠色和藍色值的圖像的給定像素的顏色。是否有可能獲得該圖像的實際顏色名稱給定像素....或者我們可以將獲得的像素轉換爲相應的顏色名稱 關於 Arun – user244470

+1

您需要製作一個字典,其中的RGB值作爲鍵和名稱作爲值。你可以使用這個網站的顏色列表,也許是http://en.wikipedia.org/wiki/List_of_colors。您將使用urllib2來檢索名稱和相應的RGB值。 –