mexopencv  0.1
mex interface for opencv library
solvePnP.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  ("Iterative", cv::SOLVEPNP_ITERATIVE)
16  ("EPnP", cv::SOLVEPNP_EPNP)
17  ("P3P", cv::SOLVEPNP_P3P)
18  ("DLS", cv::SOLVEPNP_DLS)
19  ("UPnP", cv::SOLVEPNP_UPNP);
20 }
21 
29 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
30 {
31  // Check the number of arguments
32  nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=3);
33 
34  // Argument vector
35  vector<MxArray> rhs(prhs, prhs+nrhs);
36 
37  // Option processing
38  Mat distCoeffs;
39  Mat rvec, tvec;
40  bool useExtrinsicGuess = false;
41  int flags = cv::SOLVEPNP_ITERATIVE;
42  for (int i=3; i<nrhs; i+=2) {
43  string key(rhs[i].toString());
44  if (key=="DistCoeffs")
45  distCoeffs = rhs[i+1].toMat(CV_64F);
46  else if (key=="UseExtrinsicGuess")
47  useExtrinsicGuess = rhs[i+1].toBool();
48  else if (key=="Rvec")
49  rvec = rhs[i+1].toMat(CV_64F);
50  else if (key=="Tvec")
51  tvec = rhs[i+1].toMat(CV_64F);
52  else if (key=="Method")
53  flags = PnPMethod[rhs[i+1].toString()];
54  else
55  mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option");
56  }
57  if (!rvec.empty() && !tvec.empty() && flags == cv::SOLVEPNP_ITERATIVE)
58  useExtrinsicGuess = true;
59 
60  // Process
61  bool success = false;
62  Mat cameraMatrix(rhs[2].toMat(CV_64F));
63  if (rhs[0].isNumeric() && rhs[1].isNumeric()) {
64  Mat objectPoints(rhs[0].toMat(CV_64F).reshape(3,0)),
65  imagePoints(rhs[1].toMat(CV_64F).reshape(2,0));
66  success = solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs,
67  rvec, tvec, useExtrinsicGuess, flags);
68  }
69  else if (rhs[0].isCell() && rhs[1].isCell()) {
70  vector<Point3d> objectPoints(rhs[0].toVector<Point3d>());
71  vector<Point2d> imagePoints(rhs[1].toVector<Point2d>());
72  success = solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs,
73  rvec, tvec, useExtrinsicGuess, flags);
74  }
75  else
76  mexErrMsgIdAndTxt("mexopencv:error","Invalid argument");
77  plhs[0] = MxArray(rvec);
78  if (nlhs>1)
79  plhs[1] = MxArray(tvec);
80  if (nlhs>2)
81  plhs[2] = MxArray(success);
82 }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Main entry called from Matlab.
Definition: solvePnP.cpp:29
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