OpenCV Matlab Code Generator
============================
This module contains a code generator to automatically produce Matlab mex wrappers for other modules within the OpenCV library. Once compiled and added to the Matlab path, this gives users the ability to call OpenCV methods natively from within Matlab.
Build
-----
The Matlab code generator is fully integrated into the OpenCV build system. If cmake finds a Matlab installation available on the host system while configuring OpenCV, it will attempt to generate Matlab wrappers for all OpenCV modules. If cmake is having trouble finding your Matlab installation, you can explicitly point it to the root by defining the `MATLAB_ROOT_DIR` variable. For example, on a Mac you could type:
cmake -DMATLAB_ROOT_DIR=/Applications/MATLAB_R2013a.app ..
If you prefer using the gui version of cmake (cmake-gui), you can use the *Add Entry* option in the GUI to manually add the *path* variable `MATLAB_ROOT_DIR`.
Install
-------
In order to use the bindings, you will need to add them to the Matlab path. The path to add is:
1. `${CMAKE_BUILD_DIR}/modules/matlab` if you are working from the build tree, or
2. `${CMAKE_INSTALL_PREFIX}/matlab` if you have installed OpenCV
In Matlab, simply run:
addpath('/path/to/opencv/matlab/');
Run
---
Once you've added the bindings directory to the Matlab path, you can start using them straight away! OpenCV calls need to be prefixed with a 'cv' qualifier, to disambiguate them from Matlab methods of the same name. For example, to compute the dft of a matrix, you might do the following:
```matlab
% load an image (Matlab)
I = imread('cameraman.tif');
% compute the DFT (OpenCV)
If = cv.dft(I, cv.DFT_COMPLEX_OUTPUT);
```
As you can see, both OpenCV methods and constants can be used with 'cv' qualification. You can also call:
help cv.dft
to get help on the purpose and call signature of a particular method, or
help cv
to get general help regarding the OpenCV bindings. If you ever run into issues with the bindings
cv.buildInformation();
will produce a printout of diagnostic information pertaining to your particular build of OS, OpenCV and Matlab. It is useful to submit this information alongside a bug report to the OpenCV team.
Writing your own mex files
--------------------------
The Matlab bindings come with a set of utilities to help you quickly write your own mex files using OpenCV definitions. By doing so, you have all the speed and freedom of C++, with the power of OpenCV's math expressions and optimizations.
The first thing you need to learn how to do is write a mex-file with Matlab constructs. Following is a brief example:
```cpp
// include useful constructs
// this automatically includes opencv core.hpp and mex.h)
#include <opencv2/matlab/bridge.hpp>
using namespace cv;
using namespace matlab;
using namespace bridge;
// define the mex gateway
void mexFunction(int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[]) {
// claim the inputs into scoped management
MxArrayVector raw(prhs, prhs+nrhs);
// add an argument parser to automatically handle basic options
ArgumentParser parser("my function");
parser.addVariant("variant1", 1, 1, "opt");
MxArrayVector reordered = parser.parse(raw);
// if we get here, we know the inputs are valid and reordered. Unpack...
BridgeVector inputs(reordered.begin(), reordered.end());
Mat required = inputs[0].toMat();
string optional = inputs[1].empty() ? "Default string" : inputs[1].toString();
try {
// Do stuff...
} catch(Exception& e) {
error(e.what());
} catch(...) {
error("Uncaught exception occurred");
}
// allocate an output
Bridge out;
out = required;
plhs[0] = out.toMxArray().releaseOwnership();
}
```
There are a couple of important things going on in this example. Firstly, you need to include `<opencv2/matlab/bridge.hpp>` to enable the bridging capabilities. Once you've done this, you get some nice utilities for free. `MxArray` is a class that wraps Matlab's `mxArray*` class in an OOP-style interface. `ArgumentParser` is a class that handles default, optional and named arguments for you, along with multiple possible calling syntaxes. Finally, `Bridge` is a class that allows bidirectional conversions between OpenCV/std and Matlab types.
Once you have written your file, it can be compiled with the provided mex utility:
cv.mex('my_function.cpp');
This utility automatically links in all of the necessary OpenCV libraries to make your function work.
NOTE: OpenCV uses exceptions throughout the codebase. It is a **very** good idea to wrap your code in exception handlers to avoid crashing Matlab in the event of an exception being thrown.
------------------------------------------------------------------
Developer
=========
The following sections contain information for developers seeking to use, understand or extend the Matlab bindings. The bindings are generated in python using a powerful templating engine called Jinja2. Because Matlab mex gateways have a common structure, they are well suited to templatization. There are separate templates for formatting C++ classes, Matlab classes, C++ functions, constants (enums) and documentation.
The task of the generator is two-fold:
1. To parse the OpenCV headers and build a semantic tree that can be fed to the template engine
2. To define type conversions between C++/OpenCV and Matlab types
Once a source file has been generated for each OpenCV definition, and type conversions have been established, the mex compiler is invoked to produce the mex gateway (shared object) and link in the OpenCV libraries.
File layout
-----------
opencv/modules/matlab (this module)
* `CMakeLists.txt` (main cmake configuration file)
* `README.md` (this file)
* `compile.cmake` (the cmake script for compiling generated source code)
* `generator` (the folder containing generator code)
* `filters.py` (template filters)
* `gen_matlab.py` (the binding generator control script)
* `parse_tree.py` (python class to refactor the hdr_parser.py output)
* `templates` (the raw templates for populating classes, constants, functions and docs)
* `include` (C++ headers for the bindings)
* `mxarray.hpp` (C++ OOP-style interface for Matlab mxArray* class)
* `bridge.hpp` (type conversions)
* `map.hpp` (hash map interface for instance storage and method lookup)
* `test` (generator, compiler and binding test scripts)
Call Tree
---------
The cmake call tree can be broken into 3 main components:
1. configure time
2. build time
3. install time
**Find Matlab (configure)**
The first thing to do is discover a Matlab installation on the host system. This is handled by the `OpenCVFindMatlab.cmake` in `opencv/cmake`. On Windows machines it searches the registry and path, while on *NIX machines it searches a set of canonical install paths. Once Matlab has been found, a number of variables are defined, such as the path to the mex compiler, the mex libraries, the mex include paths, the architectural extension, etc.
**Test the generator (configure)**
Attempt to produce a source file for a simple definition. This tests whether python and pythonlibs are correctly invoked on the host.
**Test the mex compiler (configure)**
Attempt to compile a simple definition using the mex compiler. A mex file is actually just a shared object with a special exported symbol `_mexFunction` which serves as the entry-point to the function. As such, the mex compiler is just a set of scripts configuring the system compiler. In most cases this is the same as the OpenCV compiler, but *could* be different. The test checks whether the mex and generator includes can be found, the system libraries can be linked and the passed compiler flags are compatible.
If any of the configure time tests fail, the bindings will be disabled, but the main OpenCV configure will continue without error. The configuration summary will contain the block:
Matlab
me
评论0