Wednesday, March 7, 2012

Reading Configuration Files in C++

This is a quick code snippet to read a user defined configuration files in C++. I use boost libraries.

There many ways to read it(depends on how you have your configuration file written). You can also use  boost::property_tree which can efficiently parse formats such as XML, INI, etc.

Make sure you've installed boost before trying this out.

For a text file with data in the following format(data in each line separated by tab spaces and new unit of data in each line):

The returned data is in form of vector of vectors. You can replace above configuration file with similar structure (and replace tabs with any common delimiter and it will work).

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.