python实现对彩色图像red.jpg进行自适应中值滤波,滤波器大小为7×7
时间: 2024-02-12 17:05:31 浏览: 128
好的,以下是Python实现对彩色图像进行自适应中值滤波的代码,滤波器大小为7x7:
```python
import cv2
# 读取图像
img = cv2.imread('red.jpg')
# 自适应中值滤波
def AdaptiveMedianFilter(img, maxWindowSize):
rows, cols, channels = img.shape
output = img.copy()
for i in range(rows):
for j in range(cols):
for c in range(channels):
windowSize = 3
while windowSize <= maxWindowSize:
# 计算当前窗口的左上角和右下角坐标
left = max(j - windowSize, 0)
top = max(i - windowSize, 0)
right = min(j + windowSize, cols - 1)
bottom = min(i + windowSize, rows - 1)
# 计算窗口内像素的中值
window = img[top:bottom+1, left:right+1, c]
median = cv2.medianBlur(window, 1)[windowSize-2, windowSize-2]
# 判断是否需要继续扩大窗口
if img[i, j, c] < median:
windowSize += 2
if windowSize > maxWindowSize:
output[i, j, c] = median
else:
output[i, j, c] = img[i, j, c]
break
else:
output[i, j, c] = median
return output
output = AdaptiveMedianFilter(img, maxWindowSize=7)
# 显示原图和处理后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Adaptive Median Filter', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在运行代码之前,请确保已经安装了OpenCV库。
阅读全文