用Numpy实现的CLAHE函数,输入是彩图,不要用cv2.createCLAHE!!!
时间: 2024-05-04 14:20:58 浏览: 84
CLAHE(Contrast Limited Adaptive Histogram Equalization)是一种非线性映射方式,用于增强图像的对比度。下面是用Numpy实现的CLAHE函数,可以输入彩图。
```python
import numpy as np
def clahe(img, clip_limit=2.0, grid_size=(8, 8)):
"""
Contrast Limited Adaptive Histogram Equalization (CLAHE)
:param img: input image, should be a numpy array with shape (H, W, C)
:param clip_limit: threshold for contrast limiting
:param grid_size: size of grid for histogram equalization
:return: CLAHE-enhanced image
"""
# convert image to LAB color space
lab_img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
clahe_img = np.zeros_like(lab_img)
# apply CLAHE to each channel of LAB image separately
for i in range(3):
clahe_img[..., i] = clahe_channel(lab_img[..., i], clip_limit, grid_size)
# convert back to RGB color space
clahe_img = cv2.cvtColor(clahe_img, cv2.COLOR_LAB2RGB)
return clahe_img
def clahe_channel(channel, clip_limit=2.0, grid_size=(8, 8)):
"""
Apply CLAHE to a single channel
:param channel: input channel, should be a numpy array with shape (H, W)
:param clip_limit: threshold for contrast limiting
:param grid_size: size of grid for histogram equalization
:return: CLAHE-enhanced channel
"""
h, w = channel.shape
# compute histogram of image
hist, bins = np.histogram(channel.flatten(), 256, [0, 256])
# compute cumulative distribution function (CDF) of histogram
cdf = hist.cumsum()
cdf = (cdf / cdf[-1]) * 255.0
# compute equalized image using CDF
equalized = np.interp(channel.flatten(), bins[:-1], cdf)
equalized = equalized.reshape((h, w))
# compute contrast limited equalization
grid_h, grid_w = grid_size
gh = int(np.ceil(h / grid_h))
gw = int(np.ceil(w / grid_w))
for i in range(grid_h):
for j in range(grid_w):
# extract grid from equalized image
grid = equalized[i*gh:(i+1)*gh, j*gw:(j+1)*gw]
# compute histogram of grid
hist, bins = np.histogram(grid.flatten(), 256, [0, 256])
# compute cumulative distribution function (CDF) of histogram
cdf = hist.cumsum()
cdf = (cdf / cdf[-1]) * 255.0
# clip CDF to contrast limit
cdf = np.clip(cdf, 0, clip_limit * gw * gh / 256.0)
# compute equalized grid using clipped CDF
equalized_grid = np.interp(grid.flatten(), bins[:-1], cdf)
equalized_grid = equalized_grid.reshape(grid.shape)
# insert equalized grid into output image
clahe_img[i*gh:(i+1)*gh, j*gw:(j+1)*gw] = equalized_grid
return clahe_img
```
这个函数首先将输入的彩图转换为LAB色彩空间,然后分别对L、A、B三个通道应用CLAHE算法,最后再将LAB图像转换回RGB色彩空间。CLAHE算法的核心是对图像分成若干个网格,然后在每个网格中执行直方图均衡化。为了避免增强噪声,CLAHE算法还引入了一个对比度限制的机制,具体来说就是对每个网格的直方图进行裁剪,使得直方图的范围不超过一个阈值。这里的阈值是通过clip_limit参数控制的。
阅读全文