MAD算法如何自适应调整融合了KMeans的CLAHE的阈值代码python
时间: 2023-12-21 15:05:55 浏览: 252
MAD (Median Absolute Deviation) 是一种鲁棒的统计方法,可以用来自适应调整融合了 KMeans 的 CLAHE 的阈值。
具体步骤如下:
1. 对于每个图像块,使用 KMeans 算法将其分为若干个子块,每个子块的灰度值相近。
2. 对于每个子块,计算其中像素值的 MAD 值,作为该子块的阈值。
3. 对于整张图像,使用 CLAHE 算法进行直方图均衡化,但是使用每个子块的阈值作为对应子块的阈值。
4. 如果整张图像的亮度过于明亮或暗淡,可以根据整张图像的 MAD 值调整阈值。如果 MAD 值较小,则将所有子块的阈值增加一个固定值;如果 MAD 值较大,则将所有子块的阈值减少一个固定值。
代码实现如下:
```python
import numpy as np
from skimage.filters import median
from skimage.filters.rank import median as median_rank
from skimage.exposure import equalize_adapthist
from sklearn.cluster import KMeans
def mad_clahe(image, block_size=32, kmeans_k=4, delta=40):
# Step 1: Use KMeans to cluster each block of image into k clusters
kmeans = KMeans(n_clusters=kmeans_k, random_state=0)
block_shape = (block_size, block_size)
blocks = view_as_blocks(image, block_shape)
n_blocks = blocks.shape[0] * blocks.shape[1]
block_centers = np.zeros((n_blocks, kmeans_k))
for i in range(blocks.shape[0]):
for j in range(blocks.shape[1]):
block = blocks[i, j]
block_flat = block.reshape((-1, 1))
kmeans.fit(block_flat)
block_centers[i * blocks.shape[1] + j] = kmeans.cluster_centers_.ravel()
# Step 2: Calculate threshold for each block as median absolute deviation
block_mads = np.median(np.abs(block_centers - np.median(block_centers, axis=1, keepdims=True)), axis=1)
# Step 3: Apply CLAHE on image with adaptive thresholds
adaptive_thresholds = block_mads.reshape(blocks.shape[0], blocks.shape[1])
image_clahe = np.zeros_like(image)
for i in range(blocks.shape[0]):
for j in range(blocks.shape[1]):
block = blocks[i, j]
block_clahe = equalize_adapthist(block, clip_limit=0.03, kernel_size=None, nbins=256, adaptive_clip_limit=True, clip_limit_range=None, mask=None, nbins_above_high=None, nbins_below_low=None, channel_axis=None)
image_clahe[i * block_size:(i + 1) * block_size, j * block_size:(j + 1) * block_size] = block_clahe
# Step 4: Adjust thresholds according to global MAD value
global_mad = np.median(np.abs(image_clahe - np.median(image_clahe)))
if global_mad < delta:
adaptive_thresholds += delta
else:
adaptive_thresholds -= delta
# Final step: Apply median filter on enhanced image
image_enhanced = median_rank(image_clahe, selem=disk(1))
return image_enhanced
```
其中,`image` 是待增强的图像,`block_size` 是每个块的大小,`kmeans_k` 是 KMeans 算法中的聚类数目,`delta` 是调整阈值时的增量。
这段代码使用了 `sklearn.cluster.KMeans` 来进行聚类,使用了 `skimage.filters.rank.median` 来进行局部中值滤波,使用了 `skimage.exposure.equalize_adapthist` 来进行自适应直方图均衡化。
阅读全文