こんにちは、鯨井貴博@opensourcetechです。
今回は、Pythonの画像処理ライブラリ Pillow を使ってみます。
Pillowとは?
PIL(Python Imaging Library)からforkした画像処理ライブラリです。
画像の加工(回転や色の変更)、画像の情報抽出などが出来ます。
以下がドキュメントとなります。
Pillow — Pillow (PIL Fork) 5.1.1 documentation
※PILについては、wiki等を参照してください。
前提条件
前提として、Pythonとpipが入っているものとします。
それらが未インストールの場合、以下のリンクなどを参照にしてインストールしておいてください。
Python モジュールのインストール — Python 3.5.4 ドキュメント
Pillowのインストール
[root@localhost ~]# pip list・・・インストール済みライブラリの一覧表示
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
asn1crypto (0.22.0)
Babel (0.9.6)
bcrypt (3.1.3)
cffi (1.10.0)
colorama (0.3.9)
configparser (3.5.0)
cryptography (2.0.3)
docutils (0.11)
enum34 (1.1.6)
future (0.16.0)
icdiff (1.9.1)
idna (2.6)
ipaddress (1.0.18)
Jinja2 (2.9.6)
jsnapy (1.2.0)
junos-eznc (2.1.6)
lxml (3.8.0)
MarkupSafe (1.0)
ncclient (0.5.3)
netaddr (0.7.19)
nose (1.3.0)
paramiko (2.2.1)
pip (9.0.1)
pyasn1 (0.3.4)
pycparser (2.18)
Pygments (1.5)
PyNaCl (1.1.2)
pyparsing (2.2.0)
pyserial (3.4)
PyYAML (3.12)
scp (0.10.2)
setuptools (0.9.8)
simplejson (3.2.0)
six (1.10.0)
Sphinx (1.1.3)
SQLAlchemy (0.7.9)
virtualenv (13.1.0)
Werkzeug (0.8.3)
wheel (0.24.0)
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@localhost ~]# pip install Pillow・・・Pillowのインストール
Collecting Pillow
Downloading https://files.pythonhosted.org/packages/00/49/a0483e7308b4b04b5a898789911dbb876d9fea54e7df0453915e47744cfd/Pillow-5.1.0-cp27-cp27mu-manylinux1_x86_64.whl (2.0MB)
100% |████████████████████████████████| 2.0MB 520kB/s
Installing collected packages: Pillow
Successfully installed Pillow-5.1.0
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
使用する画像ファイル
いつぞや撮影した金閣寺(鹿苑寺とも呼ばれる)の画像ファイルを使います。
画像ファイル情報の確認
[root@localhost tmp]# python・・・・pythonの起動
Python 2.7.13 (default, Apr 12 2017, 06:53:51)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image, ImageFilter・・・Pillowモジュールの呼び出し
>>> im = Image.open('/tmp/kinkakuji.jpg')・・・画像ファイルを開く
>>> im.show()・・・画像ファイルを表示(GUIに表示がされます)
>>> im.size・・・画像サイズの表示(単位:ピクセル)
(3840, 2160)
>>> im.format・・・画像フォーマットの確認 ※1
'JPEG'
>>> im.mode・・・画像モードの確認 ※2
'RGB'
>>> im.getpixel*1・・・指定座標(画像左上が原点)の色データ取得
(221, 252, 255)
※1 サポートされる画像フォーマット
Image file formats — Pillow (PIL F ork) 5.1.1 documentation
※2 modeのフルリスト
Concepts — Pillow (PIL Fork) 5.1.1 documentation
画像ファイルの加工
>>> im2 = im.convert('L').filter(ImageFilter.GaussianBlur())・・・画像を白黒にする ※3
>>> im2.save('/tmp/kinkakuji2.jpg')・・・画像の保存
>>> im2.show()
>>> im3 = im2.rotate(90)・・・画像の回転
>>> im3.save('/tmp/kinkakuji3.jpg')
>>> im3.show()
>>> exit()
※3 ImageFilterについて
ImageFilter Module — Pillow (PIL Fork) 5.1.1 documentation
*1:100,100