OpenCV and Matlab

I’m experimenting with using OpenCV and Matlab and have come across a problem. Matlab (at least on my Mac) loads its own versions of libraries preferentially. This isn’t normally a problem but if your mex code links against a different version you might get a library conflict. One that I have come across several times is Matlab uses an old version of libtiff (it’s used in imread, imwrite etc) and OpenCV uses a newer version. So when I run an OpenCV mex file, Matlab attempts to load the old version for my OpenCV and the mex file crashes.

My first attempt to solve this was to update the Matlabs version of libtiff – it partially worked. My libraries were fine but it broke imread so it wasn’t acceptable. The solution I found when trying the mexopencv wrapper is to preload the up to date libraries when starting Matlab. The command was

DYLD_INSERT_LIBRARIES=/opt/local/lib/libtiff.5.dylib /Applications/Matlab/MATLAB_R2012b.app/bin/matlab &