您可以将输入图像转换为带有alpha通道的BGRA通道(彩色图像),然后将每个白色像素的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中打开的结果图像看起来像:
正如您所见,一些“白色区域”不是透明的,这意味着您输入图像中这些像素并不完全是白色的。 您可以尝试使用
// 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)
cvtColor
使用 CV_GRAY2BGRA
也会导致崩溃。我在 GIMP 中检查了一下,白色背景仍然存在。我可能犯了什么错误? - ScriptyChrisMat imgColorPanel0,imgColorPanel; imgColorPanel0 = imread("transparentGUI.png"); cvtColor(imgColorPanel0, imgColorPanel, CV_BGR2GRAY);
我尝试使用 CV_GRAY2BGRA
也会崩溃。 - ScriptyChris