如何生成RGB图像的颜色直方图?

问题描述 投票:0回答:1

我在线搜索了一些来源,但它们并不是我想要的。

所以对于一组图像。我想生成颜色直方图,其形式为{color1:p1,color2:p2,..... color100:p100},其中colorxxx表示RGB图像的颜色。和p表示该颜色的概率。

有没有一种简单的方法在python中做这些事情?

谢谢

python image colors histogram
1个回答
1
投票

方法1:

{k:np.sum(a==k) for k in set(a.ravel().tolist())}

或者更可读

count = lambda A, key : np.sum(A==key)
unique_keys = set(A.ravel().tolist())
return {key : count(A,key) for key in unique_keys}

走过它:

{...}

dictionary comprehension生成映射

set(a.ravel().tolist())

a.ravel flattens the image;列表允许它被强制转换为set,它是唯一元素的容器。

np.sum(a==k)

计算元素在图像中的次数。这个is not the most efficient way to do this,但将直方图放入您请求的格式


总之,如果你的图像是3x3

a = np.array([[1,2,3],[1,3,3],[3,3,3]])

然后

set(a.ravel().tolist()) # yields set([1, 2, 3])

并且整个表达式产生

{1: 2, 2: 1, 3: 6}

方法2

from PIL.Image import fromarray
b = fromarray(a.astype(np.uint8)) # convert to a PIL image
hist =  {idx:count for idx, count in enumerate(b.histogram()) if count}

这非常相似(使用字典理解),但使用PIL histogram功能,enumerate获取索引。它可能有一些域限制。

“分档”

如果你想拥有颜色的“箱子”,正如你所指出的那样,剩下的工作只是定义你的箱子结构,这可以通过多种方式完成。例如,在前面的示例中,我们可以创建固定大小的整数二进制数

num_bins = 2
b = fromarray(a.astype(np.uint8)//num_bins) # convert to a PIL image, binned
hist =  {idx*num_bins:count for idx, count in enumerate(b.histogram()) if count}
© www.soinside.com 2019 - 2024. All rights reserved.