pixel是通过标准jdk或android bitmap获取的图像32位像素数组
这个方法的滤波器尺寸是3*3,需要更大尺寸滤波器可以依此类推,ColorModel
可根据各平台变化调整
private int[] medianFiltering(int[] pixel, int w, int h) {
int[] newPixel = new int[w * h];
int[] tempR = new int[9];
int[] tempG = new int[9];
int[] tempB = new int[9];
ColorModel cm = ColorModel.getRGBdefault();
// median values of the matrix
int r;
int g;
int b;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if (x == 0 || x == w - 1 || y == 0 || y == h - 1) {
newPixel[y * w + x] = pixel[y * w + x];
continue;
}
tempR[0] = cm.getRed(pixel[x - 1 + (y - 1) * w]);
tempR[1] = cm.getRed(pixel[x + (y - 1) * w]);
tempR[2] = cm.getRed(pixel[x + 1 + (y - 1) * w]);
tempR[3] = cm.getRed(pixel[x - 1 + y * w]);
tempR[4] = cm.getRed(pixel[x + y * w]);
tempR[5] = cm.getRed(pixel[x + 1 + y * w]);
tempR[6] = cm.getRed(pixel[x - 1 + (y + 1) * w]);
tempR[7] = cm.getRed(pixel[x + (y + 1) * w]);
tempR[8] = cm.getRed(pixel[x + 1 + (y + 1) * w]);
r = getMedianValue(tempR);
tempG[0] = cm.getGreen(pixel[x - 1 + (y - 1) * w]);
tempG[1] = cm.getGreen(pixel[x + (y - 1) * w]);
tempG[2] = cm.getGreen(pixel[x + 1 + (y - 1) * w]);
tempG[3] = cm.getGreen(pixel[x - 1 + y * w]);
tempG[4] = cm.getGreen(pixel[x + y * w]);
tempG[5] = cm.getGreen(pixel[x + 1 + y * w]);
tempG[6] = cm.getGreen(pixel[x - 1 + (y + 1) * w]);
tempG[7] = cm.getGreen(pixel[x + (y + 1) * w]);
tempG[8] = cm.getGreen(pixel[x + 1 + (y + 1) * w]);
g = getMedianValue(tempG);
tempB[0] = cm.getBlue(pixel[x - 1 + (y - 1) * w]);
tempB[1] = cm.getBlue(pixel[x + (y - 1) * w]);
tempB[2] = cm.getBlue(pixel[x + 1 + (y - 1) * w]);
tempB[3] = cm.getBlue(pixel[x - 1 + y * w]);
tempB[4] = cm.getBlue(pixel[x + y * w]);
tempB[5] = cm.getBlue(pixel[x + 1 + y * w]);
tempB[6] = cm.getBlue(pixel[x - 1 + (y + 1) * w]);
tempB[7] = cm.getBlue(pixel[x + (y + 1) * w]);
tempB[8] = cm.getBlue(pixel[x + 1 + (y + 1) * w]);
// median value
b = getMedianValue(tempB);
newPixel[y * w + x] = 255 << 24 | r << 16 | g << 8 | b;
}
}
return newPixel;
}