0

I write a simple app in OpenCV that delete black background of an image and save it with white background in JPG. However, it's always saved with black background.

This is my code:

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);
Miki
  • 40,887
  • 13
  • 123
  • 202
mahdi101
  • 87
  • 2
  • 5

1 Answers1

1

You can simply use setTo with a mask to set some pixels to a specific value according to a mask:

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

Also a few notes:

  1. You can directly load an image as grayscale using: imread(..., IMREAD_GRAYSCALE);

  2. You can avoid to use all those temporary Mats.

  3. Are you sure you want to use 0 as threshold value? Because in this case you can avoid entirely to apply theshold, and set to white all pixels that are 0 in the grayscale image: dst.setTo(Scalar(255,255,255), gray == 0);

This is how I'd do:

// 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);
Miki
  • 40,887
  • 13
  • 123
  • 202