gpt4 book ai didi

python - 如何循环直方图来获取图片的颜色?

转载 作者:行者123 更新时间:2023-11-30 23:49:41 24 4
gpt4 key购买 nike

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

最佳答案

假设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

关于python - 如何循环直方图来获取图片的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com