K近邻平滑滤波

 

 

原理:以待处理的像素作为中心,取一个nXn的模板,在模板中选择k个与待处理像素的值最接近的像素,将这k个像素的均值替换原来的像素值。

 

% K近邻平滑滤波

% input - 输入图像矩阵;n - 模板大小(357...);k - 近邻数

% output - 滤波处理后的图像矩阵

function output = emuchKNNMeanFilter(input, n, k)

    [row, col] = size(input);

    edgeWidth = floor(n / 2);

    output = zeros(row - edgeWidth * 2, col - edgeWidth * 2);

    for i = 1 + edgeWidth : row - edgeWidth

        for j = 1 + edgeWidth : col - edgeWidth

            mask = input(i - edgeWidth : i + edgeWidth,...

                j - edgeWidth : j + edgeWidth);

            center = input(i, j);

            vertex = Matrix2Vertex(mask);

            neighbour = GetNeighbour(vertex, center, k);

            output(i - 1, j - 1) = mean(neighbour);

        end

    end

end

 

% 根据输入的向量与中心值取近邻值

% vertex - 输入向量;center - 中心值;k - 近邻数

% neighbour - 近邻值

function neighbour = GetNeighbour(vertex, center, k)

    distance = abs(vertex - center);

    [sortDistance, sortIndex] = sort(distance,1);

    neighbour = vertex(sortIndex(2 : k + 1));

end

 

% 将矩阵转换为向量

function vertex = Matrix2Vertex(matrix)

    [row, col] = size(matrix);

    vertex = zeros(row * col, 1);

    for i = 1 : row * col

        vertex(i) = matrix(i);

    end

end

 

 

 

 

 

 

调用方法:

将以上代码存为文件emuchKNNMeanFilter.m,在matlab command window中调用。
例如,有矩阵
a = 
164        24        196        119        209        51
200        139        53        23        250        244
125        218        11        129        247        86
103        67        39        20        147        38
224        198        183        42        60        84
181        163        33        191        74        29
211        185        56        85        172        197
3        228        116        78        146        202
调用程序进行处理:b = emuchKNNMeanFilter(a, 3, 5)
得到处理后的矩阵
b = 
180.6        61.2        101.6        189.6
126.8        40.4        56.4        171.2
92.2        53.8        56.2        121.2
170.8        132.2        45.2        53.4
191.6        105.8        114.8        60
179.8        95        71.4        164.2

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值