Chr*_*s92 2 c++ opencv image transparent pixels
我在OpenCV中有这个图像imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_COLOR);:
当我用灰度加载它时,imgColorPanel = imread("newGUI.png", CV_LOAD_IMAGE_GRAYSCALE);它看起来像这样:
但是,我想删除白色背景或使其透明(只有它的白色像素),看起来像这样:
如何在C++ OpenCV中做到这一点?
Mic*_*cka 11
您可以将输入图像转换为BGRA通道(带有Alpha通道的彩色图像),然后修改每个白色像素以将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);
Run Code Online (Sandbox Code Playgroud)
这将保存您的图像透明度.使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11362 次 |
| 最近记录: |