gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:35:30 25 4
gpt4 key购买 nike

我在 OpenCV 中有这张图片 imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_COLOR);:

enter image description here

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

enter image description here

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

如何在 C++ OpenCV 中实现?

enter image description here

最佳答案

您可以将输入图像转换为 BGRA channel (带 alpha channel 的彩色图像),然后修改每个白色像素以将 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 打开的结果图像如下所示:

enter image description here

如您所见,一些“白色区域”不是透明的,这意味着您的那些像素在输入图像中不是完全白色的。相反,您可以尝试

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

关于c++ - 在 OpenCV C++ 中将图像的所有白色像素更改为透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36225420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com