简体   繁体   English

使用 OpenCV C++ 将 RGBA 转换为 RBG

[英]Convert RGBA to RBG with OpenCV C++

I have difficulties with converting RGBA PNG to RGB.我很难将 RGBA PNG 转换为 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.我正在使用 OpenCV C++ 加载带有 IMREAD_UNCHANGED 选项的 RGBA PNG,然后我想用白色背景替换 alpha 层。

I would appreciate any hints.我将不胜感激任何提示。

You can use cv::cvtColor to change the pixel format:您可以使用cv::cvtColor更改像素格式:

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. rgb将是没有 alpha 通道的 3 通道 rgb 图像。

Note that there are 2 ways to order the 3 r,g,b channels: either RGB or BGR.请注意,有两种方法可以对 3 个 r,g,b 通道进行排序:RGB 或 BGR。 The default in opencv is BGR, but it supports both. opencv 中默认是 BGR,但它同时支持。 Just specify the proper conversion code from enum ColorConversionCodes : Color Conversion Codes .只需从enum ColorConversionCodes中指定正确的转换代码: 颜色转换代码

See the complete documentation: cv::cvtColor查看完整文档: 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.阅读@ChristophRackwitz 的评论后,我意识到 OP 可能希望根据 alpha 通道在 rgb 通道和白色背景之间进行某种混合。 Ie the closest the alpha value for the pixel to 0, the higher the factor of the background in the blend.即像素的 alpha 值越接近 0,混合中背景的因子就越高。

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.该代码使用cv::Matptr方法访问内部数据缓冲区,并高效地更新它。 rgb_result will contain the blended rgb image. rgb_result将包含混合的 rgb 图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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