首页 > 解决方案 > 没有极值的直方图均衡

问题描述

是否可以在没有极值 0 和 255 的情况下进行直方图均衡?

具体来说,我有一个图像,其中许多像素为零。超过一半的像素为零。因此,如果我在那里进行直方图均衡,我基本上将值 1 移动到值 240,这与我想要对直方图均衡所做的完全相反。那么有没有一种方法可以只计算值 1 和 254 之间的直方图均衡?

目前我的代码如下所示:

flat = image.flatten()

# get image histogram
image_histogram, bins = np.histogram(flat, bins=range(0, number_bins), density=True)

cdf = image_histogram.cumsum() # cumulative distribution function
cdf = 255 * cdf /cdf.max() # normalize
cdf = cdf.astype('uint8')

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

image_equalized =  image_equalized.reshape(image.shape), cdf

谢谢

标签: pythonhistogramcdf

解决方案


解决这个问题的一种方法是在我们制作直方图之前过滤掉不需要的值,然后制作一个从非标准化像素到标准化像素的“转换表” 。

import numpy as np

# generate random image
image = np.random.randint(0, 256, (32, 32))

# flatten image
flat = image.flatten()

# get image histogram
image_histogram, bins = np.histogram(flat[np.where((flat != 0) & (flat != 255))[0]],
                                     bins=range(0, 10),
                                     density=True)

cdf = image_histogram.cumsum() # cumulative distribution function
cdf = 255 * cdf /cdf.max() # normalize
cdf = cdf.astype('uint8')

# use linear interpolation of cdf to find new pixel values
# we make a list conversion_table, where the index is the original pixel value,
# and the value is the histogram normalized pixel value
conversion_table = np.interp([i for i in range(0, 256)], bins[:-1], cdf)
# replace unwanted values by original
conversion_table[0] = 0
conversion_table[-1] = 255
image_equalized = np.array([conversion_table[pixel] for pixel in flat])

image_equalized =  image_equalized.reshape(image.shape), cdf

免责声明:我对图像处理完全没有任何经验,所以我不知道有效性:)


推荐阅读