无法将图像保存在具有白色背景的JPG中 OpenCV



我在OpenCV中编写了一个简单的应用程序,可以删除图像的黑色背景并将其保存在JPG中。但是,它始终以黑色背景保存。

这是我的代码:

Mat Imgsrc = imread("../temp/temp1.jpg",1) ;
mat dest;
Mat temp, thr;
cvtColor(Imgsrc, temp, COLOR_BGR2GRAY);
threshold(temp,thr, 0, 255, THRESH_BINARY);
Mat rgb[3];
split(Imgsrc,rgb);
Mat rgba[4] = { rgb[0],rgb[1],rgb[2],thr };
merge(rgba,4,dest);
imwrite("../temp/r5.jpg", dest);

您可以简单地将setTo与蒙版一起使用,根据蒙版将某些像素设置为特定值:

Mat src = imread("../temp/temp1.jpg",1) ;
Mat dst;
Mat gray, thr;
cvtColor(src, gray, COLOR_BGR2GRAY);
// Are you sure to use 0 as threshold value?
threshold(gray, thr, 0, 255, THRESH_BINARY);
// Clone src into dst
dst = src.clone();
// Set to white all pixels that are not zero in the mask
dst.setTo(Scalar(255,255,255) /*white*/, thr);
imwrite("../temp/r5.jpg", dst);

还有几点注意事项:

  1. 您可以使用以下方法直接将图像加载为灰度: imread(..., IMREAD_GRAYSCALE);

  2. 您可以避免使用所有这些临时Mat

  3. 是否确实要将0用作阈值?因为在这种情况下,您可以完全避免应用theshold,并将灰度图像中所有为0的像素设置为白色:dst.setTo(Scalar(255,255,255), gray == 0) ;

这就是我会做的:

// Load the image 
Mat src = imread("path/to/img", IMREAD_COLOR);
// Convert to grayscale
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY); 
// Set to white all pixels that are 0 in the grayscale image
src.setTo(Scalar(255,255,255), gray == 0)
// Save
imwrite("path/to/other/img", src);

最新更新