如何循环直方图以获得图片的颜色?

时间:2011-09-27 01:39:27

标签: python google-app-engine histogram

In this answer关于检测图像的颜色olooney表示“在直方图上循环并取像素颜色的平均像素数”。

我像这样运行直方图:

class ImageResize(webapp.RequestHandler):
    def get(self):
        q = HomePage.all()
        q.filter("firm_name", "noise")
        qTable = q.get()
        id = qTable.key().id()
        if id:
            homepage = HomePage.get_by_id(id)
            if homepage:
                img = images.Image(homepage.thumbnail)
                hist = img.histogram()

然后在IDLE中,对于直方图hist2的每种颜色,我试图得到平均值并除以像素数,但我得到相同的数字。我做错了什么?

>>> average_red = float(sum(hist2[0]))/len(hist2[0])
>>> average_red
789.2578125
>>> average_green = float(sum(hist2[1]))/len(hist2[1])
>>> average_green
789.2578125
>>> average_blue = float(sum(hist2[2]))/len(hist2[2])
>>> average_blue
789.2578125
>>>

更新

感谢Saxon Druce the answer。这是我使用的代码:

>>> def hist_weighed_average(hist):
    red_hist = hist[0]
    green_hist = hist[1]
    blue_hist = hist[2]

    red_weighed_sum = float(sum(i * red_hist[i] for i in range(len(red_hist))))
    green_weighed_sum = float(sum(i * green_hist[i] for i in range(len(green_hist))))
    blue_weighed_sum = float(sum(i * blue_hist[i] for i in range(len(blue_hist))))

    red_num_pixels = float(sum(red_hist))
    green_num_pixels = float(sum(green_hist))
    blue_num_pixels = float(sum(blue_hist))

    red_weighed_average = red_weighed_sum / num_pixels
    green_weighed_average = green_weighed_sum / num_pixels
    blue_weighed_average = blue_weighed_sum / num_pixels
    return red_weighed_average, green_weighed_average, blue_weighed_average
>>> hist = hist3
>>> hist_weighed_average(hist)
(4.4292897797574859, 4.8236723583271468, 5.2772779015095272)
>>> hist = hist2
>>> hist_weighed_average(hist)
(213.11471417965851, 220.01047265528334, 214.12880475129919)
>>> 

1 个答案:

答案 0 :(得分:3)

假设hist2[0]是红色像素的直方图,则它是由红色分量索引的像素计数的直方图。这意味着sum(hist2[0])始终是图像中的像素数,而len(hist2[0])总是256.这将始终为您提供相同的答案,对于红色,绿色的所有三个和蓝色。

您需要将像素计数(直方图中的值)乘以像素值(列表中的索引),然后添加它们,以获得加权和。然后除以像素数得到加权平均值。也许是这样的:

red_hist = hist2[0]
weighted_sum = sum(i * red_hist[i] for i in range(len(red_hist)))
num_pixels = sum(red_hist)
weighted_average = weighted_sum / num_pixels