Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

convert white pixels to transparent

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