Rotate/Translate Image with Background Color | OpenCV vs Pillow | Python

In this tutorial, you will learn how to rotate or translate/shift an image with a specified background color. For simple image rotation and translation, please read the previous tutorials:

Rotate with specified background-color
Rotate with specified background-color

1. Image Rotation

Rotate 45 degrees counterclockwise with a background color RGB(0,0,0) (black).

OpenCV

h, w = cv2_img.shape[:2]
M = cv2.getRotationMatrix2D(center=(w/2, h/2), angle=45, scale=1.0)
rotated_cv2_img = cv2.warpAffine(cv2_img, M, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))

Pillow

rotated_pil_img = pil_img.rotate(45, fillcolor=(0,0,0))

2. Image Translation

Translate the image to the right by 10 pixels and downward by 20 pixels with a background color RGB(0,0,0) (black).

OpenCV

shift_x = 10
shift_y = 20
h, w = cv2_img.shape[:2]
M = np.float32([[1, 0, shift_x],[0, 1, shift_y]])
shifted_cv2_img = cv2.warpAffine(cv2_img, M, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))

Pillow

shift_x = 10
shift_y = 20
shifted_pil_img = pil_img.rotate(0, translate=(shift_x, shift_y), fillcolor=(0,0,0))

Full Example

OpenCV

import cv2
import numpy as np

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

# rotate 45 degrees counterclockwise
h, w = cv2_img.shape[:2]
M = cv2.getRotationMatrix2D(center=(w/2, h/2), angle=45, scale=1.0)
# specify background color RGB(0,255,0)
rotated_cv2_img = cv2.warpAffine(cv2_img, M, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=(0,255,0))

# translate it to the right by 10 pixels and downward by 20 pixels
shift_x = 10
shift_y = 20
h, w = cv2_img.shape[:2]
M = np.float32([[1, 0, shift_x],[0, 1, shift_y]])
# specify background color RGB(0,255,0)
shifted_cv2_img = cv2.warpAffine(cv2_img, M, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=(0,255,0))

# show the images
cv2.imshow("cv2 rotated image", rotated_cv2_img)
cv2.imshow("cv2 shifted image", shifted_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 with background color RGB(0,255,0)
rotated_pil_img = pil_img.rotate(45, fillcolor=(0,255,0))

# translate it to the right by 10 pixels and downward by 20 pixels
shift_x = 10
shift_y = 20
# specify background color RGB(0,255,0)
shifted_pil_img = pil_img.rotate(0, translate=(shift_x, shift_y), fillcolor=(0,255,0))

# show the images
rotated_pil_img.show("pil rotated image")
shifted_pil_img.show("pil shifted image")

Syntax

For the syntax of both OpenCV and Pillow, please see Python | Rotate Image | OpenCV vs Pillow.

Avatar photo
Steins

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