Pillowで画像をいじってみた


Pillowとは?

Pythonの画像処理ライブラリです。
https://pillow.readthedocs.io/en/stable/

今回の環境

  • Jupyter Notebook 5.7.8
  • Pillow 5.4.1
  • Matplotlib 3.0.3

準備

パッケージをインポートします。

from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline

とりあえず画像を表示させる

lena = Image.open("./lena.png")
type(lena)
出力
PIL.PngImagePlugin.PngImageFile
fig, ax = plt.subplots()
ax.imshow(lena)
plt.title("Lena Color")
plt.show()

グレースケール化してみる

lena_gray = lena.convert("L")
type(lena_gray)
出力
PIL.Image.Image
fig, ax = plt.subplots()
ax.imshow(lena_gray)
plt.title("Lena Gray")
plt.show()

変な色になりますが、これはMatplotlibの仕様です。
カラーマップをデフォルト値から変更する必要があります。
グレースケールの画像を表示する場合はcmap="gray"を指定します。

For actually displaying a grayscale image set up the color mapping using the parameters

fig, ax = plt.subplots()
ax.imshow(lena_gray, cmap="gray")
plt.title("Lena Gray")
plt.show()

保存する

lena_gray.save("./lena_gray.png")

リサイズする

lena_resize = lena.resize((150,150))
fig, ax = plt.subplots()
ax.imshow(lena_resize)
plt.title("Lena Resize")
plt.show()

画像の目盛に注目するとサイズが変更されていることが分かります。

回転させる

今回は画像を75度回転させます。

lena_rotate = lena.rotate(75)
fig, ax = plt.subplots()
ax.imshow(lena_rotate)
plt.title("Lena rotate 75")
plt.show()

見切れてしまいました。
元の画像のサイズから変更されていないようです。
Image.rotateにexpand=Trueを追記して見切れないようにします。

Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image.

lena_rotate_expand = lena.rotate(75, expand=True)
fig, ax = plt.subplots()
ax.imshow(lena_rotate_expand)
plt.title("Lena rotate 75 expand")
plt.show()