将合并后的图像写入:在OpenCV Python中添加alpha通道后写入图像

5

我想在将图像保存为PNG文件之前更改其背景并添加alpha通道。

imshow展示了图像,但是imwrite却写入了一个空白的图像。合并后的维度也是正确的,即当我打印img_a.shape时,合并后的图像具有(x,y,4)

图像深度为uint8。我尝试将其更改为float32,然后除以255,但似乎没有效果。我可能遗漏了一些基础知识。

我应该怎么做才能让imwrite正确地写入带有alpha通道的PNG?我尝试了cv2.mergenp.dstack,但imwrite仍无法写入。在使用gimp打开它时,只显示了一个图层。

以下是我的代码:

imgo = cv2.imread('PCP_1.jpg')
image = cv2.GaussianBlur(imgo, (5, 5), 0)
r = image.shape[0]
c = image.shape[1]
shp = (r,c,1)
c_red, c_green, c_blue = cv2.split(image)
#c_red = c_red.astype(np.float32)
#c_green =c_green.astype(np.float32)
#c_blue = c_blue.astype(np.float32)
alphachn = np.zeros(shp)
#alphachn = alphachn.astype(np.float32)
img_a = cv2.merge((c_red, c_green, c_blue, alphachn))
#img_a = np.dstack( (imgo, np.zeros(shp).astype(np.uint8) ) )
print img_a.shape
cv2.imshow('image', img_a)
cv2.imwrite('image_alpha.png', img_a)
k = cv2.waitKey(0)
1个回答

3
问题出在透明通道(alpha channel)上,原因是图片可以在imshow中显示但却不能用imwrite来保存,这是因为cv2.imshow()不接受透明通道,而imwrite会考虑透明通道。 根据你的代码,你定义了透明通道为alphachn = np.zeros(shp),这样就创建了一个填充零值的NumPy矩阵和一个零值透明通道,表示透明的图像。换句话说,如果透明通道为零,那么该像素的RGB值永远不会可见,这就是使用imwrite()会得到空白图像的原因。
为了解决问题,应将透明通道初始化为alphachn = np.ones(shp, dtype=np.uint8)*255,这将创建一个NumPy矩阵,其中填充了255的值。如果想要调整透明通道值以获得半透明效果,则可以使用150代替255。

1
我在合并之前执行了alphachn = np.ones(shp)*255,然后执行了alphachn.astype('uint8')。imwrite已经成功地写入了图像。谢谢! - Prakruti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接