使用NumPy对灰度图像进行直方图均衡 [英] Histogram equalization of grayscale images with NumPy

查看:575
本文介绍了使用NumPy对灰度图像进行直方图均衡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

(1800, 1, 96,96)


推荐答案

穆斯的评论指向此博客很好地完成了这项工作。

Moose's comment which points to this blog entry does the job quite nicely.

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

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.

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, normed=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]

这篇关于使用NumPy对灰度图像进行直方图均衡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆