使用Python进行图像颜色检测

19 投票
7 回答
72664 浏览
提问于 2025-04-15 19:20

我需要识别一张在线图片的颜色,并把识别到的颜色保存到文件名里。

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()

7 个回答

6

你应该使用PIL中的ImageFile类的解析器来从网址读取文件。这样做之后就简单多了,因为你提到整张图片都是同一种颜色。下面是一些基于你代码的示例:

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的那几行。

11

正如其他人提到的,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是可以的,但在大多数情况下可能不太管用。这个值对于更大的图片需要增加。例如,1024*1024的值对于400像素*300像素的图片就合适。

12

可以使用PIL(Python图像库)来生成图像的直方图。然后,遍历这个直方图,计算每种颜色的平均值,计算时要考虑每种颜色的像素数量。

撰写回答