使用NumPy对灰度图像进行直方图均衡

pbu*_*pbu 5 python numpy image-processing histogram

如何对存储在NumPy阵列中的多个灰度图像进行直方图均衡?

我有这种4D格式的96x96像素NumPy数据:

(1800, 1, 96,96)
Run Code Online (Sandbox Code Playgroud)

Tri*_*ion 13

Moose 对这篇博客文章评论非常好.

为了完整性,我在这里使用更好的变量名称和1000个96x96图像上的循环执行给出了一个例子,这些图像在问题中是4D阵列.它很快(在我的电脑上1-2秒)并且只需要NumPy.

import numpy as np

def image_histogram_equalization(image, number_bins=256):
    # from http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html

    # get image histogram
    image_histogram, bins = np.histogram(image.flatten(), number_bins, density=True)
    cdf = image_histogram.cumsum() # cumulative distribution function
    cdf = 255 * cdf / cdf[-1] # normalize

    # use linear interpolation of cdf to find new pixel values
    image_equalized = np.interp(image.flatten(), bins[:-1], cdf)

    return image_equalized.reshape(image.shape), cdf

if __name__ == '__main__':

    # generate some test data with shape 1000, 1, 96, 96
    data = np.random.rand(1000, 1, 96, 96)

    # loop over them
    data_equalized = np.zeros(data.shape)
    for i in range(data.shape[0]):
        image = data[i, 0, :, :]
        data_equalized[i, 0, :, :] = image_histogram_equalization(image)[0]
Run Code Online (Sandbox Code Playgroud)