Ask Your Question

Specify background color when rotating an image using OpenCV in Python

asked 2018-11-01 14:50:45 -0500

Friendly_Mess gravatar image

updated 2018-12-10 07:32:34 -0500

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.

edit retag flag offensive close merge delete



downvoted for: failure to read docs (before asking anywhere)

berak gravatar imageberak ( 2018-11-01 15:03:03 -0500 )edit

@Friendly_Mess -- sorry for being, some kind of "brutal" on a noob here, but ..

berak gravatar imageberak ( 2018-11-01 15:10:17 -0500 )edit

Scalar() (the default for "border-color" is the same as (0,0,0))

berak gravatar imageberak ( 2018-11-01 15:17:46 -0500 )edit

@berak This is a valid question. BorderValue could mean a lot of things, and its difficult to make sure before trying the code. So reading the docs alone could not have been helpful for the OP.

pauljeba gravatar imagepauljeba ( 2020-05-30 23:00:25 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2018-11-01 15:32:08 -0500

berak gravatar image

what you want, in the end is to specify the background color explicitly, like :

 rotated_image = cv2.warpAffine(img, M, (cols, rows), borderValue=(255,255,255))
edit flag offensive delete link more


Works great.

pauljeba gravatar imagepauljeba ( 2020-05-30 22:58:37 -0500 )edit

Question Tools

1 follower


Asked: 2018-11-01 14:50:45 -0500

Seen: 7,221 times

Last updated: Nov 01 '18