使用透明图像的OpenCV warpPerspective的问题

2024-05-19 08:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用OpenCV改变一个假眼镜图像的透视图,但是透明部分和不透明度丢失了。结果图像没有透明度。 我想更改透视图,以便将生成的图像压在另一个图像上。在

我能用OpenCV做这个吗?在

#!/usr/bin/python
import numpy as np
import cv2

glasses = cv2.imread('fake_glasses.png')

RES_SIZE = (500,640)

pts1 = np.float32([[  0,  0], [599,  0],
                   [  0,208], [599,208]])
pts2 = np.float32([[ 94,231], [354,181],
                   [115,316], [375,281]])

M = cv2.getPerspectiveTransform(pts1,pts2)

rotated = cv2.warpPerspective(glasses, M, RES_SIZE)
cv2.imwrite("rotated_glasses.png", rotated)

fake_glasses.png (with transparent parts

mask.png


Tags: 图像importsizepngnprescv2opencv
1条回答
网友
1楼 · 发布于 2024-05-19 08:58:28

您加载图像不正确,导致透明层脱落。这很容易验证加载后打印图像的形状。在

>>> img1 = cv2.imread('fake_glasses.png')
>>> print(img1.shape)
(209, 600, 3)

未指定时,^{}的flags参数设置为IMREAD_COLOR。根据the documentation这意味着

If set, always convert image to the 3 channel BGR color image.

相反,您应该使用IMREAD_UNCHANGED

If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).

通过此更改,图像将正确加载,包括alpha平面。在

^{pr2}$

相关问题 更多 >

    热门问题