title: Extracting Background Image Using GrabCut
body: <p>I've an image (.jpg image), and I want to extract the background from the original image. I've googled a lot but have only found tutorials of extracting foreground image. </p>
  
  <p>I've taken the code from another <a href="https://stackoverflow.com/questions/15536222/opencv-grabcut-algorithm-example-not-working">stackoverflow question</a>. The code is working fine for me, and I've successfully extracted the foreground (as per my requirements). Now I want to completely remove this foreground from the original image. I want it to be something like this:-</p>
  
  <p>Background = Original Image - Foreground</p>
  
  <p>The empty space can be filled with black or white color. How can I achieve this? </p>
  
  <p>I've tried using this technique:-</p>
  
  <pre><code>Mat background = image2 - foreground;
  </code></pre>
  
  <p>but it gives a complete black image.</p>
  
  <p>Code:-</p>
  
  <pre><code>#include &lt;opencv2/opencv.hpp&gt;
  #include &lt;iostream&gt;
  
  using namespace cv;
  using namespace std;
  
  int main( )
  {
  // Open another image
  Mat image;
  image= cv::imread("images/abc.jpg");
  
  Mat image2 = image.clone();
  
  // define bounding rectangle
  cv::Rect rectangle(40,90,image.cols-80,image.rows-170);
  
  cv::Mat result; // segmentation result (4 possible values)
  cv::Mat bgModel,fgModel; // the models (internally used)
  
  // GrabCut segmentation
  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
  cout &lt;&lt; "oks pa dito" &lt;&lt;endl;
  // Get the pixels marked as likely foreground
  cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
  // Generate output image
  cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255));
  //cv::Mat background(image.size(),CV_8UC3,cv::Scalar(255,255,255));
  image.copyTo(foreground,result); // bg pixels not copied
  
  // draw rectangle on original image
  cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1);
  
  imwrite("img_1.jpg",image);
  
  imwrite("Foreground.jpg",foreground);
  Mat background = image2 - foreground;
  imwrite("Background.jpg",background);
  
  return 0;
  }
  </code></pre>
  
  <p>Note: I'm an opencv beginner and don't have much knowledge of it right now. I shall be very thankful to you if you can either post the complete code (as required by me) or just post the lines of code and tell me where these lines of code be placed. Thanks.</p>
  
  <p>P.S. This is my second question at StackOverflow.com. apologies ... if not following any convention.</p>