描述:均值滤波器是图像处理中一种常见的滤波器,它主要应用于平滑噪声。它的原理主要是利用某像素点周边像素的平均值来打到平滑噪声的效果。
常用的均值核如下图所示:

图像滤波器操作实际上就是模板操作,对于模板操作我们应该注意边界问题:
什么是边界问题?
对于边界问题就是当图像处理边界像素的时候,卷积核与图像使用区域不能匹配,计算出现问题。
处理方法:
1、忽略边界像素,即丢掉不能匹配的像素
2、保留边界像素,即复制源图像的不能匹配的边界像素到输出图像
Code:
/**
* Calculates the mean of a 3x3 pixel neighbourhood (including centre pixel).
*
* @param input the input image 2D array
* @param kernel the kernel 2D array
* @param w the image width
* @param h the image height
* @param x the x coordinate of the centre pixel of the array
* @param y the y coordinate of the centre pixel of the array
* @return the mean of the 9 pixels
*/
public static int meanNeighbour(int [][] input, int [][] kernel,
int w, int h, int x, int y) {
int sum = 0;
int number = 0;
for(int j=0;j<3;++j){
for(int i=0;i<3;++i){
if((kernel[i][j]==1) &&
((x-1+i)>=0) && ((y-1+j)>=0) && ((x-1+i)<w) && ((y-1+j)<h) ){
sum = sum + input[x-1+i][y-1+j];
++number;
}
}
}
if(number==0) return 0;
return (sum/number);
} /**
* Takes an image in 2D array form and smoothes it according to the kernel.
* @param input the input image
* @kernel the kernel 1D array
* @param width of the input image
* @param height of the output image
* @param iterations to be performed
* @return the new smoothed image 2D array
*/
public static int [][] smooth(int [][] input, int [][] kernel,
int width, int height, int iterations){
int [][] temporary = new int [width][height];
int [][] outputArrays = new int [width][height];
temporary = (int [][]) input.clone();
for (int its=0;its<iterations;++its){
for(int j=0;j<height;++j){
for(int i=0;i<width;++i){
outputArrays[i][j] = meanNeighbour(temporary,kernel,
width,height,i,j);
}
}
for(int j=0;j<height;++j){
for(int i=0;i<width;++i){
temporary[i][j]=outputArrays[i][j];
}
}
}
return outputArrays;
}Input Image:

Output Image:

总结:均值滤波器就是为了平滑周边的效果,不会因为图像上突出的点而感到难受,达到一种“Softened”的效果。
版权声明:本文为lj695242104原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。