Setting up Matlab
- From a Matlab command window, run the command mex -setup. Follow the dialog and change the compiler to use the MSVSC++ compiler.
- Find mexopts.bat (see below for locating this file) and open for editing.
- Add set OPENCVDIR=C:\Program Files\OpenCV2.1.
- Add %OPENCVDIR%\include\opencv to the set INCLUDE statement.
- Add OPENCVDIR%\lib;%OPENCVDIR%\bin to the set LIB statement.
- Add cv210.lib highgui210.lib cvaux210.lib cxcore210.lib to the end of the set LINKFLAGS statement.
Setting up Visual Studio
Edit project properties as follows to allow compilation of MEX files.
- Add the following folders to the C/C++ additional include directories:
[MATLAB_DIR]\extern\include - [MATLAB_DIR]\simulink\include
- Add the following folder to the Linker additional directories:
- [MATLAB_DIR]\extern\lib\win32\microsoft
- Add the following Linker input additional dependencies (one per line):
- libmx.lib
- libmex.lib
- libmat.lib
- Add #include "mex.h" to your source code to allow the use and compilation of mx* functions.
Creating Files
- OpenCV File
- Assuming you already have a working project that uses OpenCV, modify the source file to contain only a set of functions you would like to call from a MEX file.
- MEX File
- The MEX file needs to be written. See MathWorks' online documentation for how to do this. I used an example from here.
- Include extern references to functions that you want to use from your OpenCV file.
- Use the functions in your MEX file.
- Compile the source that uses OpenCV to create an object file (e.g. opencv_file.obj)
- Run the following command in a Matlab command window (with correct paths to your files):
- mex mex_file.cpp opencv_file.obj
- Fix any errors to get this to compile.