简体   繁体   中英

Convert RGBA to RBG with OpenCV C++

I have difficulties with converting RGBA PNG to RGB. I'm using OpenCV C++ to load RGBA PNG with IMREAD_UNCHANGED option and then I'd like to replace the alpha layer with white background.

I would appreciate any hints.

You can use cv::cvtColor to change the pixel format:

cv::Mat rgba = cv::imread("some_path", cv::IMREAD_UNCHANGED);
cv::Mat rgb;
cv::cvtColor(rgba, rgb, cv::COLOR_BGRA2BGR);

rgb will be a 3 channel rgb image without the alpha channel.

Note that there are 2 ways to order the 3 r,g,b channels: either RGB or BGR. The default in opencv is BGR, but it supports both. Just specify the proper conversion code from enum ColorConversionCodes : Color Conversion Codes .

See the complete documentation: cv::cvtColor

Update:

After reading the comments by @ChristophRackwitz I realized the OP probably wants to do some kind of blending between the rgb channels and a white background, depending on the alpha channel. Ie the closest the alpha value for the pixel to 0, the higher the factor of the background in the blend.

This is what the code below does:

cv::Mat rgba = cv::imread("image_path", cv::IMREAD_UNCHANGED);

cv::Mat rgb_result(rgba.size(), CV_8UC3);
for (int y = 0; y < rgba.rows; ++y)
{
    auto const * rgba_pLine = rgba.ptr<cv::Vec4b>(y);
    auto * rbg_result_pLine = rgb_result.ptr<cv::Vec3b>(y);
    for (int x = 0; x < rgba.cols; ++x)
    {
        auto const & rgba_pixel = rgba_pLine[x];
        auto & rgb_result_pixel = rbg_result_pLine[x];
        float alpha0to1 = rgba_pixel[3] / 255.f;
        rgb_result_pixel[0] = static_cast<uchar>(alpha0to1 * rgba_pixel[0] + (1 - alpha0to1) * 255);
        rgb_result_pixel[1] = static_cast<uchar>(alpha0to1 * rgba_pixel[1] + (1 - alpha0to1) * 255);
        rgb_result_pixel[2] = static_cast<uchar>(alpha0to1 * rgba_pixel[2] + (1 - alpha0to1) * 255);
    }
}

The code uses the ptr method of cv::Mat to access the internal data buffer, and update it efficiently. rgb_result will contain the blended rgb image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM