Change all white pixels of image to transparent in

2019-05-24 13:35发布

问题:

I have this image in OpenCV imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_COLOR);:

When I load it in with grey scale imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_GRAYSCALE); it looks like this:

However I want to remove the white background or make it transparent (only it's white pixels), to be looking like this:

How to do it in C++ OpenCV ?

回答1:

You can convert the input image to BGRA channel (color image with alpha channel) and then modify each pixel that is white to set the alpha value to zero.

See this code:

    // 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);

This will save your image with transparency. The result image opened with GIMP looks like:

As you can see, some "white regions" are not transparent, this means your those pixel weren't perfectly white in the input image. Instead you can try

    // 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)