Python 添加alpha通道时,plt.imsave不起作用

Python 添加alpha通道时,plt.imsave不起作用,python,image,matplotlib,Python,Image,Matplotlib,我想写一个透明背景的PNG图像。 将alpha通道添加到阵列时。这是行不通的。将红色、绿色和蓝色作为numpy数组作为float32类型 作品: mask = red*green*blue red[np.where(mask==0)]=0 green[np.where(mask==0)]=0 blue[np.where(mask==0)]=0 rgb = np.dstack((red,green,blue)) plt.imsave("sample.png", rgb, dp

我想写一个透明背景的PNG图像。 将alpha通道添加到阵列时。这是行不通的。将红色、绿色和蓝色作为numpy数组作为float32类型

作品:

mask = red*green*blue
red[np.where(mask==0)]=0
green[np.where(mask==0)]=0
blue[np.where(mask==0)]=0

rgb = np.dstack((red,green,blue))
plt.imsave("sample.png", rgb, dpi = 300)
不起作用:

mask = red*green*blue
red[np.where(mask==0)]=0
green[np.where(mask==0)]=0
blue[np.where(mask==0)]=0
alpha = np.where((mask==0), 0, 255).astype('float32')
rgba = np.dstack((red,green,blue, alpha))
plt.imsave("sample.png", rgba, dpi = 300)

plt.imsave在我添加alpha通道时停止工作。如何解决此问题?

此行看起来不正确:

alpha = np.where((mask==0), 0, 255).astype('float32')
不应该是:

alpha = np.where((mask==0), 0, 1).astype('float32')


根据
rgb
频道的
dtype

您标记了
opencv
,为什么不使用
cv2.imwrite()
?我尝试过,但输出是一个完整的alpha频道,或者只是一个透明图像。它不会返回错误。
alpha = np.where((mask==0), 0, 255).astype('uint8')