OpenCV:如何用4个通道加载png图像?

时间:2010-09-27 12:46:17

标签: c opencv

我一直试图用透明通道(RGB和Alph)加载.png文件而没有运气。似乎openCV剥离了图像中的第4个通道。是否有任何方法可以使用完整的4个通道加载图像,包括alpha通道,即使我必须修改OpenCV源代码并重建它

5 个答案:

答案 0 :(得分:47)

如果您使用的是OpenCV 2或OpenCV 3,则应使用IMREAD_ *标志(如here中所述)。

<强> C ++

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

<强>的Python

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

答案 1 :(得分:11)

根据documentation,OpenCV支持PNG上的alpha通道。

使用CV_LOAD_IMAGE_UNCHANGED作为这样的标志调用imread函数:

cvLoadImage("file.png", CV_LOAD_IMAGE_UNCHANGED)

答案 2 :(得分:7)

读取透明PNG的正确方法是将第4个通道用作Alpha通道。大多数情况下,人们想要一个白色背景,如果是这种情况,那么下面的代码可以用于alpha合成。

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)

关于此的详细博客在here

答案 3 :(得分:0)

加载所有4个通道的png图像的最佳方法是;

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

根据openCV文档,
如果标志值为,
 1)= 0返回灰度图像。
 2)<0按原样返回加载的图像(带有Alpha通道)。

答案 4 :(得分:0)

如果您想将此透明图像绘制在另一幅图像上,请按照@ satya-mallick的回答打开您的图像,然后使用以下方法:

/**
 * @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);
}