numpy图像中灰度值的直方图

histogram of gray scale values in numpy image

我将一张图像加载到一个 numpy 数组中,并想在直方图中绘制它的颜色值。

import numpy as np

from skimage import io
from skimage import color

img = io.imread('img.jpg')
img = color.rgb2gray(img)

unq = np.unique(img)
unq = np.sort(unq)

当我们检查 unq 的值时,我们会看到类似

的内容
array([  5.65490196e-04,   8.33333333e-04,   1.13098039e-03, ...,
         7.07550980e-01,   7.09225490e-01,   7.10073725e-01])

matplotlib 的值仍然太多,所以我的想法是遍历 unq 并删除仅偏离其前身 x 的每个值。

dels = []

for i in range(1, len(unq)):
    if abs(unq[i]-unq[i-1]) < 0.0003:
        dels.append(i)

unq = np.delete(unq, dels)

虽然这个方法有效,但效率很低,因为它没有使用 numpy 的优化实现。

有没有 numpy 功能可以帮我做这个?

刚刚注意到我的算法丢失了有关颜色出现频率的信息。让我尝试解决这个问题

如果只想计算直方图,可以使用np.histogram:

bin_counts, bin_edges = np.histogram(img, bins, ...)

此处,bins 可以是 bin 的数量,也可以是指定 bin 上下边缘的向量。

如果要绘制直方图,最简单的方法是使用 plt.hist:

bin_counts, bin_edges, patches = plt.hist(img.ravel(), bins, ...)

请注意,我在计算直方图之前使用了 img.ravel() 来展平图像数组。如果您将二维数组传递给 plt.hist(),它会将每一行视为一个单独的数据系列,这不是您想要的。