Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

enter image description here

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

enter image description here

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 ?

enter image description here

like image 554
Chris92 Avatar asked Mar 25 '16 18:03

Chris92


1 Answers

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:

enter image description here

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)
like image 165
Micka Avatar answered Sep 18 '22 03:09

Micka