convert white pixels to transparent

asked 2017-04-12 14:46:37 -0600

pablobhz gravatar image

I'm trying to convert the white pixels on a image to transparent, ussing the following 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:/inputfolder/Output/transparentWhite.png", input_bgra);

However, when i open the image, white pixels are still white (not transparent).

WHat am i doing wrong ? Thx

edit retag flag offensive close merge delete

Comments

1

imho, you got the wrong lib for this. "transparency" mightbe a thing for web devs, but it has no role at all in computer-vision. (and imshow() will just discard any alpha information)

berak gravatar imageberak ( 2017-04-12 19:10:45 -0600 )edit

Btw are there actually values in your alpha channel to begin with? If not you will have to manually set all other pixels to 255 or start with a filled/initialized matrix.

StevenPuttemans gravatar imageStevenPuttemans ( 2017-04-14 07:20:36 -0600 )edit