「毎日Unity」の技術ブログ

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

【Processing】平均化フィルタ

Processingで平均化フィルタを作ったので残しておくことにしました。

[ 使用例 ]

使用前
使用後

[ プログラム ]

プログラムを実行すると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 tmp = ((th - 1) / 2);

    float[][] f = new float[th][th];

    for(int x = 0; x < th; x++)
    {
        for(int y = 0; y < th; y++)
        {
            f[x][y] = 1.0 / pow(th, 2);
        }
    }

    for(int x1 = tmp; x1 < w - tmp; x1++)
    {
        for(int y1 = tmp; y1 < h - tmp; y1++)
        {
            float r = 0;
            float g = 0;
            float b = 0;

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

                    r += f[x2 + tmp][y2 + tmp] * red(c);
                    g += f[x2 + tmp][y2 + tmp] * green(c);
                    b += f[x2 + tmp][y2 + tmp] * blue(c);
                }
            }

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

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