Skip to content
This repository has been archived by the owner on Jan 25, 2022. It is now read-only.

Getting Started

Amro edited this page Mar 14, 2017 · 5 revisions

Getting started

Here is an example of how simple it is to use an OpenCV function from MATLAB to detect faces:

% Load a face detector and an image
cascade = cv.CascadeClassifier('haarcascade_frontalface_alt.xml');
im = imread('myface.jpg');

% Preprocess image
gr = cv.cvtColor(im, 'RGB2GRAY');
gr = cv.equalizeHist(gr);

% Detect faces
boxes = cascade.detect(gr, ...
    'ScaleFactor',1.3, 'MinNeighbors',2, 'MinSize',[30 30]);

% Draw results
for i = 1:numel(boxes)
    im = cv.rectangle(im, boxes{i}, 'Color',[0 255 0], 'Thickness',2);
end
imshow(im);

Would you like to use a camera input? No problem.

% Connect to a camera
camera = cv.VideoCapture();
pause(2);
for i = 1:50
    % Capture and show frame
    frame = camera.read();
    imshow(frame);
    pause(0.3);
end

Check out the included samples for more demos (here and here).


The package already contains over 400 OpenCV functions/classes (covering many opencv and opencv_contrib modules). You can check a list of supported functions in the user documentation.

If you can't find your favorite one, you can easily add a new MEX function through MxArray class. MxArray is a data conversion utility for MATLAB's native array and OpenCV data types.

With this class, your MEX-function is as simple as the following:

#include "mexopencv.hpp"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check arguments
    nargchk(nrhs==2 && nlhs<=1);

    // Convert MxArray to cv::Mat and cv::Size
    cv::Mat src(MxArray(prhs[0]).toMat()), dst;
    cv::Size ksize(MxArray(prhs[1]).toSize());

    // Use your favorite OpenCV function
    cv::blur(src, dst, ksize);

    // Convert cv::Mat back to mxArray*
    plhs[0] = MxArray(dst);
}

Check the developer documentation for further details.