plt.imsave does not work when alpha channel is added

Viewed 450

I want to write a PNG image with transparent background. When I add an alpha channel to the array. plt.imsave will not work. Let red, green, blue be numpy arrays as type float32.

Works:

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)

Does Not Work:

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 just stop working when I add an alpha channel. How to resolve this?

1 Answers

This line doesn't look right:

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

Shouldn't it be either:

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

or

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

depending on dtype of rgb channels.

Related