我想更改图像的背景,然后在保存为png文件之前向其添加alpha通道。
imshow
显示了图像,但是imwrite
写了一个空图像。合并后的维度也正确,即合并的图像具有(x,y,4)
,当我打印img_a.shape
图像深度为uint8
。我尝试将其更改为float32
,然后除以255
,但似乎无效。我缺少一些基本的东西。
我该怎么办imwrite
使用Alpha Channel编写正确的PNG?我尝试了cv2.merge
和np.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)
问题在于您的alpha频道,其原因是 imshow
中显示的图像,但没有使用 imwerite
显示的图像在于 cv2.imshow()拒绝Alpha Channel的表面IMwrite考虑了Alpha频道。
根据您的代码,您将Alpha通道定义为alphachn = np.zeros(shp)
,它创建了一个填充零值的Numpy矩阵,并且具有所有零值的Alpha通道表示透明 image image,或者说明Alpha频道为零,则该像素的RGB值永远不可见,这就是您使用imwrite()
获得空图像的原因。
对于修复程序,您应该将alpha初始化为alphachn = np.ones(shp, dtype=np.uint8)*255
,该alpha创建了一个具有255
值的Numpy矩阵。如果您想调整Alpha通道值以获得半透明的结果,则可以使用255的150。