「毎日Unity」の技術ブログ

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

【Processing】イラスト風フィルタ

Processingでイラスト風フィルタを作ったので残しておくことにしました。

[ 使用例 ]

使用前
使用後

[ プログラム ]

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

//平均化フィルタの一辺のサイズ(奇数)
int th1 = 7;

//階調数
int th2 = 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 = ((th1 - 1) / 2);

    float[][] f = new float[th1][th1];

    for(int x = 0; x < th1; x++)
    {
        for(int y = 0; y < th1; y++)
        {
            f[x][y] = 1.0 / pow(th1, 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));
        }
    }

    for(int x = 0; x < w; x++)
    {
        for(int y = 0; y < h; y++)
        {
            color c1 = i.get(x, y);

            color c2 = color(Get_Tone(red(c1)), Get_Tone(green(c1)), Get_Tone(blue(c1)));

            i.set(x, y, c2);
        }
    }

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

float Get_Tone(float p)
{
    float tmp1 = 255.0 / th2;

    float tmp2 = ceil(p / tmp1) * tmp1;

    return(tmp2);
}