2017年6月2日 星期五

simple opencv 2411 flann point match example practice

flann function in opencv is good for point match, which find nearest point from A points to B points, it is useful for tracking, iterative closest point (ICP) algorithm...

I copy the code from this website:

https://github.com/royshil/morethantechnical/blob/master/ICP/MyICP.cpp

and make it simple for me to understand.

code:

#include "cv.h"
#include "highgui.h"
#include <iostream>
#include <vector>
#include <limits>
using namespace cv;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 Mat X(5,2,CV_32SC1); 
 X.at<Point>(0,0)=Point(1,1);
 X.at<Point>(1,0)=Point(5,5);
 X.at<Point>(2,0)=Point(10,10);
 X.at<Point>(3,0)=Point(15,15);
 X.at<Point>(4,0)=Point(20,20);
 Mat destinations(10,2,X.type());
 destinations.at<Point>(0,0)=Point(30,30);
 destinations.at<Point>(1,0)=Point(6,6);
 destinations.at<Point>(2,0)=Point(11,11);
 destinations.at<Point>(3,0)=Point(17,17);
 destinations.at<Point>(4,0)=Point(23,23);
 destinations.at<Point>(5,0)=Point(25,25);
 destinations.at<Point>(6,0)=Point(2,2);
 destinations.at<Point>(7,0)=Point(16,16);
 destinations.at<Point>(8,0)=Point(40,40);
 destinations.at<Point>(9,0)=Point(21,21);
 cv::Mat m_indices(X.rows, 1, CV_32S);
 cv::Mat m_dists(X.rows, 1, CV_32F);
 Mat dest_32f; destinations.convertTo(dest_32f,CV_32FC2);  //convert
 Mat X_32f; X.convertTo(X_32f,CV_32FC2);
 cv::flann::Index flann_index(dest_32f, cv::flann::KDTreeIndexParams(2));  // using 2 randomized kdtrees, 1 is ok ,too
 flann_index.knnSearch(X_32f, m_indices, m_dists, 1, cv::flann::SearchParams(64) );
 cout<<"indice:"<<m_indices<<endl;
 cout<<"dist  :"<<m_dists<<endl;
 for(int i=0;i<5;i++)
 {
  cout<<i<<" in X match to "<<m_indices.at<int>(i)<<" in destinations"<<endl;
  cout<<"distance is : "<<m_dists.at<float>(i)<<endl;
 }
 system("pause");
}

the output should be:

indice:[6;
  1;
  2;
  7;
  9]
dist  :[2;
  2;
  2;
  2;
  2]
0 in X match to 6 in destinations
distance is : 2
1 in X match to 1 in destinations
distance is : 2
2 in X match to 2 in destinations
distance is : 2
3 in X match to 7 in destinations
distance is : 2
4 in X match to 9 in destinations
distance is : 2
Press any key to continue . . .