How to rotate an image using python ?

Published: April 20, 2019

DMCA.com Protection Status

Examples of how to rotate an image using python:

Rotate an image and keep the same size as the original image

To rotate an image, a solution is to use the pillow function rotate(), example

How to rotate an image using python ? How to rotate an image using python ?
How to rotate an image using python ?

from PIL import Image

im = Image.open("eiffel_tower.jpg")

print(im.size)

im = im.rotate(45)

print(im.size)

im.save("eiffel_tower_rotate_01.jpg")
im.show()

Rotate an image

The option "expand = 1" can be added to adapt the size automatically:

How to rotate an image using python ?
How to rotate an image using python ?

from PIL import Image

im = Image.open("eiffel_tower.jpg")

print(im.size)

im = im.rotate(45, expand = 1)

print(im.size)

im.save("eiffel_tower_rotate_02.jpg")
im.show()

Rotate an image (change the background color)

Since the pillow version 5.2, it is possible to specify the background color

 >>> import PIL
 >>> PIL.__version__
 '5.2.0'

example

from PIL import Image

im = Image.open("eiffel_tower.jpg")

im = im.rotate(45, expand = 1, fillcolor='white')

im.save("eiffel_tower_rotate_02.jpg")
im.show()

Get a vertically flipped image

To flip an image vertically a solution is to use the function rotate(), example:

from PIL import Image

im = Image.open("eiffel_tower.jpg")

im = im.rotate(180)

im.save("eiffel_tower_fliped_vertically.jpg")

How to rotate an image using python ? How to rotate an image using python ?
How to rotate an image using python ?

Another solution is tu use flip():

from PIL import Image
from PIL import ImageOps

im = Image.open("eiffel_tower.jpg")

im = ImageOps.flip(im)

im.save("eiffel_tower_fliped_vertically.jpg")

To flip an image vertically with numpy there is flipud, illustration:

import numpy as np 
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('eiffel_tower.jpg')

img2 = np.flipud(img)
plt.imshow(img2)

plt.savefig("eiffel_tower_fliped_vertically.png", dpi=200)
plt.show()

Note: to save an image with frameless see How to create a figure with no axes ( frameless ) or labels using matplotlib ?

References

Links Site
numpy.flipud numpy doc
Comment sauver une image seule sans les contours ou les labels avec matplotlib ? science-emergence article
Image Module illow.readthedocs.io
ImageOps Module pillow.readthedocs.io
Flopped image wikipedia
Flipped image wikipedia
Flip An Image docs.gimp.org
PIL - Images not rotating stackoverflow
Image rotation in Pillow stackoverflow
pixabay pixabay
Image

of