1
/***********************************************************************
2
* Software License Agreement (BSD License)
4
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
5
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
9
* Redistribution and use in source and binary forms, with or without
10
* modification, are permitted provided that the following conditions
13
* 1. Redistributions of source code must retain the above copyright
14
* notice, this list of conditions and the following disclaimer.
15
* 2. Redistributions in binary form must reproduce the above copyright
16
* notice, this list of conditions and the following disclaimer in the
17
* documentation and/or other materials provided with the distribution.
19
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
*************************************************************************/
31
#ifndef OPENCV_FLANN_KMEANS_INDEX_H_
32
#define OPENCV_FLANN_KMEANS_INDEX_H_
44
#include "result_set.h"
46
#include "allocator.h"
55
struct KMeansIndexParams : public IndexParams
57
KMeansIndexParams(int branching = 32, int iterations = 11,
58
flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 )
60
(*this)["algorithm"] = FLANN_INDEX_KMEANS;
62
(*this)["branching"] = branching;
63
// max iterations to perform in one kmeans clustering (kmeans tree)
64
(*this)["iterations"] = iterations;
65
// algorithm used for picking the initial cluster centers for kmeans tree
66
(*this)["centers_init"] = centers_init;
67
// cluster boundary index. Used when searching the kmeans tree
68
(*this)["cb_index"] = cb_index;
74
* Hierarchical kmeans index
76
* Contains a tree constructed through a hierarchical kmeans clustering
77
* and other information for indexing a set of points for nearest-neighbour matching.
79
template <typename Distance>
80
class KMeansIndex : public NNIndex<Distance>
83
typedef typename Distance::ElementType ElementType;
84
typedef typename Distance::ResultType DistanceType;
88
typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&);
91
* The function used for choosing the cluster centers.
93
centersAlgFunction chooseCenters;
98
* Chooses the initial centers in the k-means clustering in a random manner.
101
* k = number of centers
102
* vecs = the dataset of points
103
* indices = indices in the dataset
104
* indices_length = length of indices vector
107
void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
109
UniqueRandom r(indices_length);
112
for (index=0; index<k; ++index) {
113
bool duplicate = true;
119
centers_length = index;
123
centers[index] = indices[rnd];
125
for (int j=0; j<index; ++j) {
126
DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols);
134
centers_length = index;
139
* Chooses the initial centers in the k-means using Gonzales' algorithm
140
* so that the centers are spaced apart from each other.
143
* k = number of centers
144
* vecs = the dataset of points
145
* indices = indices in the dataset
148
void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
150
int n = indices_length;
152
int rnd = rand_int(n);
153
assert(rnd >=0 && rnd < n);
155
centers[0] = indices[rnd];
158
for (index=1; index<k; ++index) {
161
DistanceType best_val = 0;
162
for (int j=0; j<n; ++j) {
163
DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols);
164
for (int i=1; i<index; ++i) {
165
DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols);
175
if (best_index!=-1) {
176
centers[index] = indices[best_index];
182
centers_length = index;
187
* Chooses the initial centers in the k-means using the algorithm
188
* proposed in the KMeans++ paper:
189
* Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
191
* Implementation of this function was converted from the one provided in Arthur's code.
194
* k = number of centers
195
* vecs = the dataset of points
196
* indices = indices in the dataset
199
void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
201
int n = indices_length;
203
double currentPot = 0;
204
DistanceType* closestDistSq = new DistanceType[n];
206
// Choose one random center and set the closestDistSq values
207
int index = rand_int(n);
208
assert(index >=0 && index < n);
209
centers[0] = indices[index];
211
for (int i = 0; i < n; i++) {
212
closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
213
closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
214
currentPot += closestDistSq[i];
218
const int numLocalTries = 1;
220
// Choose each center
222
for (centerCount = 1; centerCount < k; centerCount++) {
224
// Repeat several trials
225
double bestNewPot = -1;
226
int bestNewIndex = -1;
227
for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
229
// Choose our center - have to be slightly careful to return a valid answer even accounting
230
// for possible rounding errors
231
double randVal = rand_double(currentPot);
232
for (index = 0; index < n-1; index++) {
233
if (randVal <= closestDistSq[index]) break;
234
else randVal -= closestDistSq[index];
237
// Compute the new potential
239
for (int i = 0; i < n; i++) {
240
DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
241
newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
244
// Store the best result
245
if ((bestNewPot < 0)||(newPot < bestNewPot)) {
247
bestNewIndex = index;
251
// Add the appropriate center
252
centers[centerCount] = indices[bestNewIndex];
253
currentPot = bestNewPot;
254
for (int i = 0; i < n; i++) {
255
DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols);
256
closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
260
centers_length = centerCount;
262
delete[] closestDistSq;
269
flann_algorithm_t getType() const
271
return FLANN_INDEX_KMEANS;
274
class KMeansDistanceComputer : public cv::ParallelLoopBody
277
KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
278
const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen,
279
int* _count, int* _belongs_to, std::vector<DistanceType>& _radiuses, bool& _converged, cv::Mutex& _mtx)
280
: distance(_distance)
282
, branching(_branching)
284
, dcenters(_dcenters)
287
, belongs_to(_belongs_to)
288
, radiuses(_radiuses)
289
, converged(_converged)
294
void operator()(const cv::Range& range) const
296
const int begin = range.start;
297
const int end = range.end;
299
for( int i = begin; i<end; ++i)
301
DistanceType sq_dist = distance(dataset[indices[i]], dcenters[0], veclen);
302
int new_centroid = 0;
303
for (int j=1; j<branching; ++j) {
304
DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
305
if (sq_dist>new_sq_dist) {
307
sq_dist = new_sq_dist;
310
if (sq_dist > radiuses[new_centroid]) {
311
radiuses[new_centroid] = sq_dist;
313
if (new_centroid != belongs_to[i]) {
314
count[belongs_to[i]]--;
315
count[new_centroid]++;
316
belongs_to[i] = new_centroid;
326
const Matrix<ElementType>& dataset;
329
const Matrix<double>& dcenters;
333
std::vector<DistanceType>& radiuses;
336
KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
343
* inputData = dataset with the input features
344
* params = parameters passed to the hierarchical k-means algorithm
346
KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
347
Distance d = Distance())
348
: dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
352
size_ = dataset_.rows;
353
veclen_ = dataset_.cols;
355
branching_ = get_param(params,"branching",32);
356
iterations_ = get_param(params,"iterations",11);
358
iterations_ = (std::numeric_limits<int>::max)();
360
centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);
362
if (centers_init_==FLANN_CENTERS_RANDOM) {
363
chooseCenters = &KMeansIndex::chooseCentersRandom;
365
else if (centers_init_==FLANN_CENTERS_GONZALES) {
366
chooseCenters = &KMeansIndex::chooseCentersGonzales;
368
else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
369
chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
372
throw FLANNException("Unknown algorithm for choosing initial centers.");
379
KMeansIndex(const KMeansIndex&);
380
KMeansIndex& operator=(const KMeansIndex&);
386
* Release the memory used by the index.
388
virtual ~KMeansIndex()
393
if (indices_!=NULL) {
399
* Returns size of index.
407
* Returns the length of an index feature.
409
size_t veclen() const
415
void set_cb_index( float index)
421
* Computes the inde memory usage
422
* Returns: memory used by the index
424
int usedMemory() const
426
return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
435
throw FLANNException("Branching factor must be at least 2");
438
indices_ = new int[size_];
439
for (size_t i=0; i<size_; ++i) {
440
indices_[i] = int(i);
443
root_ = pool_.allocate<KMeansNode>();
444
std::memset(root_, 0, sizeof(KMeansNode));
446
computeNodeStatistics(root_, indices_, (int)size_);
447
computeClustering(root_, indices_, (int)size_, branching_,0);
451
void saveIndex(FILE* stream)
453
save_value(stream, branching_);
454
save_value(stream, iterations_);
455
save_value(stream, memoryCounter_);
456
save_value(stream, cb_index_);
457
save_value(stream, *indices_, (int)size_);
459
save_tree(stream, root_);
463
void loadIndex(FILE* stream)
465
load_value(stream, branching_);
466
load_value(stream, iterations_);
467
load_value(stream, memoryCounter_);
468
load_value(stream, cb_index_);
469
if (indices_!=NULL) {
472
indices_ = new int[size_];
473
load_value(stream, *indices_, size_);
478
load_tree(stream, root_);
480
index_params_["algorithm"] = getType();
481
index_params_["branching"] = branching_;
482
index_params_["iterations"] = iterations_;
483
index_params_["centers_init"] = centers_init_;
484
index_params_["cb_index"] = cb_index_;
490
* Find set of nearest neighbors to vec. Their indices are stored inside
494
* result = the result object in which the indices of the nearest-neighbors are stored
495
* vec = the vector for which to search the nearest neighbors
496
* searchParams = parameters that influence the search algorithm (checks, cb_index)
498
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
501
int maxChecks = get_param(searchParams,"checks",32);
503
if (maxChecks==FLANN_CHECKS_UNLIMITED) {
504
findExactNN(root_, result, vec);
507
// Priority queue storing intermediate branches in the best-bin-first search
508
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
511
findNN(root_, result, vec, checks, maxChecks, heap);
514
while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
515
KMeansNodePtr node = branch.node;
516
findNN(node, result, vec, checks, maxChecks, heap);
518
assert(result.full());
526
* Clustering function that takes a cut in the hierarchical k-means
527
* tree and return the clusters centers of that clustering.
529
* numClusters = number of clusters to have in the clustering computed
530
* Returns: number of cluster centers
532
int getClusterCenters(Matrix<DistanceType>& centers)
534
int numClusters = centers.rows;
536
throw FLANNException("Number of clusters must be at least 1");
539
DistanceType variance;
540
KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
542
int clusterCount = getMinVarianceClusters(root_, clusters, numClusters, variance);
544
Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
546
for (int i=0; i<clusterCount; ++i) {
547
DistanceType* center = clusters[i]->pivot;
548
for (size_t j=0; j<veclen_; ++j) {
549
centers[i][j] = center[j];
557
IndexParams getParameters() const
559
return index_params_;
565
* Struture representing a node in the hierarchical k-means tree.
570
* The cluster center.
574
* The cluster radius.
578
* The cluster mean radius.
580
DistanceType mean_radius;
582
* The cluster variance.
584
DistanceType variance;
586
* The cluster size (number of points in the cluster)
590
* Child nodes (only for non-terminal nodes)
594
* Node points (only for terminal nodes)
602
typedef KMeansNode* KMeansNodePtr;
605
* Alias definition for a nicer syntax.
607
typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;
612
void save_tree(FILE* stream, KMeansNodePtr node)
614
save_value(stream, *node);
615
save_value(stream, *(node->pivot), (int)veclen_);
616
if (node->childs==NULL) {
617
int indices_offset = (int)(node->indices - indices_);
618
save_value(stream, indices_offset);
621
for(int i=0; i<branching_; ++i) {
622
save_tree(stream, node->childs[i]);
628
void load_tree(FILE* stream, KMeansNodePtr& node)
630
node = pool_.allocate<KMeansNode>();
631
load_value(stream, *node);
632
node->pivot = new DistanceType[veclen_];
633
load_value(stream, *(node->pivot), (int)veclen_);
634
if (node->childs==NULL) {
636
load_value(stream, indices_offset);
637
node->indices = indices_ + indices_offset;
640
node->childs = pool_.allocate<KMeansNodePtr>(branching_);
641
for(int i=0; i<branching_; ++i) {
642
load_tree(stream, node->childs[i]);
651
void free_centers(KMeansNodePtr node)
653
delete[] node->pivot;
654
if (node->childs!=NULL) {
655
for (int k=0; k<branching_; ++k) {
656
free_centers(node->childs[k]);
662
* Computes the statistics of a node (mean, radius, variance).
665
* node = the node to use
666
* indices = the indices of the points belonging to the node
668
void computeNodeStatistics(KMeansNodePtr node, int* indices, int indices_length)
671
DistanceType radius = 0;
672
DistanceType variance = 0;
673
DistanceType* mean = new DistanceType[veclen_];
674
memoryCounter_ += int(veclen_*sizeof(DistanceType));
676
memset(mean,0,veclen_*sizeof(DistanceType));
678
for (size_t i=0; i<size_; ++i) {
679
ElementType* vec = dataset_[indices[i]];
680
for (size_t j=0; j<veclen_; ++j) {
683
variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
685
for (size_t j=0; j<veclen_; ++j) {
689
variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
691
DistanceType tmp = 0;
692
for (int i=0; i<indices_length; ++i) {
693
tmp = distance_(mean, dataset_[indices[i]], veclen_);
699
node->variance = variance;
700
node->radius = radius;
706
* The method responsible with actually doing the recursive hierarchical
710
* node = the node to cluster
711
* indices = indices of the points belonging to the current node
712
* branching = the branching factor to use in the clustering
714
* TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
716
void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
718
node->size = indices_length;
721
if (indices_length < branching) {
722
node->indices = indices;
723
std::sort(node->indices,node->indices+indices_length);
728
cv::AutoBuffer<int> centers_idx_buf(branching);
729
int* centers_idx = (int*)centers_idx_buf;
731
(this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
733
if (centers_length<branching) {
734
node->indices = indices;
735
std::sort(node->indices,node->indices+indices_length);
741
cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
742
Matrix<double> dcenters((double*)dcenters_buf,branching,veclen_);
743
for (int i=0; i<centers_length; ++i) {
744
ElementType* vec = dataset_[centers_idx[i]];
745
for (size_t k=0; k<veclen_; ++k) {
746
dcenters[i][k] = double(vec[k]);
750
std::vector<DistanceType> radiuses(branching);
751
cv::AutoBuffer<int> count_buf(branching);
752
int* count = (int*)count_buf;
753
for (int i=0; i<branching; ++i) {
758
// assign points to clusters
759
cv::AutoBuffer<int> belongs_to_buf(indices_length);
760
int* belongs_to = (int*)belongs_to_buf;
761
for (int i=0; i<indices_length; ++i) {
763
DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
765
for (int j=1; j<branching; ++j) {
766
DistanceType new_sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
767
if (sq_dist>new_sq_dist) {
769
sq_dist = new_sq_dist;
772
if (sq_dist>radiuses[belongs_to[i]]) {
773
radiuses[belongs_to[i]] = sq_dist;
775
count[belongs_to[i]]++;
778
bool converged = false;
780
while (!converged && iteration<iterations_) {
784
// compute the new cluster centers
785
for (int i=0; i<branching; ++i) {
786
memset(dcenters[i],0,sizeof(double)*veclen_);
789
for (int i=0; i<indices_length; ++i) {
790
ElementType* vec = dataset_[indices[i]];
791
double* center = dcenters[belongs_to[i]];
792
for (size_t k=0; k<veclen_; ++k) {
796
for (int i=0; i<branching; ++i) {
798
for (size_t k=0; k<veclen_; ++k) {
799
dcenters[i][k] /= cnt;
803
// reassign points to clusters
805
KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, count, belongs_to, radiuses, converged, mtx);
806
parallel_for_(cv::Range(0, (int)indices_length), invoker);
808
for (int i=0; i<branching; ++i) {
809
// if one cluster converges to an empty cluster,
810
// move an element into that cluster
812
int j = (i+1)%branching;
813
while (count[j]<=1) {
817
for (int k=0; k<indices_length; ++k) {
818
if (belongs_to[k]==j) {
819
// for cluster j, we move the furthest element from the center to the empty cluster i
820
if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
834
DistanceType** centers = new DistanceType*[branching];
836
for (int i=0; i<branching; ++i) {
837
centers[i] = new DistanceType[veclen_];
838
memoryCounter_ += (int)(veclen_*sizeof(DistanceType));
839
for (size_t k=0; k<veclen_; ++k) {
840
centers[i][k] = (DistanceType)dcenters[i][k];
845
// compute kmeans clustering for each of the resulting clusters
846
node->childs = pool_.allocate<KMeansNodePtr>(branching);
849
for (int c=0; c<branching; ++c) {
852
DistanceType variance = 0;
853
DistanceType mean_radius =0;
854
for (int i=0; i<indices_length; ++i) {
855
if (belongs_to[i]==c) {
856
DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
858
mean_radius += sqrt(d);
859
std::swap(indices[i],indices[end]);
860
std::swap(belongs_to[i],belongs_to[end]);
866
variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
868
node->childs[c] = pool_.allocate<KMeansNode>();
869
std::memset(node->childs[c], 0, sizeof(KMeansNode));
870
node->childs[c]->radius = radiuses[c];
871
node->childs[c]->pivot = centers[c];
872
node->childs[c]->variance = variance;
873
node->childs[c]->mean_radius = mean_radius;
874
computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
882
* Performs one descent in the hierarchical k-means tree. The branches not
883
* visited are stored in a priority queue.
886
* node = node to explore
887
* result = container for the k-nearest neighbors found
889
* checks = how many points in the dataset have been checked so far
890
* maxChecks = maximum dataset points to checks
894
void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
895
Heap<BranchSt>* heap)
897
// Ignore those clusters that are too far away
899
DistanceType bsq = distance_(vec, node->pivot, veclen_);
900
DistanceType rsq = node->radius;
901
DistanceType wsq = result.worstDist();
903
DistanceType val = bsq-rsq-wsq;
904
DistanceType val2 = val*val-4*rsq*wsq;
907
if ((val>0)&&(val2>0)) {
912
if (node->childs==NULL) {
913
if (checks>=maxChecks) {
914
if (result.full()) return;
916
checks += node->size;
917
for (int i=0; i<node->size; ++i) {
918
int index = node->indices[i];
919
DistanceType dist = distance_(dataset_[index], vec, veclen_);
920
result.addPoint(dist, index);
924
DistanceType* domain_distances = new DistanceType[branching_];
925
int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
926
delete[] domain_distances;
927
findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
932
* Helper function that computes the nearest childs of a node to a given query point.
935
* q = the query point
936
* distances = array with the distances to each child node.
939
int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, Heap<BranchSt>* heap)
943
domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
944
for (int i=1; i<branching_; ++i) {
945
domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
946
if (domain_distances[i]<domain_distances[best_index]) {
951
// float* best_center = node->childs[best_index]->pivot;
952
for (int i=0; i<branching_; ++i) {
953
if (i != best_index) {
954
domain_distances[i] -= cb_index_*node->childs[i]->variance;
956
// float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
957
// if (domain_distances[i]<dist_to_border) {
958
// domain_distances[i] = dist_to_border;
960
heap->insert(BranchSt(node->childs[i],domain_distances[i]));
969
* Function the performs exact nearest neighbor search by traversing the entire tree.
971
void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
973
// Ignore those clusters that are too far away
975
DistanceType bsq = distance_(vec, node->pivot, veclen_);
976
DistanceType rsq = node->radius;
977
DistanceType wsq = result.worstDist();
979
DistanceType val = bsq-rsq-wsq;
980
DistanceType val2 = val*val-4*rsq*wsq;
983
if ((val>0)&&(val2>0)) {
989
if (node->childs==NULL) {
990
for (int i=0; i<node->size; ++i) {
991
int index = node->indices[i];
992
DistanceType dist = distance_(dataset_[index], vec, veclen_);
993
result.addPoint(dist, index);
997
int* sort_indices = new int[branching_];
999
getCenterOrdering(node, vec, sort_indices);
1001
for (int i=0; i<branching_; ++i) {
1002
findExactNN(node->childs[sort_indices[i]],result,vec);
1005
delete[] sort_indices;
1013
* I computes the order in which to traverse the child nodes of a particular node.
1015
void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
1017
DistanceType* domain_distances = new DistanceType[branching_];
1018
for (int i=0; i<branching_; ++i) {
1019
DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
1022
while (domain_distances[j]<dist && j<i) j++;
1023
for (int k=i; k>j; --k) {
1024
domain_distances[k] = domain_distances[k-1];
1025
sort_indices[k] = sort_indices[k-1];
1027
domain_distances[j] = dist;
1028
sort_indices[j] = i;
1030
delete[] domain_distances;
1034
* Method that computes the squared distance from the query point q
1035
* from inside region with center c to the border between this
1036
* region and the region with center p
1038
DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
1040
DistanceType sum = 0;
1041
DistanceType sum2 = 0;
1043
for (int i=0; i<veclen_; ++i) {
1044
DistanceType t = c[i]-p[i];
1045
sum += t*(q[i]-(c[i]+p[i])/2);
1049
return sum*sum/sum2;
1054
* Helper function the descends in the hierarchical k-means tree by spliting those clusters that minimize
1055
* the overall variance of the clustering.
1058
* clusters = array with clusters centers (return value)
1059
* varianceValue = variance of the clustering (return value)
1062
int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
1064
int clusterCount = 1;
1067
DistanceType meanVariance = root->variance*root->size;
1069
while (clusterCount<clusters_length) {
1070
DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
1071
int splitIndex = -1;
1073
for (int i=0; i<clusterCount; ++i) {
1074
if (clusters[i]->childs != NULL) {
1076
DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;
1078
for (int j=0; j<branching_; ++j) {
1079
variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
1081
if (variance<minVariance) {
1082
minVariance = variance;
1088
if (splitIndex==-1) break;
1089
if ( (branching_+clusterCount-1) > clusters_length) break;
1091
meanVariance = minVariance;
1094
KMeansNodePtr toSplit = clusters[splitIndex];
1095
clusters[splitIndex] = toSplit->childs[0];
1096
for (int i=1; i<branching_; ++i) {
1097
clusters[clusterCount++] = toSplit->childs[i];
1101
varianceValue = meanVariance/root->size;
1102
return clusterCount;
1106
/** The branching factor used in the hierarchical k-means clustering */
1109
/** Maximum number of iterations to use when performing k-means clustering */
1112
/** Algorithm for choosing the cluster centers */
1113
flann_centers_init_t centers_init_;
1116
* Cluster border index. This is used in the tree search phase when determining
1117
* the closest cluster to explore next. A zero value takes into account only
1118
* the cluster centres, a value greater then zero also take into account the size
1124
* The dataset used by this index
1126
const Matrix<ElementType> dataset_;
1128
/** Index parameters */
1129
IndexParams index_params_;
1132
* Number of features in the dataset.
1137
* Length of each feature.
1142
* The root node in the tree.
1144
KMeansNodePtr root_;
1147
* Array of indices to vectors in the dataset.
1157
* Pooled memory allocator.
1159
PooledAllocator pool_;
1162
* Memory occupied by the index.
1169
#endif //OPENCV_FLANN_KMEANS_INDEX_H_