mexopencv  3.4.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 {
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);
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 }
KMEANS_USE_INITIAL_LABELS
double kmeans(InputArray data, int K, InputOutputArray bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray())
KMEANS_PP_CENTERS
const ConstMap< string, int > Initialization
KMeans initalization types for option processing.
Definition: kmeans.cpp:14
STL namespace.
KMEANS_RANDOM_CENTERS
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Main entry called from Matlab.
Definition: kmeans.cpp:26
struct mxArray_tag mxArray
Forward declaration for mxArray.
Definition: matrix.h:259
#define CV_32F
InputOutputArray noArray()
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
STL class.
#define CV_32S
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