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

Posted on   Capterlliar  阅读(154)  评论(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
复制代码

 

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2021-11-29 POJ-1094 Sorting It All Out
点击右上角即可分享
微信分享提示