「毎日Unity」の技術ブログ

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

【Processing】エッジ検出フィルタ

Processingでエッジ検出フィルタを作ったので残しておくことにしました。

[ 使用例 ]

使用前
使用後

[ プログラム ]

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

//カーネル
float[][] k = new float[][]
{
    {0, 2, 0},
    {2, -8, 2},
    {0, 2, 0},
};
//閾値
int th = 50;

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

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

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

            g[x][y] = 0.3 * red(c) + 0.59 * green(c) + 0.11 * blue(c);
        }
    }

    for(int x1 = 1; x1 < w - 1; x1++) 
    {
        for(int y1 = 1; y1 < h - 1; y1++) 
        {  
            float s = 0;

            for(int x2 = -1; x2 < 1 + 1; x2++)
            {
                for(int y2 = -1; y2 < 1 + 1; y2++)
                {
                    s += (k[x2 + 1][y2 + 1] * g[x1 + x2][y1 + y2]);
                }
            }

            if(s > th)
            {
                s = 255;
            }
            else
            {
                s = 0;
            }

            i.set(x1, y1, color(s));
        }
    }

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