KD-Tree 开源实现代码
- 添加头文件 #include <KDTree.hpp>
- 测试代码及源文件 下载链接(OpenCV version: 4.5.1)
- hpp 文件名为 “KDTree.hpp”
#ifndef __KDTREE_H__
#define __KDTREE_H__
#include <algorithm>
#include <cmath>
#include <exception>
#include <functional>
#include <numeric>
#include <vector>
namespace obstarcalib::caliblink {
template <typename PointT, int DIM = 2, typename Allocator = std::allocator<PointT>>
class KDTree {
public:
KDTree()
: root_(nullptr) {
};
KDTree(const std::vector<PointT, Allocator>& points)
: root_(nullptr)
{
build(points);
}
~KDTree() {
clear(); }
void build(const std::vector<PointT, Allocator>& points)
{
clear();
points_ = points;
std::vector<int> indices(points.size());
std::iota(std::begin(indices), std::end(indices), 0);
root_ = buildRecursive(indices.data(), (int)points.size(), 0);
}
void clear()
{
clearRecursive(root_);
root_ = nullptr;
points_.clear();
}
bool validate() const
{
try {
validateRecursive(root_, 0);
} catch (const Exception&) {
return false;
}
return true;
}
int nnSearch(const PointT& query, double* minDist = nullptr) const
{
int guess;
double _minDist = std::numeric_limits<double>::max();
nnSearchRecursive(query, root_, &guess, &_minDist);
if (minDist)
*minDist = _minDist;
return guess;
}
std::vector<int> knnSearch(const PointT& query, int k) const
{
KnnQueue queue(k);
knnSearchRecursive(query, root_, queue, k);
std::vector<int> indices(queue.size());
for (size_t i = 0; i < queue.size(); i++)
indices[i] = queue[i].second;
return indices;