Pillowで画像処理

Pillowは、もし誤解していなければ、GDIのような単純なグラフィクスライブラリーだ。
バッファーを準備して、線を書いたり、単純な図形を書いたり、画像を読みだして表示したりできる。
setpixelやgetpixelもあるので、それを利用して画像処理を書くこともできる。
こんな感じだ。

    imageFromFile = Image.open(filename) # it generates the PIL.Image.Image object
    imageFromFile.show()
    input()

    # manipulate R, G, B to set all to Y
    imageBuffer = Image.new('RGB', imageFromFile.size) # it generates the PIL.Image.Image object
    for y_pos in range(imageFromFile.size[1]):
        for x_pos in range(imageFromFile.size[0]):
            (inR, inG, inB) = imageFromFile.getpixel((x_pos, y_pos)) # the cordinate is type, it returns pixel value of tuple
            Y = int(inR * .3 +  inG * .6 + inB * .1)
            outR = Y
            outG = Y
            outB = Y
            imageBuffer.putpixel((x_pos, y_pos), (outR, outG, outB)) # the cordinate is type, the pixel value is tuple
    imageBuffer.show()

ここでは、RGB値を元に輝度(Y)値をITU-R.BT601を使って概算(R x 0.3 + G x 0.6 + B x 0.1、ビット誤差が気になる場合には R / 4 + G x 5 / 8 + B x 1 / 8 とするのが吉)で求めている、https://ja.wikipedia.org/wiki/YUV
同じ方法で画素ごとのフィルターや空間フィルターが書ける。
Pillowには描画機能がないので、showメソッドはOSデフォルトのビュワーを開く。


github.com