使用python代码完成图像的直方图均衡,实现基本均衡算法,分块均衡算法和局部均衡
时间: 2023-09-17 20:09:46 浏览: 97
好的,下面是使用Python代码实现图像的直方图均衡,分别包括基本均衡算法、分块均衡算法和局部均衡:
首先,我们需要导入必要的库和读取一张待处理的图片:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('lena.jpg', 0)
```
接下来,我们先实现基本均衡算法。对于一幅灰度图像,其直方图为图像中每个灰度级出现的频率。我们可以通过计算每个灰度级出现的概率来得到直方图。然后,将直方图归一化后,再通过累计概率得到新的灰度级。最后,将新的灰度级映射回原图像中即可。
```python
def basic_histogram_equalization(img):
hist, bins = np.histogram(img.flatten(), 256, [0, 256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max() / cdf.max()
img_equalized = np.interp(img.flatten(), bins[:-1], cdf_normalized)
img_equalized = img_equalized.reshape(img.shape)
return img_equalized.astype('uint8')
img_basic_eq = basic_histogram_equalization(img)
```
下面,我们来实现分块均衡算法。这种方法将图像划分成多个子块,然后对每个子块进行直方图均衡。这样可以减少计算量,减小直方图不均衡的影响。
```python
def block_histogram_equalization(img, block_size=16):
img_equalized = np.zeros_like(img)
h, w = img.shape
for i in range(0, h, block_size):
for j in range(0, w, block_size):
block = img[i:i+block_size, j:j+block_size]
block_equalized = basic_histogram_equalization(block)
img_equalized[i:i+block_size, j:j+block_size] = block_equalized
return img_equalized.astype('uint8')
img_block_eq = block_histogram_equalization(img)
```
最后,我们来实现局部均衡算法。这种方法将图像分成若干个局部区域,然后在每个局部区域内进行直方图均衡。这样可以保留图像的细节信息,同时避免过度增强图像的高频内容。
```python
def local_histogram_equalization(img, kernel_size=(3, 3)):
img_equalized = np.zeros_like(img)
h, w = img.shape
k_h, k_w = kernel_size
for i in range(h):
for j in range(w):
i_min = max(i-k_h//2, 0)
i_max = min(i+k_h//2, h-1)
j_min = max(j-k_w//2, 0)
j_max = min(j+k_w//2, w-1)
block = img[i_min:i_max+1, j_min:j_max+1]
block_equalized = basic_histogram_equalization(block)
img_equalized[i, j] = block_equalized[k_h//2, k_w//2]
return img_equalized.astype('uint8')
img_local_eq = local_histogram_equalization(img)
```
最后,我们可以将原图像和三种直方图均衡的结果进行可视化比较:
```python
plt.figure(figsize=(10, 10))
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(2, 2, 2)
plt.imshow(img_basic_eq, cmap='gray')
plt.title('Basic Histogram Equalization')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.imshow(img_block_eq, cmap='gray')
plt.title('Block Histogram Equalization')
plt.axis('off')
plt.subplot(2, 2, 4)
plt.imshow(img_local_eq, cmap='gray')
plt.title('Local Histogram Equalization')
plt.axis('off')
plt.show()
```
运行代码后,就可以看到原图像和三种直方图均衡的结果了。
阅读全文