加载具有透明背景的图像

时间:2020-07-20 16:19:25

标签: python opencv

我尝试过的

我尝试加载此

Small Circle

在python中带有opencv的图像,如您所见,图像将以png的形式加载到此处而没有alpha通道。但是原始图像的所有内容都是透明的,只有圆圈可见。在下面的示例中,我加载该图像并使用cv2.imshow显示该图像。有趣的是,我的整个背景有点发黄。

import cv2

foreground = cv2.imread('img2.png', cv2.IMREAD_UNCHANGED)

cv2.imshow('img', foreground)
cv2.waitKey(0)

cv2.destroyAllWindows()

imshow的结果如下:

enter image description here

因此,我在加载代码后进一步检查了图像并检查了数组值。现在,我的第一个像素是背景,但是我需要找到绿色像素:

import cv2
import numpy as np

foreground = cv2.imread('img2.png', cv2.IMREAD_UNCHANGED)

bg_pixel_u = 0
bg_pixel_v = 0

print(foreground[bg_pixel_u, bg_pixel_v,:])
# > [115 189 247 0]

gr_pixel_u = np.where(foreground[:,:,0] != 115)[0][0]
gr_pixel_v = np.where(foreground[:,:,0] != 115)[1][0]

print(foreground[gr_pixel_u, gr_pixel_v,:])
# > [7 255 82 254]

cv2.imshow('img', foreground)
cv2.waitKey(0)

cv2.destroyAllWindows()

所以我对掩码数组做了一个小解决方法:

mask = foreground[:,:,3] == 0
foreground[mask, :3] = [0, 0, 0]

所以我的最终图像如下:

enter image description here

我的问题

所以我的值[115 189 247 0]来自我的原始图像,它们是我在gimp中使用的背景。在我使用opencv加载图像之前,它们不可见。因此,有没有一种加载图像的方法,因此可以轻松地使用cv2.addWeighted堆叠图像?因为此功能似乎忽略了我的Alpha通道值。

我的版本

python:3.7.7 opencv:3.4.2

0 个答案:

没有答案