首页 > 解决方案 > 添加 Alpha 通道时 plt.imsave 不起作用

问题描述

我想写一个透明背景的PNG图像。当我向数组添加 alpha 通道时。plt.imsave将不起作用。让 red、green、blue 成为 float32 类型的 numpy 数组。

作品:

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 通道时停止工作。如何解决这个问题?

标签: pythonimagematplotlib

解决方案


这条线看起来不正确:

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

不应该是:

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

或者

alpha = np.where((mask==0), 0, 255).astype('uint8')

取决于渠道dtypergb


推荐阅读