Search code examples
opencvbackgroundforeground

Extracting transparent background of an image with opencv


I have got a mask calculated in grab_cut(which calculates the foreground). I want to extract only the background leaving the foreground transparent. I manage to do so using the following code in order to extract foreground(background transparent). How is it possible to do the opposite?

int border = 20;
int border2 = border + border;
cv::Rect rectangle(border,border,image.cols-border2,image.rows-border2);

cv::Mat result; // segmentation result (4 possible values)
cv::Mat bgModel,fgModel; /
cv::grabCut(image,    // input image
    result,   // segmentation result
    rectangle,// rectangle containing foreground 
    bgModel,fgModel, // models
    1,        // number of iterations
    cv::GC_INIT_WITH_RECT); // use rectangle
cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255));
image.copyTo(foreground,result); // bg pixels not copied
cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1);
cv::imwrite(argv[2], foreground);
cv::imwrite(argv[3], image);

Mat dst;//(src.rows,src.cols,CV_8UC4);
Mat tmp,alpha;

cvtColor(foreground,tmp,CV_BGR2GRAY);
threshold(tmp,alpha,100,255,THRESH_BINARY);
Mat rgb[3];
split(foreground,rgb);
Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
merge(rgba,4,dst);
imwrite("dst.png",dst);

Basically i think I ve got to change those lines:

cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255));
image.copyTo(foreground,result); // bg pixels not copied

How is is possible to select the rest of the image the opposite of result?


Solution

  • Just invert your mask as in:

    cv::Mat background(image.size(),CV_8UC3,cv::Scalar(255,255,255));
    image.copyTo(background, ~result); // fg pixels not copied