Python, Pillow: Rotate image

Posted: 2019-06-25 / Tags: Python, Pillow, Image Processing
Sponsored Link


In the Image module of the Python image processing library Pillow(PIL), a method rotate() for rotating an image is provided.

Please refer to the following post for installation and basic usage of Pillow(PIL).

Use flip() and mirror() of the ImageOps module to flip the image vertically or horizontally.

See the following post for image rotation with OpenCV, NumPy.

Sample code

Load the image.

from PIL import Image

im ='data/src/lena.jpg')


Rotation angle

In rotate(), specify the rotation angle in degrees as the first argument. The direction of rotation is counterclockwise.

Rotate 90 degrees:

im_rotate = im.rotate(90)

Pillow rotate 90

Rotate 45 degrees.

im_rotate = im.rotate(45)

Pillow rotate 45

Parameter expand

As can be seen from the output image of the above example, by default the size of the output image is equal to the size of the input image, and parts outside the region are truncated.

Set the parameter expand to True if you want to keep the whole rotated image.

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

Pillow rotate 90 expand

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

Pillow rotate 45 expand

Parameter resample

The parameter resample can be used to specify the filter to be used for resampling.

  • Image.NEAREST (Nearest neighbor / default)
  • Image.BILINEAR
  • Image.BICUBIC

With Image.BICUBIC, the details are clearer than the default Image.NEAREST.

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

Pillow rotate 45 expand bicubic

Parameter center

You can specify the rotation center position with the parameter center. By default, center is the center of the image.

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

Pillow rotate 45 change center

In the case of expand=True, the output image area is determined assuming that the image is rotated about the image center.

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

Pillow rotate 45 change center expand

Parametet translate

You can translate before rotation with the parameter translate. translate is specified by (translation distance in x direction, translation distance in y direction).

Without rotation:

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

Pillow rotate 0 translate

Rotate 45 degrees and translate:

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

Pillow rotate 45 translate

If expand=True, the output image area is determined assuming that the image is rotated without translation.

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

Pillow rotate 45 translate expand

Sponsored Link

Related Categories

Related Posts