Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

What are your inner and outer-rectangles? One is your foreground and the other your background? What do you not understand from the docu (http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=grabcut#grabcut) ?

There exist also an example: <your-opencv-folder>/samples/cpp/grabcut.cpp

Maybe another example helps, in which I assumed that the middle-portion of the image is definitely foreground and the first 5 rows of the image are definitely background:

cv::Mat1b markers(img.rows, img.cols);
// let's set all of them to possible background first
markers.setTo(cv::GC_PR_BGD);

// cut out a small area in the middle of the image
int m_rows = 0.1 * img.rows;
int m_cols = 0.1 * img.cols;
// of course here you could also use cv::Rect() instead of cv::Range to select 
// the region of interest
cv::Mat1b fg_seed = markers(cv::Range(img.rows/2 - m_rows/2, img.rows/2 + m_rows/2), 
                            cv::Range(img.cols/2 - m_cols/2, img.cols/2 + m_cols/2));
// mark it as foreground
fg_seed.setTo(cv::GC_FGD);

// select first 5 rows of the image as background
cv::Mat1b bg_seed = markers(cv::Range(0, 5),cv::Range::all());
bg_seed.setTo(cv::GC_BGD);

cv::Mat bgd, fgd;
int iterations = 1;
cv::grabCut(img, markers, cv::Rect(), bgd, fgd, iterations, cv::GC_INIT_WITH_MASK);

// let's get all foreground and possible foreground pixels
cv::Mat1b mask_fgpf = ( markers == cv::GC_FGD) | ( markers == cv::GC_PR_FGD);
// and copy all the foreground-pixels to a temporary image
cv::Mat3b tmp = cv::Mat3b::zeros(img.rows, img.cols);
img.copyTo(tmp, mask_fgpf);
// show it
cv::imshow("foreground", tmp);
cv::waitKey(0);

Please forgive me any errors in the code, I just wrote it from scratch.