透明图像的 OpenCV warpPerspective 问题
Problems with OpenCV warpPerspective with transparent images
我正在尝试使用 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)
您加载图像不正确,删除了透明层。这很容易验证——加载图像后打印图像的形状。
>>> img1 = cv2.imread('fake_glasses.png')
>>> print(img1.shape)
(209, 600, 3)
不指定时,imread
is set to IMREAD_COLOR
. According to the documentation的flags参数表示
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 平面。
>>> img2 = cv2.imread('fake_glasses.png', cv2.IMREAD_UNCHANGED)
>>> print(img2.shape)
(209, 600, 4)
我正在尝试使用 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)
您加载图像不正确,删除了透明层。这很容易验证——加载图像后打印图像的形状。
>>> img1 = cv2.imread('fake_glasses.png')
>>> print(img1.shape)
(209, 600, 3)
不指定时,imread
is set to IMREAD_COLOR
. According to the documentation的flags参数表示
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 平面。
>>> img2 = cv2.imread('fake_glasses.png', cv2.IMREAD_UNCHANGED)
>>> print(img2.shape)
(209, 600, 4)