# 图像处理滤波器(一)——均值滤波器(Mean Filter)

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:

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客