有没有更好的方法来实现直方图?

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

我有一个二维uint16 numpy数组,我想计算该数组的直方图。我使用的功能是:

def calc_hist(source):
    hist = np.zeros(2**16, dtype='uint16')
    for i in range(source.shape[0]):
       for j in range(source.shape[1]):
           hist[source[i, j] = hist[source[i, j] + 1 

此功能执行时间过多。据我了解,在numpy模块中有一个直方图函数,但我不知道如何使用它。我尝试过:

hist,_ = np.histogram(source.flatten(), bins=range(2**16))

但是我得到的结果与我自己的函数不同。如何调用numpy.histogram获得相同的结果?还是有其他选择?

python performance numpy histogram
1个回答
0
投票

[正如Corley Brigman指出的那样,通过bins=range(x)决定了容器边缘[1]。因此,您将最终得到x-1个具有相应边[0,1),[1,2),...,[x-1,x]的容器。

根据您的情况,您将有2 ^ 16-1个垃圾箱。要解决此问题,只需使用range(2**16+1)

[1] https://numpy.org/doc/stable/reference/generated/numpy.histogram.html?highlight=histogram#numpy.histogram

© www.soinside.com 2019 - 2024. All rights reserved.