Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the alpha channel of a TIFF image in Python OpenCV?

I want to read the alpha channel from a tiff image using Python OpenCV. I am using Enthought Canopy with OpenCV 2.4.5-3 module.

I followed the OpenCV website's tutorial using cv2.imread, but it doesn't seem to work.

What I have now is:

import cv2
image = cv2.imread('image.tif', -1)

Then I used: print (image.shape), it still shows the (8192, 8192, 3). But I used Matlab to read the same image, I can see the dimension of this image is (8192, 8192, 4).

I am not sure what should I do to read the alpha channel of this image.

Thanks in advance!! Nan

like image 233
Nan An Avatar asked Feb 08 '14 22:02

Nan An


People also ask

Can OpenCV read TIFF?

Can OpenCV read TIFF? So, OpenCV can always read JPEGs, PNGs, and TIFFs.

What is cv2 Imread ()?

cv2. imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix. Syntax: cv2.imread(path, flag)

What is alpha channel in OpenCV?

OpenCV Python – Read PNG images with Transparency (Alpha) Channel. PNG images usually have four channels. Three color channels for red, green and blue, and the fourth channel is for transparency, also called alpha channel.


2 Answers

This is an old question, but just in case someone else stumbles on it: if img.tiff is a 4-channel TIFF, then

import cv2
img = cv2.imread('img.tiff', cv2.IMREAD_UNCHANGED)
print img.shape 

yields (212,296,4) as expected.

If you then use

channels = cv2.split(img)

you can reference the alpha layer (channels[3]) - for instance, as a mask.

The idea for this was taken from How do I use Gimp / OpenCV Color to separate images into coloured RGB layers? which cleverly uses a fake layer and merge to enable recovery of the individual RGB layers in their actual colours.

like image 116
GT. Avatar answered Nov 10 '22 00:11

GT.


I found a solution this problem in converting the original image to RBGA format through PIL library.

from PIL import Image
import numpy as np
import cv2

path_to_image = 'myimg.png'
image = Image.open(path_to_image).convert('RGBA')
image.save(path_to_image)

image = cv2.imread(path_to_image, cv2.IMREAD_UNCHANGED)
print image.shape

out > (800, 689, 4)

like image 42
Alexandr Abramov Avatar answered Nov 10 '22 00:11

Alexandr Abramov