「毎日Unity」の技術ブログ

開発で役立つ情報を発信する

【Processing】メディアンフィルタ

Processingでメディアンフィルタを作ったので残しておくことにしました。

[ メディアンフィルタとは ]

周辺画素値の中央値(メディアン)を使って画像のノイズを除去する手法です。
www.sophia-it.com

[ 使用例 ]

使用前
使用後

[ プログラム ]

プログラムを実行するとpdeファイルと同じディレクトリ内にフィルタリングされた画像が保存されます。

//フィルタの一辺のサイズ(奇数)
int th = 5;

void setup()
{
    PImage i = loadImage("入力画像.png");

    int w = i.width;
    int h = i.height;

    color p[][] = new color[w][h];
    for(int x = 0; x < w; x++)
    {
        for(int y = 0; y < h; y++)
        {
            p[x][y] = i.get(x, y);
        }
    }

    int tmp1 = ((th - 1) / 2);

    int tmp2 = (int)pow(th, 2);

    float[] r = new float[tmp2];
    float[] g = new float[tmp2];
    float[] b = new float[tmp2];

    int m = tmp2 - ((tmp2 - 1) / 2) - 1;

    for(int x1 = tmp1; x1 < w - tmp1; x1++)
    {
        for(int y1 = tmp1; y1 < h - tmp1; y1++)
        {
            for(int x2 = -tmp1; x2 < tmp1 + 1; x2++)
            {
                for(int y2 = -tmp1; y2 < tmp1 + 1; y2++)
                {
                    color c = p[x1 + x2][y1 + y2];

                    int index = (x2 + tmp1) * th + (y2 + tmp1);

                    r[index] = red(c);
                    g[index] = green(c);
                    b[index] = blue(c);
                }
            }

            r = sort(r);
            g = sort(g);
            b = sort(b);

            i.set(x1, y1, color(r[m], g[m], b[m]));
        }
    }

    i.save("出力画像.png");
}