在OpenCV的源码目录的samples的文件夹下,有grabCut的使用例程,请参考:
opencv\samples\cpp\grabcut.cpp。
在这里给出最简单的调用grabcut
#include <cv.h> #include <highgui.h> #pragma comment(lib,"cv210d.lib") #pragma comment(lib,"cxcore210d.lib") #pragma comment(lib,"highgui210d.lib") #include <iostream> using namespace std; using namespace cv; void MyShowImage(Mat Image,const string winName) { imshow( winName, Image ); } void getBinMask( const Mat& comMask, Mat& binMask ) { binMask.create( comMask.size(), CV_8UC1 ); binMask = comMask & 1; } int main( int argc, char** argv ) { Mat image = imread( "lena.jpg", 1 ); const string winName = "image"; MyShowImage(image,winName); /***********************************/ Mat bg;Mat fg; Rect rect = Rect(47,48,408,464); Mat mask,res; mask.create( image.size(), CV_8UC1); grabCut( image, mask, rect, bg, fg, 1, 0 ); Mat binMask; getBinMask( mask, binMask ); image.copyTo( res, binMask ); MyShowImage(res,winName); /***********************************/ cvWaitKey(0); return 0; }
运行结果: