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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28518684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:22:10  来源:igfitidea点击:

Histogram equalization of grayscale images with NumPy

pythonimage-processingnumpyhistogram

提问by pbu

How to do histogram equalization for multiple grayscaled images stored in a NumPy array easily?

如何轻松地对存储在 NumPy 数组中的多个灰度图像进行直方图均衡?

I have the 96x96 pixel NumPy data in this 4D format:

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

(1800, 1, 96,96)

采纳答案by Trilarion

Moose's commentwhich points to this blog entrydoes the job quite nicely.

指向此博客条目的Moose 的评论非常好地完成了这项工作。

For completeness I give an axample here using nicer variable names and a looped execution on 1000 96x96 images which are in a 4D array as in the question. It is fast (1-2 seconds on my computer) and only needs NumPy.

为了完整起见,我在这里给出了一个例子,使用更好的变量名称和对 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]

回答by Dodo

Very fast and easy way is to use the cumulative distribution function provided by the skimage module. Basically what you do mathematically to proof it.

非常快速和简单的方法是使用 skimage 模块提供的累积分布函数。基本上你用数学方法来证明它。

from skimage import exposure
import numpy as np
def histogram_equalize(img):
    img = rgb2gray(img)
    img_cdf, bin_centers = exposure.cumulative_distribution(img)
    return np.interp(img, bin_centers, img_cdf)

回答by Diego Ferri

As of today janeriksolem's url is broken.

截至今天,janeriksolem的网址已损坏。

I found however this gistthat links the same page and claims to perform histogram equalization without computing the histogram.

然而,我发现这个链接同一页面的要点并声称在不计算直方图的情况下执行直方图均衡化。

The code is:

代码是:

img_eq = np.sort(img.ravel()).searchsorted(img)