AHE算法python实现
时间: 2023-07-26 18:10:17 浏览: 285
AHE(自适应直方图均衡化)算法是一种用于增强图像对比度的方法。以下是Python实现AHE算法的示例代码:
```python
import cv2
import numpy as np
# 自适应直方图均衡化函数
def adaptive_histogram_equalization(img, clip_limit=2.0, tile_size=8):
# 将图像转为灰度图
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_height, img_width = img_gray.shape
# 计算每个tile的大小
tile_rows = int(np.ceil(img_height / tile_size))
tile_cols = int(np.ceil(img_width / tile_size))
# 计算clip_limit
map_size = tile_rows * tile_cols
clip_limit = int(clip_limit * map_size / 256)
# 对每个tile进行直方图均衡化
map_array = np.zeros((tile_rows, tile_cols, 256), dtype=np.uint32)
for i in range(tile_rows):
for j in range(tile_cols):
x1, y1 = i * tile_size, j * tile_size
x2, y2 = min(x1 + tile_size, img_height), min(y1 + tile_size, img_width)
tile = img_gray[x1:x2, y1:y2]
hist, _ = np.histogram(tile.flatten(), bins=256, range=(0, 255))
cdf = np.cumsum(hist)
cdf = (cdf * 255) // cdf[-1]
map_array[i, j, :] = cdf
# 对整张图像进行映射
img_out = np.zeros_like(img_gray)
for i in range(tile_rows):
for j in range(tile_cols):
x1, y1 = i * tile_size, j * tile_size
x2, y2 = min(x1 + tile_size, img_height), min(y1 + tile_size, img_width)
tile = img_gray[x1:x2, y1:y2]
cdf = map_array[i, j, :]
cdf_min = np.min(cdf)
cdf[cdf < cdf_min + clip_limit] = cdf_min + clip_limit
cdf[cdf > 255 - clip_limit] = 255 - clip_limit
cdf = ((cdf - cdf_min) * 255) // (256 - 2 * clip_limit)
img_out[x1:x2, y1:y2] = cdf[tile]
return img_out
```
使用方法:
```python
img = cv2.imread('input_image.jpg')
img_out = adaptive_histogram_equalization(img, clip_limit=3.0, tile_size=16)
cv2.imshow('Input Image', img)
cv2.imshow('Output Image', img_out)
cv2.waitKey(0)
```
其中,`clip_limit`是限制像素值范围的参数,`tile_size`是每个tile的大小。
阅读全文