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

时间:2018-07-13 21:00:59

标签: python image colors histogram

我在线上搜索了一些资源,但它们并不是我要找的。

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

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

谢谢

1 个答案:

答案 0 :(得分:1)

方法1

http://localhost/wp/wp-json/swp_api/search?s=139&engine=scity&post_type=city

或更可读

{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()) flattens the image;列表允许将其强制转换为set,这是唯一元素的容器。

a.ravel

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


如果您的图片是3x3,请放在一起

np.sum(a==k)

然后

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

整个表达式产生

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

方法2

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

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

“装箱”

如果您希望像所指出的那样具有颜色的“容器”,那么剩下的工作就是定义容器的结构,可以通过多种方法来完成。例如,在前面的示例中,我们可以通过

创建固定大小的整数箱
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}