mexopencv  0.1
mex interface for opencv library
imdecode.cpp
Go to the documentation of this file.
1 
8 #include "mexopencv.hpp"
9 using namespace std;
10 using namespace cv;
11 
19 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
20 {
21  // Check the number of arguments
22  nargchk(nrhs>=1 && (nrhs%2)==1 && nlhs<=1);
23 
24  // Argument vector
25  vector<MxArray> rhs(prhs, prhs+nrhs);
26 
27  // Option processing
28  bool unchanged = false,
29  anydepth = false,
30  anycolor = false,
31  color = true;
32  int flags = 0;
33  bool override = false;
34  bool flip = true;
35  for (int i=1; i<nrhs; i+=2) {
36  string key(rhs[i].toString());
37  if (key == "Flags") {
38  flags = rhs[i+1].toInt();
39  override = true;
40  }
41  else if (key == "Unchanged")
42  unchanged = rhs[i+1].toBool();
43  else if (key == "AnyDepth")
44  anydepth = rhs[i+1].toBool();
45  else if (key == "AnyColor")
46  anycolor = rhs[i+1].toBool();
47  else if (key == "Grayscale") {
48  color = !rhs[i+1].toBool();
49  anycolor = false;
50  }
51  else if (key == "Color") {
52  color = rhs[i+1].toBool();
53  anycolor = false;
54  }
55  else if (key == "FlipChannels")
56  flip = rhs[i+1].toBool();
57  else
58  mexErrMsgIdAndTxt("mexopencv:error",
59  "Unrecognized option %s", key.c_str());
60  }
61 
62  // build flag value from options
63  if (!override) {
64  if (unchanged) {
65  // depth and cn as is (as determined by decoder).
66  // This is the only way to load alpha channel if present
67  flags = cv::IMREAD_UNCHANGED;
68  }
69  else {
70  // depth as is, otherwise CV_8U
71  flags |= (anydepth ? cv::IMREAD_ANYDEPTH : 0);
72  // channels as is (if gray then cn=1, else cn=3 [BGR])
73  flags |= (anycolor ? cv::IMREAD_ANYCOLOR :
74  // otherwise explicitly either cn = 3 or cn = 1
75  (color ? cv::IMREAD_COLOR : cv::IMREAD_GRAYSCALE));
76  }
77  }
78 
79  // Process
80  Mat buf(rhs[0].toMat(CV_8U));
81  Mat img = imdecode(buf, flags);
82  if (img.data == NULL)
83  mexErrMsgIdAndTxt("mexopencv:error", "imdecode failed");
84  if (flip && (img.channels() == 3 || img.channels() == 4)) {
85  // OpenCV's default is BGR/BGRA while MATLAB's is RGB/RGBA
86  cvtColor(img, img, (img.channels()==3 ?
87  cv::COLOR_BGR2RGB : cv::COLOR_BGRA2RGBA));
88  }
89  plhs[0] = MxArray(img);
90 }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Main entry called from Matlab.
Definition: imdecode.cpp:19
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.