mexopencv  0.1
mex interface for opencv library
kmeans.cpp
Go to the documentation of this file.
1 
8 #include "mexopencv.hpp"
9 using namespace std;
10 using namespace cv;
11 
12 namespace {
14 const ConstMap<string,int> Initialization = ConstMap<string,int>
15  ("Random", cv::KMEANS_RANDOM_CENTERS)
16  ("PP", cv::KMEANS_PP_CENTERS);
17 }
18 
26 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
27 {
28  // Check the number of arguments
29  nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=3);
30 
31  // Argument vector
32  vector<MxArray> rhs(prhs, prhs+nrhs);
33 
34  // Option processing
35  Mat bestLabels;
36  TermCriteria criteria;
37  int attempts = 10;
38  int flags = cv::KMEANS_RANDOM_CENTERS;
39  for (int i=2; i<nrhs; i+=2) {
40  string key(rhs[i].toString());
41  if (key=="InitialLabels") {
42  bestLabels = rhs[i+1].toMat(CV_32S);
43  flags |= cv::KMEANS_USE_INITIAL_LABELS;
44  }
45  else if (key=="Criteria")
46  criteria = rhs[i+1].toTermCriteria();
47  else if (key=="Attempts")
48  attempts = rhs[i+1].toInt();
49  else if (key=="Initialization")
50  flags = Initialization[rhs[i+1].toString()];
51  else
52  mexErrMsgIdAndTxt("mexopencv:error",
53  "Unrecognized option %s", key.c_str());
54  }
55 
56  // Process
57  Mat data(rhs[0].toMat(CV_32F)), centers;
58  int K = rhs[1].toInt();
59  double compactness = kmeans(data, K, bestLabels, criteria, attempts,
60  flags, (nlhs>1 ? centers : noArray()));
61  plhs[0] = MxArray(bestLabels);
62  if (nlhs>1)
63  plhs[1] = MxArray(centers);
64  if (nlhs>2)
65  plhs[2] = MxArray(compactness);
66 }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Main entry called from Matlab.
Definition: kmeans.cpp:26
mxArray object wrapper for data conversion and manipulation.
Definition: MxArray.hpp:123
void nargchk(bool cond)
Alias for input/ouput arguments number check.
Definition: mexopencv.hpp:166
Global constant definitions.
std::map wrapper with one-line initialization and lookup method.
Definition: MxArray.hpp:927