David
David

Reputation: 33

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.

I found a similar question but for PIL.

Upvotes: 2

Views: 6008

Answers (2)

shivaraj karki
shivaraj karki

Reputation: 159

In order to fill the borders same as image border pixel colors, use

#find out average pixel intensity 
border_val = tuple(np.mean(np.array(image)[0, :], axis=0))

# perform the actual rotation 
image = cv2.warpAffine(image, M, (cols, rows),
                       borderMode=cv2.BORDER_CONSTANT,
                       borderValue=[int(i) for i in border_val])              

Upvotes: 0

A Kruger
A Kruger

Reputation: 2419

The warpAffine parameter borderMode can be used to control how the background will be handled. You can set this to cv2.BORDER_CONSTANT to make the background a solid color, then choose the color with the parameter borderValue. For example, if you want a green background, use

rotated_image = cv2.warpAffine(img, M, (cols, rows),
                           borderMode=cv2.BORDER_CONSTANT,
                           borderValue=(0,255,0))

Upvotes: 14

Related Questions