Python, Pillowで画像を回転するrotate

Modified: | Tags: Python, Pillow, 画像処理

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')

lena

回転角度: 引数angle

rotate()では第一引数angleに回転角度をdegree(度)で指定する。回転方向は反時計回り。

90度回転。

im_rotate = im.rotate(90)

Pillow rotate 90

45度回転。

im_rotate = im.rotate(45)

Pillow rotate 45

リサンプリングフィルター: 引数resample

引数resampleでリサンプリングの際に使用するフィルターを指定できる。

  • Image.NEAREST: ニアレストネイバー (デフォルト)
  • Image.BILINEAR: バイリニア
  • Image.BICUBIC: バイキュービック

Image.BICUBICとすると細部がキレイになる。

im_rotate = im.rotate(45, resample=Image.BICUBIC)

Pillow rotate 45 bicubic

出力画像サイズの拡張: 引数expand

上の出力画像から分かるように、デフォルトでは出力画像のサイズは入力画像のサイズと等しくなり、領域外の部分は切り取られてしまう。

回転した画像全体を残したい場合は引数expandTrueにする。

im_rotate = im.rotate(90, expand=True)

Pillow rotate 90 expand

im_rotate = im.rotate(45, expand=True)

Pillow rotate 45 expand

回転の中心座標: 引数center

引数centerで回転の中心位置を指定できる。デフォルトは画像の中心が回転の中心。

im_rotate = im.rotate(45, center=(0, 60))

Pillow rotate 45 change center

expand=Trueの場合、画像中心(デフォルト)で回転したとみなして範囲が決定する。

im_rotate = im.rotate(45, center=(0, 60), expand=True)

Pillow rotate 45 change center expand

平行移動: 引数translate

引数translateで回転前に平行移動させることができる。(x方向の移動距離, y方向の移動距離)で指定する。

分かりやすいように、まず回転角度を0度(無回転)とした例を示す。

im_rotate = im.rotate(0, translate=(100, 50))

Pillow rotate 0 translate

45度にすると以下のようになる。

im_rotate = im.rotate(45, translate=(100, 50))

Pillow rotate 45 translate

expand=Trueの場合、平行移動がない状態(デフォルト)で回転したとみなして範囲が決定する。

im_rotate = im.rotate(45, translate=(100, 50), expand=True)

Pillow rotate 45 translate expand

外側の色: 引数fillcolor

引数fillcolorで外側の色を指定できる。デフォルトは黒。

RGBの場合は(R, G, B)のタプルで指定する。

im_rotate = im.rotate(45, fillcolor=(255, 128, 0), expand=True)

Pillow rotate 45 fillcolor expand

関連カテゴリー

関連記事