「毎日Unity」の技術ブログ

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

【Processing】モザイクフィルタ

Processingでモザイクフィルタを作ったので残しておくことにしました。

[ 使用例 ]

使用前
使用後(平均化オン)
使用後(平均化オフ)

[ プログラム ]

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

//ドットの幅
int th = 10;
//平均化オンオフ
boolean b = true;

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

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

    if(b)
    {
        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 = (int)pow(th, 2);

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

        for(int x1 = 0; x1 < w; x1++)
        {
            for(int y1 = 0; y1 < h; y1++)
            {
                int tmp2 = (int)(x1 / th) * th;
                int tmp3 = (int)(y1 / th) * th;

                for(int x2 = tmp2; x2 < tmp2 + th; x2++)
                {
                    for(int y2 = tmp3; y2 < tmp3 + th; y2++)
                    {
                        int index = (x2 - tmp2) * th + (y2 - tmp3);

                        if(x2 < 0 || y2 < 0 || x2 > w - 1 || y2 > h - 1)
                        {
                            r[index] = -1;
                            g[index] = -1;
                            b[index] = -1;
                        }
                        else
                        {
                            color c = p[x2][y2];

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

                color c = color(Get_Average(r), Get_Average(g), Get_Average(b));

                i.set(x1, y1, c);
            }
        }
    }
    else
    {
        for(int x = 0; x < w; x++)
        {
            for(int y = 0; y < h; y++)
            {
                int tmp1 = (int)(x / th) * th;
                int tmp2 = (int)(y / th) * th;

                i.set(x, y, i.get(tmp1, tmp2));
            }
        }
    }

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

float Get_Average(float[] p)
{
    float tmp1 = 0;
    float tmp2 = 0;

    for(int i = 0; i < p.length; i++)
    {
        if(p[i] != -1)
        {
            tmp1 += p[i];
            tmp2 += 1;
        }
    }

    return(tmp1 / tmp2);
}