挑战图像处理100问(10)——中值滤波

在这里插入图片描述
读取图像,使用中值滤波器来对加了噪声的图片进行降噪处理。
Author: Tian YJ
原图如下:

在这里插入图片描述
中值滤波器是一种可以使图像平滑的滤波器。这种滤波器用滤波器范围内(在这里是 3 × 3 3\times3 )像素点的中值进行滤波。
在这里插入图片描述

代码实现
# -*- coding: utf-8 -*-
"""
Created on Thu Apr  9 08:54:47 2020

@author: Tian YJ
"""

import cv2 # 我只用它来做图像读写和绘图,没调用它的其它函数哦
import numpy as np # 进行数值计算
from numpy import random # numpy中的随机函数

# 定义高斯滤波函数
def median_filter(img, K_size=3):
	# 获取图像尺寸
	H, W, C = img.shape

	# 图像边缘补零
	pad = K_size // 2 # 使图像边缘能与滤波器中心对齐
	out = np.zeros((H+2*pad, W+2*pad, C), dtype=np.float)
	out[pad:pad+H, pad:pad+W] = img.copy().astype(np.float)

	tem = out.copy()

	# 进行滤波
	for y in range(H):
		for x in range(W):
			for c in range(C):
				out[pad+y, pad+x, c] = np.median(out[y:y+K_size, x:x+K_size, c])

	out = out[pad:pad+H, pad:pad+W].astype(np.uint8)

	return out

# 读取图片
path = 'C:/Users/86187/Desktop/image/'


file_in = path + 'cake_noise.jpg' 
file_out = path + 'median_filter.jpg' 
img = cv2.imread(file_in)

# 调用函数进行中值滤波
out = median_filter(img, K_size=3)

# 保存图片
cv2.imwrite(file_out, out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果展示
原图 加噪声 中值滤波
在这里插入图片描述 在这里插入图片描述 在这里插入图片描述
发布了43 篇原创文章 · 获赞 40 · 访问量 2110

猜你喜欢

转载自blog.csdn.net/qq_42662568/article/details/105402522