Saturday, March 3, 2012

Mahalanobis Distance in OpenCV and Python

In this post we discuss about calculating Mahalanobis distance in OpenCV using C++.

Here we calculate Covariance Matrix, Inverse Covariance Matrix and Mahalanobis Distance using newer C++ API and comparing its results in Python (Numpy, Scipy).

Btw, My other programs in OpenCV will be posted here.

In OpenCV, its calculated as:

For covariance:
For inverse matrix:
For Mahalanobis Distance:
In Python you use:

I have been through this post and this post where they do covariance matrix in OpenCV using C++ but follow older API structure. I double checked this implementation with their code and Numpy.

There are lots of articles on the web claiming to get wrong results using the the OpenCV's API to calculate Covariance Matrix, etc. I also found similar errors but with the following code I got them fixed.

There is another variant of this function. But it looks more like C API.
Mahalanobis distance takes into account the co-variance in the variable data while calculating the distance between 2 points. This is a good example of Mahalanobis distance explanation and implementation in Matlab.

First in OpenCV:
The above implementation was checked in Numpy to see if the results were right or wrong (there are many posts in the web asking if the calccovar matrix function is buggy or request to change the calccovarmatrix function API ).

Now in Numpy:
The results match.

No comments:

Post a Comment