1 | initial version |
to use the Mahalanobis distance, you need to build a global "model" first - the inverse covariance matrix of all your training samples. then, using that, you can compare a test sample to a train sample, to find out which is the best match in your database . so:
//// step 1, offline / once:
// put all your processed train samples into a single Mat,
// each feature flattened onto a row of its own
Mat features;
Mat _covar, _mean;
calcCovarMatrix(features, _covar, _mean, CV_COVAR_NORMAL|CV_COVAR_ROWS, CV_32F);
_covar /= (features.rows-1);
Mat icovar; // this is the one used later
invert(_covar, icovar, DECOMP_SVD);
//// step 2, predict on a test image
Mat testFeature;
for (all trainFeatures) {
Mat trainFeature = ...
double dist = Mahalanobis(testFeature, trainFeature, icovar);
}
so far, so good. however, be aware, that building a covariance matrix and even inverting it is extremely expensive, that's why most often some feature reduction like PCA is applied before.
2 | No.2 Revision |
to use the Mahalanobis distance, you need to build a global "model" first - the inverse covariance matrix of all your training samples. then, using that, you can compare a test sample to a train sample, to find out which is the best match in your database . so:
//// step 1, offline / once:
// put all your processed train samples into a single Mat,
// each feature flattened onto a row of its own
Mat features;
Mat _covar, _mean;
calcCovarMatrix(features, _covar, _mean, CV_COVAR_NORMAL|CV_COVAR_ROWS, CV_32F);
_covar /= (features.rows-1);
Mat icovar; // this is the one used later
invert(_covar, icovar, DECOMP_SVD);
//// step 2, predict on a test image
Mat testFeature;
for (all trainFeatures) {
Mat trainFeature = ...
double dist = Mahalanobis(testFeature, trainFeature, icovar);
}
so far, so good. however, be aware, that building a covariance matrix and even inverting it is extremely expensive, that's why most often some feature reduction like PCA is applied before.before (shorter features).