填充直方图数组的有效方法

efficient way to fill histogram array

有没有人有想法使以下 python 代码更快并且可能没有 for 循环或向量化?我敢打赌 numpy 中有一个技巧或很酷的功能可以做到这一点,但还没有找到方法。

“img”是 uint8 的 numpy 图像:

 histogram = np.empty((height, width, 256), dtype=np.uint16)
 max_bin = np.empty((height, width), dtype=np.uint16)
 while ...:
    img = ...
    for y in range(height):
        for x in range(width):
            histogram[y, x, img[y, x]] += 1

    for y in range(height):
        for x in range(width):
            max_bin[y,x] = np.argmax(histogram[y, x])

您可以使用函数 np.bincount 来做到这一点,但它需要同时加载所有图像(至少按块加载)。在您的情况下,最好使用 Numba 的 @njit.

如果您有很多小图像,您可以使用 thread-local 直方图并行执行此操作,然后对这些局部直方图求和以获得您想要的结果。