Rotate Image Without Cropping | OpenCV vs Pillow | Python

This tutorial will show you how to rotate an image without cutting/cropping the sides of it using OpenCV (cv2) and Pillow (PIL). We also call this “rotation with bounding”.

Rotate With Bounding

Rotate without cropping
Rotate without cropping

For OpenCV, you need to first install imutils by: pip install imutils.

The following code shows the image rotation by 45 degrees counterclockwise.

# OpenCV
rotated_cv2_img = imutils.rotate_bound(cv2_img, -45)

# Pillow
rotated_pil_img = pil_img.rotate(45, expand=True)

Full Example

OpenCV

import cv2
import imutils

# read image
cv2_img = cv2.imread("test_images/test1.jpg")

# rotate 45 degrees counterclockwise
rotated_cv2_img = imutils.rotate_bound(cv2_img, -45)

# show the rotated image
cv2.imshow("cv2 rotated image", rotated_cv2_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Pillow

from PIL import Image

# read image
pil_img = Image.open("test_images/test1.jpg")

# rotate 45 degrees counterclockwise
rotated_pil_img = pil_img.rotate(45, expand=True)

# show the rotated image
rotated_pil_img.show("pil rotated image")

Syntax

Imutils

imutils.rotate_bound(image, angle)

Parameters:

  • image: cv2 image (Numpy array).
  • angle: angle in degrees. A negative number for counterclockwise rotation.

Returns:

  • An image (Numpy array).

Pillow

For syntax of Image.rotate, Please see Python | Rotate Image | OpenCV vs Pillow.

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.