自己用python代码编写函数实现自适应直方图均衡化,且生成图比原图小一圈
时间: 2024-03-27 22:39:11 浏览: 82
好的,我已经明白了您的需求,下面是使用 Python 实现自适应直方图均衡化并生成比原图小一圈的函数:
```python
import cv2
import numpy as np
def adaptive_histogram_equalization(img):
# 将图像转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算图像的均值和方差
mean, std = cv2.meanStdDev(gray)
mean = mean[0][0]
std = std[0][0]
# 设置参数
k = 0.4
epsilon = 0.0001
max_intensity = 255
# 计算每个像素的局部均值和局部标准差
width, height = gray.shape
local_mean = np.zeros((width, height))
local_std = np.zeros((width, height))
for i in range(width):
for j in range(height):
x0 = max(0, i - 1)
y0 = max(0, j - 1)
x1 = min(width - 1, i + 1)
y1 = min(height - 1, j + 1)
local_patch = gray[x0:x1, y0:y1]
local_mean[i][j] = np.mean(local_patch)
local_std[i][j] = np.std(local_patch)
# 计算增益和偏移量
gain = k * std / (local_std + epsilon)
offset = mean - gain * local_mean
# 进行自适应直方图均衡化
result = np.zeros_like(gray)
for i in range(width):
for j in range(height):
value = int(gain[i][j] * gray[i][j] + offset[i][j])
value = min(max_intensity, max(0, value))
result[i][j] = value
# 将结果进行缩小
result = cv2.resize(result, (result.shape[1]-2, result.shape[0]-2))
return result
```
这个函数的输入为一张彩色图片,输出为经过自适应直方图均衡化并缩小一圈后的灰度图像。您可以将图片读入后传入这个函数,例如:
```python
img = cv2.imread('example.jpg')
result = adaptive_histogram_equalization(img)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`example.jpg` 为您要处理的图片文件名。
阅读全文