挑战图像处理100问(12)——运动模糊滤波

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

在这里插入图片描述
Motion Filter取对角线方向的像素的平均值,像下式这样定义:
[130001300013] left[ egin{matrix} frac{1}{3}&0&0\ 0&frac{1}{3}&0\ 0 & 0& frac{1}{3} end{matrix} ight]

代码实现
# -*- coding: utf-8 -*-
"""
Created on Thu Apr  9 13:53:38 2020

@author: Tian YJ
"""

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

# 定义Motion Filter
def motion_filter(img, K_size=3):
	# 获取图像尺寸
	H, W, C = img.shape

	# 设置滤波器系数
	K = np.diag([1]*K_size).astype(np.float)
	K /= K_size

	# 图像边缘补零
	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.sum(K * tem[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 + 'motion_filter.jpg' 
img = cv2.imread(file_in)

# 调用函数进行Motion滤波
out = motion_filter(img, K_size=3)

# 保存图片
cv2.imwrite(file_out, out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果展示
原图 加噪声 均值滤波
在这里插入图片描述 在这里插入图片描述 在这里插入图片描述
原文地址:https://www.cnblogs.com/Jack-Tim-TYJ/p/12831916.html