繁体   English   中英

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

[英]Change all white pixels of image to transparent in OpenCV C++

我在OpenCV中有这个图像imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_COLOR);

在此输入图像描述

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

在此输入图像描述

但是,我想删除白色背景或使其透明(只有它的白色像素),看起来像这样:

如何在C ++ OpenCV中实现?

在此输入图像描述

您可以将输入图像转换为BGRA通道(带有Alpha通道的彩色图像),然后修改每个白色像素以将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)

暂无
暂无

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

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