Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pillow v2.6.0 paletted PNG (256) How to add an Alpha channel?

Tags:

python

pillow

I have a numpy array that is written to an image, a RGB colormap added as a palette, and all that remains is a transparency channel (256 values) on top. I have tried converting to RGBA, LA, and other ways around it but, I cannot figure out how to add this multi-value channel on top as a palette.

Here is an example that I have that adds a single-value channel of transparency:

# data = numpy array 1624x3856
im = Image.fromarray(data)
im = im.convert('P')
# cmap is a 768-valued RGB array
im.putpalette(my_cmap)
im.save('filename.png', transparency=0)

The channel I want to save is as follows:

# len(alpha) = 256
alpha = [0,255,255,255...255,255,255]

Any help would be greatly appreciated.

like image 834
monkcoder Avatar asked Oct 23 '14 17:10

monkcoder


People also ask

What is alpha channel in PNG?

Alpha channel. An alpha channel, representing transparency information on a per-pixel basis, can be included in grayscale and truecolor PNG images. An alpha value of zero represents full transparency, and a value of (2^bitdepth)-1 represents a fully opaque pixel.

How do you insert an image into a Pillow in Python?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).


1 Answers

Here is a simple example on how to ensure a Pillow image is RGBA :

img = Image.open("SOME_RGB_IMAGE.png")

if img.mode == "RGB":
    a_channel = Image.new('L', img.size, 255)   # 'L' 8-bit pixels, black and white
    img.putalpha(a_channel)
like image 178
snoob dogg Avatar answered Sep 18 '22 00:09

snoob dogg