基于python的图像颜色检测

2024-05-26 22:58:11 发布

您现在位置: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()

Tags: 代码图像名称http网站颜色examplemy
3条回答

Use a PIL (Python Image Library) histogram.在直方图上循环,并取像素计数所加权的像素颜色的平均值。

正如其他人提到的,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")

我希望能帮上忙

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

您应该使用ImageFile类中的PIL解析器从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()

这应该将图像的第一个像素的颜色的红绿色和蓝色值附加到图像名称的末尾。我把所有的东西都测试了一遍,直到出现问题为止。

相关问题 更多 >

    热门问题