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()
Author And Source
この問題について(Pillowで画像をいじってみた), 我々は、より多くの情報をここで見つけました https://qiita.com/Hiroki1928/items/b21fc5b91ce980e442b1著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .