OpenCV : How to Load png images with 4 channels?

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

I have been trying to load .png files with transparency channel (RGB and Alph) with no luck. It appears that openCV strips the 4th channel out of the image. Is there any method to load the image with the complete 4 channels including the alpha channel even if I had to modify the OpenCV source code and rebuild it

回答1:

If you are using OpenCV 2 or OpenCV 3 you should use IMREAD_* flags (as mentioned at here).

C++

using namespace cv; Mat image = imread("image.png", IMREAD_UNCHANGED); 

Python

import cv2 im = cv2.imread("image.png", cv2.IMREAD_UNCHANGED) 


回答2:

According to the documentation, OpenCV supports alpha channel on PNGs.

Just call the imread function using CV_LOAD_IMAGE_UNCHANGED as flags like this:

cvLoadImage("file.png", CV_LOAD_IMAGE_UNCHANGED) 


回答3:

The right way to read a transparent PNG is to use the 4th channel as alpha channel. Most of the times one wants a white background, if that is the case then below code can be used for alpha compositing.

def read_transparent_png(filename):     image_4channel = cv2.imread(filename, cv2.IMREAD_UNCHANGED)     alpha_channel = image_4channel[:,:,3]     rgb_channels = image_4channel[:,:,:3]      # White Background Image     white_background_image = np.ones_like(rgb_channels, dtype=np.uint8) * 255      # Alpha factor     alpha_factor = alpha_channel[:,:,np.newaxis].astype(np.float32) / 255.0     alpha_factor = np.concatenate((alpha_factor,alpha_factor,alpha_factor), axis=2)      # Transparent Image Rendered on White Background     base = rgb_channels.astype(np.float32) * alpha_factor     white = white_background_image.astype(np.float32) * (1 - alpha_factor)     final_image = base + white     return final_image.astype(np.uint8) 

A detailed blog on this is here here.



回答4:

Apparently, OpenCV still doesn't support PNGs with Alpha channel.

There are hacks to bypass this.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!