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.

In this tutorial, we will learn how to read a PNG image with transparency.

The syntax of imread() function contains a second argument whose default value is cv2.IMREAD_COLOR. Any transparency present in the image is not read.

To read PNG images with transparency (alpha) channel, use cv2.IMREAD_UNCHANGED as second argument in cv2.imread() function as shown in the following.

cv2.imread('/path/to/image/', cv2.IMREAD_UNCHANGED)

Example 1 – Read PNG Image with Transparency

Following is example to read PNG image containing four channels (Red, Green, Blue, Alpha).

read-png-image.py

import cv2

img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)

print(img[100][50])

Output

[176 127  65 255]

The output is a pixel value at (100,50)th position. It contains four channels of data.

Conclusion

In this OpenCV Python Tutorial, we have learnt how to read a PNG image with transparency channel.