手动实现高斯滤波(python)
2020-07-12 本文已影响0人
陨星落云
手动实现高斯滤波
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 14:53:28 2020
@author: 陨星落云
"""
import imageio
import numpy as np
def GaussianFilter(img):
h,w,c = img.shape
# 高斯滤波
K_size = 3
sigma = 1
# 零填充
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)
# 定义滤波核
K = np.zeros((K_size,K_size),dtype=np.float)
for x in range(-pad,-pad+K_size):
for y in range(-pad,-pad+K_size):
K[y+pad,x+pad] = np.exp(-(x**2+y**2)/(2*(sigma**2)))
K /= (sigma*np.sqrt(2*np.pi))
K /= K.sum()
# 卷积的过程
tmp = out.copy()
for y in range(h):
for x in range(w):
for ci in range(c):
out[pad+y,pad+x,ci] = np.sum(K*tmp[y:y+K_size,x:x+K_size,ci])
out = out[pad:pad+h,pad:pad+w].astype(np.uint8)
return out
if __name__ == "__main__":
# 读取图像
img = imageio.imread("lena.jpg")
# 高斯滤波
imageio.imsave("GaussianFilter.jpg",GaussianFilter(img))
结果:
image