Python, Pillowで画像を回転するrotate
Pythonの画像処理ライブラリPillow(PIL)のImage
モジュールに、画像を回転するメソッドrotate()
が用意されている。
ここではrotate()
の使い方として、それぞれの引数について説明する。
- 回転角度: 引数
angle
- リサンプリングフィルター: 引数
resample
- 出力画像サイズの拡張: 引数
expand
- 回転の中心座標: 引数
center
- 平行移動: 引数
translate
- 外側の色: 引数
fillcolor
Pillow(PIL)のインストール、基本的な使い方などは以下の記事参照。
回転ではなく上下反転、左右反転はImageOps
モジュールのflip()
, mirror()
を使う。以下の記事を参照。
OpenCV, NumPyでの画像の回転については以下の記事を参照。
以下のように処理する画像を読み込んでおく。
from PIL import Image
im = Image.open('data/src/lena.jpg')
回転角度: 引数angle
rotate()
では第一引数angle
に回転角度をdegree(度)で指定する。回転方向は反時計回り。
90度回転。
im_rotate = im.rotate(90)
45度回転。
im_rotate = im.rotate(45)
リサンプリングフィルター: 引数resample
引数resample
でリサンプリングの際に使用するフィルターを指定できる。
Image.NEAREST
: ニアレストネイバー (デフォルト)Image.BILINEAR
: バイリニアImage.BICUBIC
: バイキュービック
Image.BICUBIC
とすると細部がキレイになる。
im_rotate = im.rotate(45, resample=Image.BICUBIC)
出力画像サイズの拡張: 引数expand
上の出力画像から分かるように、デフォルトでは出力画像のサイズは入力画像のサイズと等しくなり、領域外の部分は切り取られてしまう。
回転した画像全体を残したい場合は引数expand
をTrue
にする。
im_rotate = im.rotate(90, expand=True)
im_rotate = im.rotate(45, expand=True)
回転の中心座標: 引数center
引数center
で回転の中心位置を指定できる。デフォルトは画像の中心が回転の中心。
im_rotate = im.rotate(45, center=(0, 60))
expand=True
の場合、画像中心(デフォルト)で回転したとみなして範囲が決定する。
im_rotate = im.rotate(45, center=(0, 60), expand=True)
平行移動: 引数translate
引数translate
で回転前に平行移動させることができる。(x方向の移動距離, y方向の移動距離)
で指定する。
分かりやすいように、まず回転角度を0度(無回転)とした例を示す。
im_rotate = im.rotate(0, translate=(100, 50))
45度にすると以下のようになる。
im_rotate = im.rotate(45, translate=(100, 50))
expand=True
の場合、平行移動がない状態(デフォルト)で回転したとみなして範囲が決定する。
im_rotate = im.rotate(45, translate=(100, 50), expand=True)
外側の色: 引数fillcolor
引数fillcolor
で外側の色を指定できる。デフォルトは黒。
RGBの場合は(R, G, B)
のタプルで指定する。
im_rotate = im.rotate(45, fillcolor=(255, 128, 0), expand=True)