Luis Masuelli
Luis Masuelli

Reputation: 12343

How do I read / understand the transparent color in a PNG image with imread?

This is my code (using Anaconda with scikit-image):

from skimage.io import imread
image = imread('myimage.png')

But I'd like to know which one, in the palette, is the transparent color, and be able to treat it like that. This means: When the image is finally loaded, it has shape (W, H, 3) as RGB, despite the info from pnginfo be the following:

Bitdepth (Bits/Sample): 8
Channels (Samples/Pixel): 1
Pixel depth (Pixel Depth): 8
Colour Type (Photometric Interpretation): PALETTED COLOUR with alpha (44 colours, 1 transparent)

I would like one out of three:

How can I?

I am using Anaconda, which has stuff like:

Upvotes: 0

Views: 2266

Answers (2)

Marina Godin
Marina Godin

Reputation: 21

So scipy has depricated imread and python says to use matplotlib's plt.imread(). I had look around and found this example which creates a transparent image by removing the column defining the colour white Code here: https://www.geeksforgeeks.org/how-to-make-background-image-transparent-using-python/

from PIL import Image
  
def convertImage(image=image):
    image = Image.open(image)
    image = image.convert("RGBA")
  
    data = image.getdata()
  
    newData = []
  
    for item in data:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
  
    image.putdata(newData)
    image.save('newimage.png', "PNG")
    
#  
convertImage('apple.jpg')

As you can see it's not perfect but it depends on the resolution you need. Image of apple

Upvotes: 0

Luis Masuelli
Luis Masuelli

Reputation: 12343

The skimage.io.imread method uses Pillow by default (since no plugin argument was passed, and Pillow is the first preferred plugin when calling functions like imread), but the plugin in skimage.io.imread does not make use of the mode argument as other plugins do. Part of the source code demonstrating this lack of support is this:

# This chunk of code belongs to the plugin implementation of imread.
im = Image.open(fname)
try:
    # this will raise an IOError if the file is not readable
    im.getdata()[0]
except IOError:
    site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries"
    raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site))
else:
    return pil_to_ndarray(im, dtype=dtype, img_num=img_num)

Instead of calling skimage.io.read, there's one function in another package (scipy.ndimage.imread, which also comes if you have scikit-image) which does the needed trick:

from scipy.ndimage import imread
rgba = imread('myimage.png', mode='RGBA')

Upvotes: 0

Related Questions