mexopencv  3.4.1
MEX interface for OpenCV library
grabCut.cpp
Go to the documentation of this file.
1 
8 #include "mexopencv.hpp"
9 #include "opencv2/imgproc.hpp"
10 using namespace std;
11 using namespace cv;
12 
13 namespace {
16  ("InitWithRect", cv::GC_INIT_WITH_RECT)
17  ("InitWithMask", cv::GC_INIT_WITH_MASK)
18  ("Eval", cv::GC_EVAL);
19 }
20 
28 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
29 {
30  // Check the number of arguments
31  nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=3);
32 
33  // Argument vector
34  vector<MxArray> rhs(prhs, prhs+nrhs);
35  bool rect_variant = (rhs[1].numel() == 4 &&
36  (rhs[1].rows()==1 || rhs[1].cols()==1));
37 
38  // Option processing
39  Mat bgdModel, fgdModel;
40  int iterCount = 10;
41  int mode = cv::GC_EVAL;
42  for (int i=2; i<nrhs; i+=2) {
43  string key(rhs[i].toString());
44  if (key == "BgdModel")
45  bgdModel = rhs[i+1].toMat(CV_64F);
46  else if (key == "FgdModel")
47  fgdModel = rhs[i+1].toMat(CV_64F);
48  else if (key == "IterCount")
49  iterCount = rhs[i+1].toInt();
50  else if (key == "Mode")
51  mode = GrabCutType[rhs[i+1].toString()];
52  else
53  mexErrMsgIdAndTxt("mexopencv:error",
54  "Unrecognized option %s", key.c_str());
55  }
56 
57  // Initialize mask and rect
58  Mat mask;
59  Rect rect;
60  if (rect_variant) {
61  rect = rhs[1].toRect();
62  mode = cv::GC_INIT_WITH_RECT;
63  }
64  else
65  mask = rhs[1].toMat(CV_8U);
66 
67  // Process
68  Mat img(rhs[0].toMat(CV_8U));
69  grabCut(img, mask, rect, bgdModel, fgdModel, iterCount, mode);
70  plhs[0] = MxArray(mask);
71  if (nlhs > 1)
72  plhs[1] = MxArray(bgdModel);
73  if (nlhs > 2)
74  plhs[2] = MxArray(fgdModel);
75 }
const ConstMap< string, int > GrabCutType
GrabCut algorithm types for option processing.
Definition: grabCut.cpp:15
#define CV_8U
GC_INIT_WITH_RECT
STL namespace.
struct mxArray_tag mxArray
Forward declaration for mxArray.
Definition: matrix.h:259
void grabCut(InputArray img, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode=GC_EVAL)
#define CV_64F
LIBMWMEX_API_EXTERN_C void mexErrMsgIdAndTxt(const char *identifier, const char *err_msg,...)
Issue formatted error message with corresponding error identifier and return to MATLAB prompt...
mxArray object wrapper for data conversion and manipulation.
Definition: MxArray.hpp:123
void nargchk(bool cond)
Alias for input/output arguments number check.
Definition: mexopencv.hpp:181
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Main entry called from Matlab.
Definition: grabCut.cpp:28
GC_INIT_WITH_MASK
STL class.
Global constant definitions.
T c_str(T... args)
std::map wrapper with one-line initialization and lookup method.
Definition: MxArray.hpp:927
cv::Mat toMat() const