Ask Your Question
-2

Specify background color when rotating an image using OpenCV in Python

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

Friendly_Mess gravatar image

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

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

Comments

1

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

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

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

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

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

berak gravatar imageberak ( 2018-11-01 15:17:46 -0600 )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 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
4

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

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

Comments

Works great.

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

Question Tools

1 follower

Stats

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

Seen: 17,170 times

Last updated: Nov 01 '18