Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Specify background color when rotating an image using OpenCV in Python

I'm trying to rotate an image in Python using OpenCV with the following code:

import cv2

img = cv2.imread("image.png")

rows = img.shape[0]
cols = img.shape[1]

img_center = (cols / 2, rows / 2)
M = cv2.getRotationMatrix2D(img_center, 45, 1)

rotated_image = cv2.warpAffine(img, M, (cols, rows))

The code works as it should, but the background where the image is no longer visible turns black. I want the background to be white and I'm therefore wondering if it's possible to specify the color OpenCV should use for it when rotating.

Specify background color when rotating an image using OpenCV in Python

I'm trying to rotate an image in Python using OpenCV with the following code:

import cv2

img = cv2.imread("image.png")

rows = img.shape[0]
cols = img.shape[1]

img_center = (cols / 2, rows / 2)
M = cv2.getRotationMatrix2D(img_center, 45, 1)

rotated_image = cv2.warpAffine(img, M, (cols, rows))

The code works as it should, but the background where the image is no longer visible turns black. I want the background to be white and I'm therefore wondering if it's possible to specify the color OpenCV should use for it when rotating.