程序代码
# coding: utf-8
'''
东南大学《数字图像处理》课程 作业5 - 中值滤波
09017227 卓旭 written with Python 3
本程序内灰度图像作为二维数组,存储顺序为[行][列],像素点坐标表示为img[x][y],坐标系为
O--------> [y axis]
|
|
V [x axis]
'''
import imageio
import numpy as np
import cv2 # OpenCV仅用于显示图片
IMAGE_PATH='./Img_Denoise.bmp'
FILTER_SIZE=3
'''
读入灰度图像,转为二维numpy数组
'''
def readImage(imagePath):
return imageio.imread(imagePath)
'''
获取奇数个数中的中位数
'''
def getMedian(arr):
middle = (len(arr) + 1) // 2 - 1
return sorted(arr)[middle]
'''
中值滤波实现(nXn窗口),返回处理好的结果图
'''
def filter(image, filterSize):
height, width = image.shape
padding = (filterSize - 1) // 2
# 获取某像素的邻域及其自身
def getNeighborAndMe(x, y, padding):
I = image
res = []
for ii in range(-padding, padding + 1):
for jj in range(-padding, padding + 1):
res.append(I[x + ii, y + jj])
return res
result = image.copy()
for i in range(height):
for j in range(width):
# 边界保留
if i < padding or j < padding or i > height - padding - 1 or j > width - padding - 1:
continue
result[i, j] = getMedian(getNeighborAndMe(i, j, padding))
return result
if __name__ == '__main__':
print("开始运算...")
result = filter(readImage(IMAGE_PATH), FILTER_SIZE)
imageio.imsave('Denoise_Result.bmp', result)
cv2.imshow("Denoise", result)
cv2.waitKey(0)