Tuesday, March 10, 2009

OpenCV SURF naiveNearestNeighbor

https://opencvlibrary.svn.sourceforge.net/svnroot/opencvlibrary/trunk/opencv/samples/c/find_obj.cpp

This code finds the two nearest neighbors, but only returns the very
nearest if it is distinctly better than the second nearest:

int
naiveNearestNeighbor( const float* vec, int laplacian,
const CvSeq* model_keypoints,
const CvSeq* model_descriptors )
{
int length = (int)(model_descriptors->elem_size/sizeof(float));
int i, neighbor = -1;
double d, dist1 = 1e6, dist2 = 1e6;
CvSeqReader reader, kreader;
cvStartReadSeq( model_keypoints, &kreader, 0 );
cvStartReadSeq( model_descriptors, &reader, 0 );

for( i = 0; i < model_descriptors->total; i++ )
{
const CvSURFPoint* kp = (const CvSURFPoint*)kreader.ptr;
const float* mvec = (const float*)reader.ptr;
CV_NEXT_SEQ_ELEM( kreader.seq->elem_size, kreader );
CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
if( laplacian != kp->laplacian )
continue;
/// in compareSURFdescriptors, the third parameter is said to be the
/// 'best' distance, but it is really the second best here
d = compareSURFDescriptors( vec, mvec, dist2, length );

if( d < dist1 )
{
dist2 = dist1;
dist1 = d;
neighbor = i;
}
/// if dist1 < d <dist2
else if ( d < dist2 )
dist2 = d;
}
/// the two best can't be close to each other
if ( dist1 < 0.6*dist2 )
return neighbor;
return -1;
}

No comments:

Post a Comment