2010-02-16 122 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值。 –