ABMHE算法 python代码
时间: 2023-07-23 07:08:09 浏览: 180
鲸鱼优化算法python代码
5星 · 资源好评率100%
ABMHE(Adaptive Block-based Multi-Histogram Equalization)算法是一种图像增强算法,可以提高图像的对比度和细节。以下是一个简单的Python实现:
```python
import cv2
import numpy as np
def abmhe(img, block_size=16, clip_limit=0.03):
# 计算图像尺寸和块数
h, w = img.shape[:2]
blocks_h = h // block_size
blocks_w = w // block_size
# 计算直方图均衡化后的像素值
pixel_range = 256
hist_eq_pixels = np.zeros(pixel_range)
for i in range(pixel_range):
hist_eq_pixels[i] = i * (pixel_range - 1) / (block_size ** 2)
# 计算每个块的像素值分布
block_pixels = np.zeros((blocks_h, blocks_w, block_size, block_size))
for i in range(blocks_h):
for j in range(blocks_w):
block_pixels[i, j] = img[i*block_size:(i+1)*block_size, j*block_size:(j+1)*block_size]
block_hists = np.zeros((blocks_h, blocks_w, pixel_range))
for i in range(blocks_h):
for j in range(blocks_w):
block_hist, _ = np.histogram(block_pixels[i, j], bins=pixel_range, range=(0, pixel_range-1))
block_hists[i, j] = block_hist
# 计算每个块的限制值
clip_value = clip_limit * block_size ** 2
limit_value = np.zeros((blocks_h, blocks_w))
block_sums = np.sum(block_hists, axis=2)
for i in range(blocks_h):
for j in range(blocks_w):
limit_value[i, j] = np.clip(clip_value / (block_sums[i, j] + 1e-6), 0, 1)
# 计算每个块的均值
block_means = np.zeros((blocks_h, blocks_w))
for i in range(blocks_h):
for j in range(blocks_w):
block_means[i, j] = np.mean(block_pixels[i, j])
# 应用增强算法
enhanced_img = np.zeros_like(img)
for i in range(blocks_h):
for j in range(blocks_w):
block_hist = block_hists[i, j]
limit = limit_value[i, j]
mean = block_means[i, j]
cdf = np.cumsum(block_hist) / (block_size ** 2)
cdf = np.clip(cdf, 0, 1)
cdf_eq = np.interp(hist_eq_pixels, np.arange(pixel_range), cdf)
cdf_diff = cdf_eq - cdf
cdf_diff[0] = np.max(cdf_diff[1:])
index = np.arange(pixel_range)
for k in range(pixel_range):
index[k] = np.argmin(np.abs(cdf_diff - cdf_diff[k]))
block_pixels[i, j] = index[block_pixels[i, j]]
block_pixels[i, j] = np.clip(block_pixels[i, j], 0, 255)
block_pixels[i, j] = (1 - limit) * block_pixels[i, j] + limit * mean
enhanced_img[i*block_size:(i+1)*block_size, j*block_size:(j+1)*block_size] = block_pixels[i, j]
return enhanced_img
```
这个实现将图像分成16x16大小的块,然后分别处理每个块以提高图像对比度和细节。clip_limit参数控制限制值,可以调整算法的效果。
阅读全文