How to load png images with 4 channels?

Viewed 92621

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?

6 Answers

If you wanna draw this transparent image over another image, open your image as answered by @satya-mallick (mode IMREAD_UNCHANGED), then use this method to draw the image over a frame Mat:

/**
 * @brief Draws a transparent image over a frame Mat.
 * 
 * @param frame the frame where the transparent image will be drawn
 * @param transp the Mat image with transparency, read from a PNG image, with the IMREAD_UNCHANGED flag
 * @param xPos x position of the frame image where the image will start.
 * @param yPos y position of the frame image where the image will start.
 */
void drawTransparency(Mat frame, Mat transp, int xPos, int yPos) {
    Mat mask;
    vector<Mat> layers;
    
    split(transp, layers); // seperate channels
    Mat rgb[3] = { layers[0],layers[1],layers[2] };
    mask = layers[3]; // png's alpha channel used as mask
    merge(rgb, 3, transp);  // put together the RGB channels, now transp insn't transparent 
    transp.copyTo(frame.rowRange(yPos, yPos + transp.rows).colRange(xPos, xPos + transp.cols), mask);
}

The best possible way to load a png image with all 4 channels is ;

img= cv2.imread('imagepath.jpg',negative value)

As per openCV documentation,
If Flag value is,
1) =0 Return a grayscale image.
2) <0 Return the loaded image as is (with alpha channel).

you can use:

import matplotlib.image as mpimg


img=mpimg.imread('image.png')
plt.imshow(img)
Related