手动实现高斯滤波(python)
程序员文章站
2024-01-14 13:18:52
手动实现高斯滤波# -*- coding: utf-8 -*-"""Created on Sat Jul 11 14:53:28 2020@author: 陨星落云"""import imageioimport numpy as npdef GaussianFilter(img): h,w,c = img.shape # 高斯滤波 K_size = 3 sigma = 1 # 零填充 pad = K_size//2...
手动实现高斯滤波
# -*- 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))
结果:
本文地址:https://blog.csdn.net/qq_28368377/article/details/107288647