posha
posha

Reputation: 901

What happens in GrabCut Algorithm

I want to know the what actually happnens in the following code.

cv::Rect rectangle(x,y,width,height);

    cv::Mat result; 
    cv::Mat bgModel,fgModel;


    cv::grabCut(image,  
                    result,  
                    rectangle,
                    bgModel,fgModel, 
                    1,       
                    cv::GC_INIT_WITH_RECT);


    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));
    image.copyTo(foreground,result); 

According to my knowledge when we define the rectangle outside the rectangle will be consider as the known background and the inside as the unknown foreground.

Then bgmodel and fgmodel are Gausian mixed models which keeps the foreground and background pixels separately.

The parameter we are passing as 1 means, we are asking to divide the pixels to separate pixels process to run only once.

what i can't understand is

cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);

What actually happens in the above method.

If anyone could explain, that would be a great help. thanx.

Upvotes: 1

Views: 1115

Answers (1)

polkovnikov.ph
polkovnikov.ph

Reputation: 6632

I've found this book which tells that this code compares values of pixels in result to GC_PR_FGD value. Those that are equal it doesn't touch, all the other pixels it deletes. Here's a citation from there:

The input/output segmentation image can have one of the four values:

  • cv::GC_BGD, for pixels certainly belonging to the background (for example, pixels outside the rectangle in our example)
  • cv::GC_FGD, for pixels certainly belonging to the foreground (none in our example)
  • cv::GC_PR_BGD, for pixels probably belonging to the background
  • cv::GC_PR_FGD for pixels probably belonging to the foreground (that is the initial value for the pixels inside the rectangle in our example).

We get a binary image of the segmentation by extracting the pixels having a value equal to cv::GC_PR_FGD:

// 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));
image.copyTo(foreground, // bg pixels are not copied
          result);

Upvotes: 2

Related Questions