In this OpenCV Python tutorial, we will learn how to read a PNG image with transparency or alpha channel using cv2.imread() and cv2.IMREAD_UNCHANGED.
OpenCV Python Read PNG Image with Transparency Channel
A PNG image may contain an alpha channel in addition to its color channels. The alpha channel stores transparency information for each pixel. In OpenCV Python, this matters because the default image reading mode does not preserve the transparent channel.
When you read a transparent PNG using the default cv2.imread() mode, OpenCV loads only the color channels. To keep transparency, pass cv2.IMREAD_UNCHANGED as the second argument. This reads the image as it is, including the alpha channel when it exists.
Why cv2.IMREAD_UNCHANGED is Needed for Transparent PNG Images
PNG files can store transparency, but OpenCV does not keep that transparency when the image is loaded with the default flag, cv2.IMREAD_COLOR. The default mode reads the image as a color image and drops the 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.
cv2.imread('/path/to/image/', cv2.IMREAD_UNCHANGED)
For a transparent PNG, the returned image array generally has four channels in OpenCV: Blue, Green, Red, and Alpha. This order is usually written as BGRA, not RGBA.
OpenCV imread Flags for PNG Transparency
The following table shows how common OpenCV read flags affect a PNG image with transparency.
| OpenCV read flag | What it reads from a transparent PNG | Typical channel count |
|---|---|---|
cv2.IMREAD_COLOR | Reads only the color data and ignores transparency | 3 channels, BGR |
cv2.IMREAD_GRAYSCALE | Reads the image as grayscale | 1 channel |
cv2.IMREAD_UNCHANGED | Reads the image without dropping the alpha channel | 4 channels, BGRA when alpha exists |
Example: Read PNG Image with Alpha Channel in OpenCV Python
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
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.
In this output, the first three values represent the BGR color channels, and the fourth value represents the alpha channel. An alpha value of 255 usually means fully opaque, while an alpha value of 0 means fully transparent.
Check Whether a PNG Image Has an Alpha Channel in OpenCV
Not every PNG image has transparency. Some PNG files contain only three color channels. After reading the image with cv2.IMREAD_UNCHANGED, check the shape of the NumPy array to know whether the alpha channel is present.
import cv2
img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)
if img is None:
print('Could not read the image')
elif len(img.shape) == 3 and img.shape[2] == 4:
print('PNG image has an alpha channel')
print('Image shape:', img.shape)
else:
print('PNG image does not have an alpha channel')
print('Image shape:', img.shape)
For a PNG image with transparency, the shape may look like (height, width, 4). The last number indicates the number of channels.
PNG image has an alpha channel
Image shape: (512, 512, 4)
Split BGRA Channels from a Transparent PNG Image
After reading a PNG image with transparency, you can split the image into separate Blue, Green, Red, and Alpha channels. This is useful when you need to process the transparency mask separately.
import cv2
img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)
if img is None:
print('Could not read the image')
elif len(img.shape) == 3 and img.shape[2] == 4:
blue, green, red, alpha = cv2.split(img)
print('Blue channel shape:', blue.shape)
print('Alpha channel shape:', alpha.shape)
else:
print('This image does not contain four channels')
The alpha array contains the transparency value for each pixel. You can use it as a mask when combining a transparent PNG with another image or background.
Display a Transparent PNG Image on a Solid Background
When you display a transparent PNG directly, the transparent parts may not appear the way you expect in every environment. If you want a predictable preview, you can blend the PNG over a white background before displaying it.
import cv2
import numpy as np
img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)
if img is None:
print('Could not read the image')
elif len(img.shape) == 3 and img.shape[2] == 4:
bgr = img[:, :, :3]
alpha = img[:, :, 3] / 255.0
white_background = np.ones_like(bgr, dtype=np.uint8) * 255
alpha = alpha[:, :, np.newaxis]
result = (bgr * alpha + white_background * (1 - alpha)).astype(np.uint8)
cv2.imshow('PNG on white background', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
cv2.imshow('PNG image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
This example keeps the original color channels and uses the alpha channel only to blend the transparent PNG with a white background.
Save a Transparent PNG After Reading it with OpenCV
If you read a PNG with cv2.IMREAD_UNCHANGED and do not remove the alpha channel, you can save it back as a PNG using cv2.imwrite(). The output file should also contain the alpha channel.
import cv2
img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)
if img is None:
print('Could not read the image')
else:
cv2.imwrite('/home/img/python-copy.png', img)
Use a PNG output file when you want to preserve transparency. Saving to formats that do not support alpha will not keep transparent pixels in the same way.
Common Issues When Reading Transparent PNG Images in OpenCV
The following issues are common when working with PNG transparency in OpenCV Python.
| Issue | Likely reason | Fix |
|---|---|---|
| Alpha channel is missing | The PNG was read with the default cv2.IMREAD_COLOR flag | Use cv2.IMREAD_UNCHANGED |
| Image has only 3 channels | The PNG file may not contain transparency | Check img.shape after reading |
| Pixel values appear in a different color order | OpenCV uses BGR or BGRA channel order | Remember that the first channel is Blue, not Red |
cv2.imread() returns None | Wrong path, missing file, or unsupported/corrupt image file | Check the file path and test if img is None |
| Transparent area does not preview clearly | The display background is not controlled | Blend the PNG with a solid background before display |
QA Checklist for OpenCV PNG Transparency Tutorial
- Confirm that every PNG transparency example uses
cv2.IMREAD_UNCHANGEDwhen the alpha channel must be preserved. - Verify that the tutorial explains OpenCV channel order as
BGRAfor transparent PNG images. - Check that the code handles
cv2.imread()returningNonebefore reading pixel values or displaying the image. - Make sure the article does not imply that every PNG image has transparency; some PNG files have only three channels.
- Confirm that alpha values are explained as transparency values, with
0transparent and255opaque.
FAQs on Reading PNG Images with Transparency in OpenCV Python
Can OpenCV read PNG images with transparency?
Yes. OpenCV can read PNG images with transparency when you pass cv2.IMREAD_UNCHANGED to cv2.imread(). This preserves the alpha channel if the PNG file contains one.
Why does my PNG image have only three channels in OpenCV?
Your PNG may have been read with the default cv2.IMREAD_COLOR flag, or the PNG file itself may not contain transparency. Use cv2.IMREAD_UNCHANGED and check img.shape to confirm the number of channels.
What is the channel order of a transparent PNG in OpenCV?
For a transparent PNG read with cv2.IMREAD_UNCHANGED, OpenCV usually returns channels in BGRA order: Blue, Green, Red, and Alpha. This is different from the common RGBA order used in some other image libraries.
How do I get only the alpha channel from a PNG in OpenCV?
Read the image with cv2.IMREAD_UNCHANGED, then access the fourth channel using img[:, :, 3] if the image shape has four channels. You can also use cv2.split(img) to split all channels.
Does cv2.IMREAD_COLOR preserve PNG transparency?
No. cv2.IMREAD_COLOR reads the PNG as a normal color image and does not preserve the alpha channel. Use cv2.IMREAD_UNCHANGED when transparency is needed.
Conclusion
In this OpenCV Python Tutorial, we learned how to read a PNG image with transparency channel. Use cv2.imread() with cv2.IMREAD_UNCHANGED to preserve the alpha channel, check img.shape to confirm whether transparency exists, and remember that OpenCV stores transparent PNG color data in BGRA channel order.
TutorialKart.com