均值滤波及中值滤波(Java)

Posted on 2022-11-29 16:25  Capterlliar  阅读(143)  评论(0编辑  收藏  举报

既然要滤波,先添加点噪点:

public static BMPImage AddNoise(BMPImage img){
        BMPImage img2=new BMPImage(img.width,img.height);
        for(int i=1;i<img.height-1;i++){
            for(int j=1;j<img.width-1;j++){
                img2.red[i][j]=img.red[i][j];
                img2.green[i][j]=img.green[i][j];
                img2.blue[i][j]=img.blue[i][j];
            }
        }
        for(int i=1;i<img.height-1;i++){
            for(int j=1;j<img.width-1;j++){
                double flag= Math.random();
                if(flag>0.98) {
                    img2.red[i][j] = 0;
                    img2.green[i][j] = 0;
                    img2.blue[i][j] = 0;
                }
            }
        }
        return img2;
    }
View Code

均值滤波:

public static BMPImage MeanFiltering(BMPImage img){
        BMPImage img2=new BMPImage(img.width,img.height);
        for(int i=1;i<img.height-1;i++){
            for(int j=1;j<img.width-1;j++){
                int r=0,g=0,b=0;
                for(int m=-1;m<=1;m++){
                    for(int n=-1;n<=1;n++){
                        r+=img.red[i+m][j+n];
                        g+=img.green[i+m][j+n];
                        b+=img.blue[i+m][j+n];
                    }
                }
                img2.red[i][j]=(int)(r/9.0);
                img2.green[i][j]=(int)(g/9.0);
                img2.blue[i][j]=(int)(b/9.0);
            }
        }
        return img2;
    }
View Code

 

 中值滤波:

public static BMPImage MidFiltering(BMPImage img){
        BMPImage img2=new BMPImage(img.width,img.height);
        for(int i=1;i<img.height-1;i++){
            for(int j=1;j<img.width-1;j++){
                int[] r=new int[9];
                int[] g=new int[9];
                int[] b=new int[9];
                int cnt=0;
                for(int m=-1;m<=1;m++){
                    for(int n=-1;n<=1;n++){
                        r[cnt]=img.red[i+m][j+n];
                        g[cnt]=img.green[i+m][j+n];
                        b[cnt]=img.blue[i+m][j+n];
                        cnt++;
                    }
                }
                Arrays.sort(r);
                Arrays.sort(g);
                Arrays.sort(b);
                img2.red[i][j]=r[4];
                img2.green[i][j]=g[4];
                img2.blue[i][j]=b[4];
            }
        }
        return img2;
    }
View Code