您的位置:首页 > 运维架构

opencv 快速线性搜索knnsearch和knnmatch比较

2015-05-15 11:19 555 查看
利用opencv的flann以及match的库进行线性近邻knn搜索的速度测试,结果表明knnmatch更快一些,看了下opencv底层代码,knnmatch用了parallel_for_ 并行加速

#include <vector>
#include <iostream>
#include <time.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
const int samples = 50000;
const int DIM = 1024;
const int k =10;

inline double cpu_time(){
return clock()*1000/CLOCKS_PER_SEC;
}

void generate_data(Mat& data){
RNG rng((unsigned int)time(NULL));
data.create(samples,DIM,CV_32FC1);

Point center;
center.x = rng.uniform(0,data.cols);
center.y = rng.uniform(0,data.rows);
rng.fill(data, RNG::NORMAL, Scalar(center.x,center.y), Scalar(data.cols*0.05,data.rows*0.05));
}

void linear_search(const Mat& data, const Mat& point, Mat& indices, Mat& dists, const int k){
double t1,t2;
flann::Index flannIndex(data, flann::LinearIndexParams(), cvflann::FLANN_DIST_L2);
cout<<"Begin LinearSearch: "<<endl;
t1 = cpu_time();
flannIndex.knnSearch(point, indices, dists, k, flann::SearchParams(64));
t2 = cpu_time();
cout<<"Finish linerSearch: "<<t2-t1<<"ms"<<endl;
}
float calculate(float* a, float* b, int size, float worst_dist = -1){
float diff0,diff1,diff2,diff3,result=0;
float* last = a + size;
float* lastgroup = last-3;
while (a < lastgroup)
{
diff0 = a[0]-b[0];
diff1 = a[1]-b[1];
diff2 = a[2]-b[2];
diff3 = a[3]-b[3];
result += diff0*diff0 + diff1*diff1 + diff2*diff2 + diff3*diff3;

a+=4;
b+=4;
if ((worst_dist>0)&&(result>worst_dist))
{
return result;
}
}
while (a<last)
{
diff0 = *a++ - *b++;
result+= diff0*diff0;
}
return result;
}
//My test with loop unrolling, as it is one of the most expensive inner loops
void test(float* a, float* b){
double t1,t2;
t1 = cpu_time();
cout<<"Begin test: "<<endl;
float* data = a;
float done=0;
for(int i=0; i<samples; i++,data+=DIM){
calculate(data,b,DIM);
}
t2 = cpu_time();
cout<<"Finish test: "<<t2-t1<<"ms"<<endl;
}
//Brute Force Matcher
void BFM(Mat& data, Mat& point){
double t1, t2;
Ptr<DescriptorMatcher> DM = DescriptorMatcher::create("BruteForce");

vector<vector<DMatch> > matches;
cout<<"Begin BFM: "<<endl;
t1 = cpu_time();
DM->knnMatch(point,data,matches,k);
t2 = cpu_time();
cout<<"Finish BFM: "<<t2-t1<<"ms"<<endl;
for (int i=0;i<k;i++)
{
cout<<matches[0][i].trainIdx<<", ";
}
cout<<endl;
}

int main(){
Mat data;
generate_data(data);
Mat point = data.row(10).clone();
float* a = (float* )data.data;
float* b = (float* )point.data;

test(a,b);

Mat indices(1,DIM,CV_32FC1);
Mat dists(1,DIM,CV_32FC1);

BFM(data,point);

linear_search(data,point,indices,dists,k);
cout<<indices<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: