数字图像处理——加权均值滤波器

均值滤波器中,模板内像素的权重都为一,其只是简单的像素加法平均

而,加权均值滤波器,对模板中的像素点赋予不同的权重,求的是像素的加权平均,典型的模板,例如高斯模糊,其模板权重呈现钟型的高斯分布:

                                                                                          \begin{bmatrix} 1 & 2 & 1\\ 2& 4 & 2\\ 1&2 &1 \end{bmatrix}

下面使用上式表示的模板,实现:

图像数据 :

导入,要使用的库:

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

 读取图像数据并可视化:

img = Image.open('Fig0333(a)(test_pattern_blurring_orig).tif')
plt.axis('off')
plt.imshow(img, cmap = 'gray')
plt.show()

滤波过程:

定义滤波模板:

kernel = [[1,2,1], [2,4,2], [1,2,1]]

 滤波函数:

def rejector2(img, m, n, kernel):
    num_sum = [sum(i) for i in kernel]
    num_sum = sum(num_sum)
    img_data = np.array(img)
    img_new = [[] for _ in range(np.shape(img_data)[0])]
    a = m // 2
    b = n // 2
    for i in range(np.shape(img_data)[0]):
        for j in range(np.shape(img_data)[1]):
            num = 0
            x = 0
            for k in range(i-a, i+a+1, 1):
                y = 0
                for l in range(j-b, j+b+1, 1):
                    c = k>=0 and k<np.shape(img_data)[0]
                    d = l>=0 and l<np.shape(img_data)[1]
                    #依然使用0填充
                    if c and d:
                        #计算模板中像素的加权之和
                        num += img_data[k][l] * kernel[x][y]
                    y += 1
                x += 1
            #求平均值
            num = num / num_sum
            img_new[i].append(int(num))
    return img_new

 测试结果,可视化:

img_new = rejector2(img, len(kernel), len(kernel[0]), kernel)

plt.figure(figsize=(25,25))
plt.subplot(131)
plt.axis('off')
plt.imshow(img_new, cmap = 'gray')

plt.subplot(132)
plt.axis('off')
plt.imshow(new_img[0], cmap = 'gray')

plt.subplot(133)
plt.axis('off')
plt.imshow(img, cmap = 'gray')
plt.show()

 左侧为加权均值滤波,中间为平滑线性滤波,右侧为原图像

  • 3
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫猫虫(——)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值