原理:以待处理的像素作为中心,取一个nXn的模板,在模板中选择k个与待处理像素的值最接近的像素,将这k个像素的均值替换原来的像素值。
% K近邻平滑滤波
% input - 输入图像矩阵;n - 模板大小(3,5,7...);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