在OpenCV C++中将图像的所有白色像素变为透明

6

我在OpenCV中有这张图片 imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_COLOR);:

enter image description here

当我使用灰度加载它 imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_GRAYSCALE); 时,它看起来像这样:

enter image description here

然而,我想要删除白色背景或使其透明(仅其白色像素),看起来像这样:

如何在C++ OpenCV中实现?

enter image description here


cv::cvtColor(input,output; CV_BGR2BGRA); 然后,对于每个像素:如果像素为白色,则将该像素的 alpha 值设置为零。 - Micka
啊,你的输入图像已经是透明的了?使用CV_LOAD_IMAGE_ANYDEPTH标志。 - Micka
请使用任何负值来读取图像,详见 http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#imread - Micka
但是请注意,像cv :: imshow这样的opencv gui函数无法正确处理alpha通道,因此您必须自己处理它。 但是,您确实拥有alpha值=透明度信息! - Micka
1
然后加载为彩色图像,并使用我的第一个评论 :) 如果您在此过程中遇到问题,请告诉我。 - Micka
显示剩余2条评论
1个回答

18

您可以将输入图像转换为带有alpha通道的BGRA通道(彩色图像),然后将每个白色像素的alpha值设置为零。

参见以下代码:

    // load as color image BGR
    cv::Mat input = cv::imread("C:/StackOverflow/Input/transparentWhite.png");

    cv::Mat input_bgra;
    cv::cvtColor(input, input_bgra, CV_BGR2BGRA);

    // find all white pixel and set alpha value to zero:
    for (int y = 0; y < input_bgra.rows; ++y)
    for (int x = 0; x < input_bgra.cols; ++x)
    {
        cv::Vec4b & pixel = input_bgra.at<cv::Vec4b>(y, x);
        // if pixel is white
        if (pixel[0] == 255 && pixel[1] == 255 && pixel[2] == 255)
        {
            // set alpha to zero:
            pixel[3] = 0;
        }
    }

    // save as .png file (which supports alpha channels/transparency)
    cv::imwrite("C:/StackOverflow/Output/transparentWhite.png", input_bgra);

这将保留您的图像透明度。 在GIMP中打开的结果图像看起来像:

输入图像的描述

正如您所见,一些“白色区域”不是透明的,这意味着您输入图像中这些像素并不完全是白色的。 您可以尝试使用

    // if pixel is white
    int thres = 245; // where thres is some value smaller but near to 255.
    if (pixel[0] >= thres&& pixel[1] >= thres && pixel[2] >= thres)

似乎不起作用。 transparentGUI.png 仍然有背景。此外,以灰度加载此图像会导致崩溃。 - ScriptyChris
在灰度加载中,您必须在cvtColor中使用CV_GRAY2BGRA代码。如果我运行代码,我的png结果图像具有透明度。您是否在GIMP中打开它?一些查看器总是显示背景。 - Micka
cvtColor 使用 CV_GRAY2BGRA 也会导致崩溃。我在 GIMP 中检查了一下,白色背景仍然存在。我可能犯了什么错误? - ScriptyChris
抱歉,我在GIMP中检查了错误的图像(旧的“newGUI.png”图像而不是修改后的图像) - 没有白色背景,这很好。但是OpenCV仍然无法加载它(崩溃)或者带有背景加载。 错误信息为:“在0x74FCB727处未处理的异常,位于ConsoleApplication1.exe中:Microsoft C++异常:cv::Exception,内存位置为0x002AC198。”,当我像这样操作时 Mat imgColorPanel0,imgColorPanel; imgColorPanel0 = imread("transparentGUI.png"); cvtColor(imgColorPanel0, imgColorPanel, CV_BGR2GRAY); 我尝试使用 CV_GRAY2BGRA 也会崩溃。 - ScriptyChris
请用Python解释一下。 - Shubh Patni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接