LoginSignup
6
7

More than 5 years have passed since last update.

Pillowを使ってPythonで簡単に画像処理する

Last updated at Posted at 2017-04-04

pillow: 画像処理ライブラリ。scikit-imageやopencvより軽量でお手軽。

インストール

$ pip install -U Pillow

wgetで画像取得

$ cd <workspace>
$ wget --no-check-certificate -O gorilla.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Male_silverback_Gorilla.JPG/236px-Male_silverback_Gorilla.JPG
$ atom test_pillow.py # 下記参照

gorilla.jpg

画像を読み込んで、お絵描きして保存するスクリプト

test_pillow.py
from __future__ import print_function
from PIL import Image, ImageDraw, ImageFont

# fileから読み込み
im = Image.open('gorilla.JPG')

# 画像情報
print(im.format, im.size, im.mode)

# コード変換 Gray
# im = im.convert("L")
# コード変換 Alpha Channel 追加
# im = im.convert('RGBA')
# コード変換 RGB2BGR
# r, g, b = im.split() 
# im = Image.merge("RGB", (b, g, r))

# 領域切り取り
# box = (50, 50, 200, 200) # left, upper, right, lower
# region = im.crop(box)
# region
# region.show()
# 領域貼り付け
# im = im.paste(region, box)

# 画像変換
# im = im.transpose(Image.FLIP_LEFT_RIGHT)
# im = im.transpose(Image.ROTATE_90)
# im = im.rotate(45)

# フィルタリング
# from PIL import ImageFilter
# im = im.filter(ImageFilter.BLUR)

# お絵描き
# font_bookで調べて好きな fontを選ぶ @mac
fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', size=20)
d = ImageDraw.Draw(im)
d.line((0, 0) + im.size, fill=(128,0,0), width=2)
d.line((0, im.size[1], im.size[0], 0), fill=(128,0,0), width=2)
# draw rectangle
import numpy as np
thickness = 5
left, top, right, bottom = 30,20, 220, 220 # ほんとは deep_learning使う。今回は指定。
text_origin = (10,10)
label_size = d.textsize("gorilla", fnt)
for i in range(thickness):
    d.rectangle([left + i, top + i, right - i, bottom - i], outline=(0,0,128))
d.rectangle([text_origin, tuple(np.array(text_origin) + label_size)], fill=(0,0,128))
d.text(text_origin, "gorilla", font=fnt, fill=(255,255,255))
del d

# 画像保存
im.save('gorilla_convert.jpg')

# 画像表示
im.show()

実行

$ python test_pillow.py

gorilla_convert.jpg

スクリーンキャプチャ

from PIL import ImageGrab

ImageGrab.grab(bbox=(0, 50, 800, 650))
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7