使用python进行图像颜色检测

use*_*470 18 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()
Run Code Online (Sandbox Code Playgroud)

olo*_*ney 12

使用PIL(Python图像库)直方图.循环直方图并获取像素数量的像素颜色的平均值.

  • 在回答后续问题时,这是一个展示这种方法的工作示例:https://gist.github.com/1246268 (4认同)

luc*_*luc 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")
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助

更新:将256传递给getcolors对于非常小的图像是可以的,但在大多数情况下可能不起作用.对于较大的图像,必须增加该值.例如,1024*1024可用于400像素*300像素图像.


Jus*_*eel 6

您应该使用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()
Run Code Online (Sandbox Code Playgroud)

这应该将图像的第一个像素的颜色的红色绿色和蓝色值附加到图像名称的末尾.我测试了一切直到fout线.