空间滤波基础

# 作者:喵酱
# 开发时间:2022/4/17 10:11
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from scipy import ndimage
plt.rcParams['font.sans-serif'] = ['FangSong']  # 设置字体以便正确显示中文


def add_salt_noise(img, P):
    """添加椒盐噪声"""
    img_ = img.copy()
    h, w = img.shape
    mask = np.random.choice((0, 1, 2), size=(h, w), p=P)
    img_[mask == 1] = 255
    img_[mask == 2] = 0
    return img_


def mean_filtering(img):
    """均值滤波"""
    kernel = 1/9 * np.asarray([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
    img_out = ndimage.convolve(img, kernel)
    return img_out


def gaussian_filtering(img):
    """高斯滤波"""
    kernel = 1/16 * np.asarray([[1, 2, 1], [2, 4, 2], [1, 2, 1]])
    img_out = ndimage.convolve(img, kernel)
    return img_out


def abort_filtering(img):
    """中值滤波"""
    h, w = img.shape
    img_ = img.copy()
    for i in np.arange(1, h):
        for j in np.arange(1, w):
            mat = img[i-1:i+1, j-1:j+1]
            img_[i][j] = np.median(mat)
    return img_


img = np.asarray(Image.open('la.tif'))              # 读入原始图像
img_noise = add_salt_noise(img, [0.9, 0.05, 0.05])  # 添加椒盐噪声
img_noise_mean = mean_filtering(img_noise)          # 均值滤波
img_noise_gaussian = gaussian_filtering(img_noise)  # 高斯滤波
img_noise_abort = abort_filtering(img_noise)        # 中值滤波

plt.figure(1)
plt.subplot(121)
plt.imshow(img, cmap='gray')
plt.title('原始图像')
plt.subplot(122)
plt.imshow(img_noise, cmap='gray')
plt.title('添加椒盐噪声图像')
plt.figure(2)
plt.subplot(131)
plt.imshow(img_noise_mean, cmap='gray')
plt.title('均值滤波图像')
plt.subplot(132)
plt.imshow(img_noise_gaussian, cmap='gray')
plt.title('高斯滤波图像')
plt.subplot(133)
plt.imshow(img_noise_abort, cmap='gray')
plt.title('中值滤波图像')
plt.show()


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值