[分享] 使用 flann & kdtree 簡易範例
FLANN - Fast Library for Approximate Nearest Neighbors
一個快速找到離你最近的向量的程式庫~
好酷~
給有需要的人。
#include <cmath>
#include <cstdio>
#include <flann/flann.hpp>
int main(int argc, char** argv)
{
// 你要找幾個最近點用nn
int nn = 3;
// 資料總數
const int rows = 9000;
// 資料維度
const int cols = 3;
// 查找的位置數
const int qsize = 2;
float* rdata = new float[cols * rows];
float* qdata = new float[cols * qsize];
// 產生亂數資料
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
rdata[i * cols + j] = rand() * 0.01f;
}
}
for (int i = 0; i < qsize; ++i)
{
for (int j = 0; j < cols; ++j)
{
qdata[i * cols + j] = rand() * 0.01f;
printf("%d %f\n", i * cols + j, qdata[i * cols + j]);
}
}
// 初始化
flann::Matrix<float> dataset(rdata, rows, cols);
flann::Matrix<float> query(qdata, qsize, cols);
flann::Matrix<int> indices(new int[query.rows * nn], query.rows, nn);
flann::Matrix<float> dists(new float[query.rows * nn], query.rows, nn);
// construct an randomized kd-tree index using 4 kd-trees
flann::Index<flann::L2<float> > index(dataset, flann::KDTreeIndexParams(4));
index.buildIndex();
printf("index.knnSearch\n");
// do a knn search, using 128 checks
index.knnSearch(query, indices, dists, nn, flann::SearchParams(128));
for (int i = 0; i < query.rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
int idx = indices[i][j];
printf("index:%d distance:%f position:(%f, %f, %f)\n",
idx, dists[i][j], rdata[idx * cols], rdata[idx * cols + 1],
rdata[idx * cols + 2]);
}
}
delete[] dataset.ptr();
delete[] query.ptr();
delete[] indices.ptr();
delete[] dists.ptr();
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.118.175.37
推
01/09 22:06, , 1F
01/09 22:06, 1F
→
01/10 08:13, , 2F
01/10 08:13, 2F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章