Image Translation | OpenCV vs Pillow | Python

This tutorial will show you how to translate/shift an image along the x-axis and y-axis using OpenCV (cv2) and Pillow (PIL).

Translate an image
Translate an image

OpenCV

Translate the image 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]])
shifted_cv2_img = cv2.warpAffine(cv2_img, M, (w, h))

Pillow

Translate the image to the right by 10 pixels and downward by 20 pixels.

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

Note: pil_img.rotate(angle, translate) will do translation before rotation.

Full Example

OpenCV

import cv2
import numpy as np

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

# 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]])
shifted_cv2_img = cv2.warpAffine(cv2_img, M, (w, h))

# show the image
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")

# translate it to the right by 10 pixels and downward by 20 pixels
shift_x = 10
shift_y = 20
shifted_pil_img = pil_img.rotate(0, translate=(shift_x, shift_y))

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

Syntax

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

References

Avatar photo
Steins

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