在 Python 中使用 OpenCV 旋转图像时指定背景颜色

Specify background color when rotating an image using OpenCV in Python

我正在尝试通过以下代码使用 OpenCV 在 Python 中旋转图像:

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))

代码正常运行,但图像不再可见的背景变为黑色。我希望背景是白色的,因此我想知道是否可以指定旋转时应该使用的颜色 OpenCV

我找到了 但是 PIL

warpAffine 参数 borderMode 可用于控制背景的处理方式。您可以将其设置为 cv2.BORDER_CONSTANT 以使背景成为纯色,然后使用参数 borderValue 选择颜色。例如,如果您想要绿色背景,请使用

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