In this OpenCV tutorial using Python, we will learn how to read a PNG image with transparency or alpha channel.

OpenCV Python – Read PNG images with Transparency (or 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.

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.

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

Example

In the following program, we read a PNG format image located at '/home/img/python.png' using imread() function. We then print the pixel data at a position. The pixel data must contain data corresponding to the four channels.

Python Program

</>
Copy
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 learned how to read a PNG image with transparency channel.