hierarchical_clustering_index.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. /***********************************************************************
  2. * Software License Agreement (BSD License)
  3. *
  4. * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
  5. * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
  6. *
  7. * THE BSD LICENSE
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  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.
  18. *
  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. *************************************************************************/
  30. #ifndef OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_
  31. #define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_
  32. #include <algorithm>
  33. #include <map>
  34. #include <cassert>
  35. #include <limits>
  36. #include <cmath>
  37. #include "general.h"
  38. #include "nn_index.h"
  39. #include "dist.h"
  40. #include "matrix.h"
  41. #include "result_set.h"
  42. #include "heap.h"
  43. #include "allocator.h"
  44. #include "random.h"
  45. #include "saving.h"
  46. namespace cvflann
  47. {
  48. struct HierarchicalClusteringIndexParams : public IndexParams
  49. {
  50. HierarchicalClusteringIndexParams(int branching = 32,
  51. flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM,
  52. int trees = 4, int leaf_size = 100)
  53. {
  54. (*this)["algorithm"] = FLANN_INDEX_HIERARCHICAL;
  55. // The branching factor used in the hierarchical clustering
  56. (*this)["branching"] = branching;
  57. // Algorithm used for picking the initial cluster centers
  58. (*this)["centers_init"] = centers_init;
  59. // number of parallel trees to build
  60. (*this)["trees"] = trees;
  61. // maximum leaf size
  62. (*this)["leaf_size"] = leaf_size;
  63. }
  64. };
  65. /**
  66. * Hierarchical index
  67. *
  68. * Contains a tree constructed through a hierarchical clustering
  69. * and other information for indexing a set of points for nearest-neighbour matching.
  70. */
  71. template <typename Distance>
  72. class HierarchicalClusteringIndex : public NNIndex<Distance>
  73. {
  74. public:
  75. typedef typename Distance::ElementType ElementType;
  76. typedef typename Distance::ResultType DistanceType;
  77. private:
  78. typedef void (HierarchicalClusteringIndex::* centersAlgFunction)(int, int*, int, int*, int&);
  79. /**
  80. * The function used for choosing the cluster centers.
  81. */
  82. centersAlgFunction chooseCenters;
  83. /**
  84. * Chooses the initial centers in the k-means clustering in a random manner.
  85. *
  86. * Params:
  87. * k = number of centers
  88. * vecs = the dataset of points
  89. * indices = indices in the dataset
  90. * indices_length = length of indices vector
  91. *
  92. */
  93. void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length)
  94. {
  95. UniqueRandom r(indices_length);
  96. int index;
  97. for (index=0; index<k; ++index) {
  98. bool duplicate = true;
  99. int rnd;
  100. while (duplicate) {
  101. duplicate = false;
  102. rnd = r.next();
  103. if (rnd<0) {
  104. centers_length = index;
  105. return;
  106. }
  107. centers[index] = dsindices[rnd];
  108. for (int j=0; j<index; ++j) {
  109. DistanceType sq = distance(dataset[centers[index]], dataset[centers[j]], dataset.cols);
  110. if (sq<1e-16) {
  111. duplicate = true;
  112. }
  113. }
  114. }
  115. }
  116. centers_length = index;
  117. }
  118. /**
  119. * Chooses the initial centers in the k-means using Gonzales' algorithm
  120. * so that the centers are spaced apart from each other.
  121. *
  122. * Params:
  123. * k = number of centers
  124. * vecs = the dataset of points
  125. * indices = indices in the dataset
  126. * Returns:
  127. */
  128. void chooseCentersGonzales(int k, int* dsindices, int indices_length, int* centers, int& centers_length)
  129. {
  130. int n = indices_length;
  131. int rnd = rand_int(n);
  132. assert(rnd >=0 && rnd < n);
  133. centers[0] = dsindices[rnd];
  134. int index;
  135. for (index=1; index<k; ++index) {
  136. int best_index = -1;
  137. DistanceType best_val = 0;
  138. for (int j=0; j<n; ++j) {
  139. DistanceType dist = distance(dataset[centers[0]],dataset[dsindices[j]],dataset.cols);
  140. for (int i=1; i<index; ++i) {
  141. DistanceType tmp_dist = distance(dataset[centers[i]],dataset[dsindices[j]],dataset.cols);
  142. if (tmp_dist<dist) {
  143. dist = tmp_dist;
  144. }
  145. }
  146. if (dist>best_val) {
  147. best_val = dist;
  148. best_index = j;
  149. }
  150. }
  151. if (best_index!=-1) {
  152. centers[index] = dsindices[best_index];
  153. }
  154. else {
  155. break;
  156. }
  157. }
  158. centers_length = index;
  159. }
  160. /**
  161. * Chooses the initial centers in the k-means using the algorithm
  162. * proposed in the KMeans++ paper:
  163. * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
  164. *
  165. * Implementation of this function was converted from the one provided in Arthur's code.
  166. *
  167. * Params:
  168. * k = number of centers
  169. * vecs = the dataset of points
  170. * indices = indices in the dataset
  171. * Returns:
  172. */
  173. void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length)
  174. {
  175. int n = indices_length;
  176. double currentPot = 0;
  177. DistanceType* closestDistSq = new DistanceType[n];
  178. // Choose one random center and set the closestDistSq values
  179. int index = rand_int(n);
  180. assert(index >=0 && index < n);
  181. centers[0] = dsindices[index];
  182. // Computing distance^2 will have the advantage of even higher probability further to pick new centers
  183. // far from previous centers (and this complies to "k-means++: the advantages of careful seeding" article)
  184. for (int i = 0; i < n; i++) {
  185. closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols);
  186. closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
  187. currentPot += closestDistSq[i];
  188. }
  189. const int numLocalTries = 1;
  190. // Choose each center
  191. int centerCount;
  192. for (centerCount = 1; centerCount < k; centerCount++) {
  193. // Repeat several trials
  194. double bestNewPot = -1;
  195. int bestNewIndex = 0;
  196. for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
  197. // Choose our center - have to be slightly careful to return a valid answer even accounting
  198. // for possible rounding errors
  199. double randVal = rand_double(currentPot);
  200. for (index = 0; index < n-1; index++) {
  201. if (randVal <= closestDistSq[index]) break;
  202. else randVal -= closestDistSq[index];
  203. }
  204. // Compute the new potential
  205. double newPot = 0;
  206. for (int i = 0; i < n; i++) {
  207. DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols);
  208. newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
  209. }
  210. // Store the best result
  211. if ((bestNewPot < 0)||(newPot < bestNewPot)) {
  212. bestNewPot = newPot;
  213. bestNewIndex = index;
  214. }
  215. }
  216. // Add the appropriate center
  217. centers[centerCount] = dsindices[bestNewIndex];
  218. currentPot = bestNewPot;
  219. for (int i = 0; i < n; i++) {
  220. DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols);
  221. closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
  222. }
  223. }
  224. centers_length = centerCount;
  225. delete[] closestDistSq;
  226. }
  227. /**
  228. * Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel):
  229. * select the first point of the list as a candidate, then parse the points list. If another
  230. * point is further than current candidate from the other centers, test if it is a good center
  231. * of a local aggregation. If it is, replace current candidate by this point. And so on...
  232. *
  233. * Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points,
  234. * this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex
  235. * class that pick centers among existing points instead of computing the barycenters, there is a real
  236. * improvement.
  237. *
  238. * Params:
  239. * k = number of centers
  240. * vecs = the dataset of points
  241. * indices = indices in the dataset
  242. * Returns:
  243. */
  244. void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length)
  245. {
  246. const float kSpeedUpFactor = 1.3f;
  247. int n = indices_length;
  248. DistanceType* closestDistSq = new DistanceType[n];
  249. // Choose one random center and set the closestDistSq values
  250. int index = rand_int(n);
  251. assert(index >=0 && index < n);
  252. centers[0] = dsindices[index];
  253. for (int i = 0; i < n; i++) {
  254. closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols);
  255. }
  256. // Choose each center
  257. int centerCount;
  258. for (centerCount = 1; centerCount < k; centerCount++) {
  259. // Repeat several trials
  260. double bestNewPot = -1;
  261. int bestNewIndex = 0;
  262. DistanceType furthest = 0;
  263. for (index = 0; index < n; index++) {
  264. // We will test only the potential of the points further than current candidate
  265. if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) {
  266. // Compute the new potential
  267. double newPot = 0;
  268. for (int i = 0; i < n; i++) {
  269. newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols)
  270. , closestDistSq[i] );
  271. }
  272. // Store the best result
  273. if ((bestNewPot < 0)||(newPot <= bestNewPot)) {
  274. bestNewPot = newPot;
  275. bestNewIndex = index;
  276. furthest = closestDistSq[index];
  277. }
  278. }
  279. }
  280. // Add the appropriate center
  281. centers[centerCount] = dsindices[bestNewIndex];
  282. for (int i = 0; i < n; i++) {
  283. closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols)
  284. , closestDistSq[i] );
  285. }
  286. }
  287. centers_length = centerCount;
  288. delete[] closestDistSq;
  289. }
  290. public:
  291. /**
  292. * Index constructor
  293. *
  294. * Params:
  295. * inputData = dataset with the input features
  296. * params = parameters passed to the hierarchical k-means algorithm
  297. */
  298. HierarchicalClusteringIndex(const Matrix<ElementType>& inputData, const IndexParams& index_params = HierarchicalClusteringIndexParams(),
  299. Distance d = Distance())
  300. : dataset(inputData), params(index_params), root(NULL), indices(NULL), distance(d)
  301. {
  302. memoryCounter = 0;
  303. size_ = dataset.rows;
  304. veclen_ = dataset.cols;
  305. branching_ = get_param(params,"branching",32);
  306. centers_init_ = get_param(params,"centers_init", FLANN_CENTERS_RANDOM);
  307. trees_ = get_param(params,"trees",4);
  308. leaf_size_ = get_param(params,"leaf_size",100);
  309. if (centers_init_==FLANN_CENTERS_RANDOM) {
  310. chooseCenters = &HierarchicalClusteringIndex::chooseCentersRandom;
  311. }
  312. else if (centers_init_==FLANN_CENTERS_GONZALES) {
  313. chooseCenters = &HierarchicalClusteringIndex::chooseCentersGonzales;
  314. }
  315. else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
  316. chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp;
  317. }
  318. else if (centers_init_==FLANN_CENTERS_GROUPWISE) {
  319. chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser;
  320. }
  321. else {
  322. throw FLANNException("Unknown algorithm for choosing initial centers.");
  323. }
  324. trees_ = get_param(params,"trees",4);
  325. root = new NodePtr[trees_];
  326. indices = new int*[trees_];
  327. for (int i=0; i<trees_; ++i) {
  328. root[i] = NULL;
  329. indices[i] = NULL;
  330. }
  331. }
  332. HierarchicalClusteringIndex(const HierarchicalClusteringIndex&);
  333. HierarchicalClusteringIndex& operator=(const HierarchicalClusteringIndex&);
  334. /**
  335. * Index destructor.
  336. *
  337. * Release the memory used by the index.
  338. */
  339. virtual ~HierarchicalClusteringIndex()
  340. {
  341. free_elements();
  342. if (root!=NULL) {
  343. delete[] root;
  344. }
  345. if (indices!=NULL) {
  346. delete[] indices;
  347. }
  348. }
  349. /**
  350. * Release the inner elements of indices[]
  351. */
  352. void free_elements()
  353. {
  354. if (indices!=NULL) {
  355. for(int i=0; i<trees_; ++i) {
  356. if (indices[i]!=NULL) {
  357. delete[] indices[i];
  358. indices[i] = NULL;
  359. }
  360. }
  361. }
  362. }
  363. /**
  364. * Returns size of index.
  365. */
  366. size_t size() const CV_OVERRIDE
  367. {
  368. return size_;
  369. }
  370. /**
  371. * Returns the length of an index feature.
  372. */
  373. size_t veclen() const CV_OVERRIDE
  374. {
  375. return veclen_;
  376. }
  377. /**
  378. * Computes the inde memory usage
  379. * Returns: memory used by the index
  380. */
  381. int usedMemory() const CV_OVERRIDE
  382. {
  383. return pool.usedMemory+pool.wastedMemory+memoryCounter;
  384. }
  385. /**
  386. * Builds the index
  387. */
  388. void buildIndex() CV_OVERRIDE
  389. {
  390. if (branching_<2) {
  391. throw FLANNException("Branching factor must be at least 2");
  392. }
  393. free_elements();
  394. for (int i=0; i<trees_; ++i) {
  395. indices[i] = new int[size_];
  396. for (size_t j=0; j<size_; ++j) {
  397. indices[i][j] = (int)j;
  398. }
  399. root[i] = pool.allocate<Node>();
  400. computeClustering(root[i], indices[i], (int)size_, branching_,0);
  401. }
  402. }
  403. flann_algorithm_t getType() const CV_OVERRIDE
  404. {
  405. return FLANN_INDEX_HIERARCHICAL;
  406. }
  407. void saveIndex(FILE* stream) CV_OVERRIDE
  408. {
  409. save_value(stream, branching_);
  410. save_value(stream, trees_);
  411. save_value(stream, centers_init_);
  412. save_value(stream, leaf_size_);
  413. save_value(stream, memoryCounter);
  414. for (int i=0; i<trees_; ++i) {
  415. save_value(stream, *indices[i], size_);
  416. save_tree(stream, root[i], i);
  417. }
  418. }
  419. void loadIndex(FILE* stream) CV_OVERRIDE
  420. {
  421. free_elements();
  422. if (root!=NULL) {
  423. delete[] root;
  424. }
  425. if (indices!=NULL) {
  426. delete[] indices;
  427. }
  428. load_value(stream, branching_);
  429. load_value(stream, trees_);
  430. load_value(stream, centers_init_);
  431. load_value(stream, leaf_size_);
  432. load_value(stream, memoryCounter);
  433. indices = new int*[trees_];
  434. root = new NodePtr[trees_];
  435. for (int i=0; i<trees_; ++i) {
  436. indices[i] = new int[size_];
  437. load_value(stream, *indices[i], size_);
  438. load_tree(stream, root[i], i);
  439. }
  440. params["algorithm"] = getType();
  441. params["branching"] = branching_;
  442. params["trees"] = trees_;
  443. params["centers_init"] = centers_init_;
  444. params["leaf_size"] = leaf_size_;
  445. }
  446. /**
  447. * Find set of nearest neighbors to vec. Their indices are stored inside
  448. * the result object.
  449. *
  450. * Params:
  451. * result = the result object in which the indices of the nearest-neighbors are stored
  452. * vec = the vector for which to search the nearest neighbors
  453. * searchParams = parameters that influence the search algorithm (checks)
  454. */
  455. void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
  456. {
  457. int maxChecks = get_param(searchParams,"checks",32);
  458. // Priority queue storing intermediate branches in the best-bin-first search
  459. Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
  460. std::vector<bool> checked(size_,false);
  461. int checks = 0;
  462. for (int i=0; i<trees_; ++i) {
  463. findNN(root[i], result, vec, checks, maxChecks, heap, checked);
  464. }
  465. BranchSt branch;
  466. while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
  467. NodePtr node = branch.node;
  468. findNN(node, result, vec, checks, maxChecks, heap, checked);
  469. }
  470. assert(result.full());
  471. delete heap;
  472. }
  473. IndexParams getParameters() const CV_OVERRIDE
  474. {
  475. return params;
  476. }
  477. private:
  478. /**
  479. * Struture representing a node in the hierarchical k-means tree.
  480. */
  481. struct Node
  482. {
  483. /**
  484. * The cluster center index
  485. */
  486. int pivot;
  487. /**
  488. * The cluster size (number of points in the cluster)
  489. */
  490. int size;
  491. /**
  492. * Child nodes (only for non-terminal nodes)
  493. */
  494. Node** childs;
  495. /**
  496. * Node points (only for terminal nodes)
  497. */
  498. int* indices;
  499. /**
  500. * Level
  501. */
  502. int level;
  503. };
  504. typedef Node* NodePtr;
  505. /**
  506. * Alias definition for a nicer syntax.
  507. */
  508. typedef BranchStruct<NodePtr, DistanceType> BranchSt;
  509. void save_tree(FILE* stream, NodePtr node, int num)
  510. {
  511. save_value(stream, *node);
  512. if (node->childs==NULL) {
  513. int indices_offset = (int)(node->indices - indices[num]);
  514. save_value(stream, indices_offset);
  515. }
  516. else {
  517. for(int i=0; i<branching_; ++i) {
  518. save_tree(stream, node->childs[i], num);
  519. }
  520. }
  521. }
  522. void load_tree(FILE* stream, NodePtr& node, int num)
  523. {
  524. node = pool.allocate<Node>();
  525. load_value(stream, *node);
  526. if (node->childs==NULL) {
  527. int indices_offset;
  528. load_value(stream, indices_offset);
  529. node->indices = indices[num] + indices_offset;
  530. }
  531. else {
  532. node->childs = pool.allocate<NodePtr>(branching_);
  533. for(int i=0; i<branching_; ++i) {
  534. load_tree(stream, node->childs[i], num);
  535. }
  536. }
  537. }
  538. void computeLabels(int* dsindices, int indices_length, int* centers, int centers_length, int* labels, DistanceType& cost)
  539. {
  540. cost = 0;
  541. for (int i=0; i<indices_length; ++i) {
  542. ElementType* point = dataset[dsindices[i]];
  543. DistanceType dist = distance(point, dataset[centers[0]], veclen_);
  544. labels[i] = 0;
  545. for (int j=1; j<centers_length; ++j) {
  546. DistanceType new_dist = distance(point, dataset[centers[j]], veclen_);
  547. if (dist>new_dist) {
  548. labels[i] = j;
  549. dist = new_dist;
  550. }
  551. }
  552. cost += dist;
  553. }
  554. }
  555. /**
  556. * The method responsible with actually doing the recursive hierarchical
  557. * clustering
  558. *
  559. * Params:
  560. * node = the node to cluster
  561. * indices = indices of the points belonging to the current node
  562. * branching = the branching factor to use in the clustering
  563. *
  564. * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
  565. */
  566. void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level)
  567. {
  568. node->size = indices_length;
  569. node->level = level;
  570. if (indices_length < leaf_size_) { // leaf node
  571. node->indices = dsindices;
  572. std::sort(node->indices,node->indices+indices_length);
  573. node->childs = NULL;
  574. return;
  575. }
  576. std::vector<int> centers(branching);
  577. std::vector<int> labels(indices_length);
  578. int centers_length;
  579. (this->*chooseCenters)(branching, dsindices, indices_length, &centers[0], centers_length);
  580. if (centers_length<branching) {
  581. node->indices = dsindices;
  582. std::sort(node->indices,node->indices+indices_length);
  583. node->childs = NULL;
  584. return;
  585. }
  586. // assign points to clusters
  587. DistanceType cost;
  588. computeLabels(dsindices, indices_length, &centers[0], centers_length, &labels[0], cost);
  589. node->childs = pool.allocate<NodePtr>(branching);
  590. int start = 0;
  591. int end = start;
  592. for (int i=0; i<branching; ++i) {
  593. for (int j=0; j<indices_length; ++j) {
  594. if (labels[j]==i) {
  595. std::swap(dsindices[j],dsindices[end]);
  596. std::swap(labels[j],labels[end]);
  597. end++;
  598. }
  599. }
  600. node->childs[i] = pool.allocate<Node>();
  601. node->childs[i]->pivot = centers[i];
  602. node->childs[i]->indices = NULL;
  603. computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1);
  604. start=end;
  605. }
  606. }
  607. /**
  608. * Performs one descent in the hierarchical k-means tree. The branches not
  609. * visited are stored in a priority queue.
  610. *
  611. * Params:
  612. * node = node to explore
  613. * result = container for the k-nearest neighbors found
  614. * vec = query points
  615. * checks = how many points in the dataset have been checked so far
  616. * maxChecks = maximum dataset points to checks
  617. */
  618. void findNN(NodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
  619. Heap<BranchSt>* heap, std::vector<bool>& checked)
  620. {
  621. if (node->childs==NULL) {
  622. if (checks>=maxChecks) {
  623. if (result.full()) return;
  624. }
  625. for (int i=0; i<node->size; ++i) {
  626. int index = node->indices[i];
  627. if (!checked[index]) {
  628. DistanceType dist = distance(dataset[index], vec, veclen_);
  629. result.addPoint(dist, index);
  630. checked[index] = true;
  631. ++checks;
  632. }
  633. }
  634. }
  635. else {
  636. DistanceType* domain_distances = new DistanceType[branching_];
  637. int best_index = 0;
  638. domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_);
  639. for (int i=1; i<branching_; ++i) {
  640. domain_distances[i] = distance(vec, dataset[node->childs[i]->pivot], veclen_);
  641. if (domain_distances[i]<domain_distances[best_index]) {
  642. best_index = i;
  643. }
  644. }
  645. for (int i=0; i<branching_; ++i) {
  646. if (i!=best_index) {
  647. heap->insert(BranchSt(node->childs[i],domain_distances[i]));
  648. }
  649. }
  650. delete[] domain_distances;
  651. findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked);
  652. }
  653. }
  654. private:
  655. /**
  656. * The dataset used by this index
  657. */
  658. const Matrix<ElementType> dataset;
  659. /**
  660. * Parameters used by this index
  661. */
  662. IndexParams params;
  663. /**
  664. * Number of features in the dataset.
  665. */
  666. size_t size_;
  667. /**
  668. * Length of each feature.
  669. */
  670. size_t veclen_;
  671. /**
  672. * The root node in the tree.
  673. */
  674. NodePtr* root;
  675. /**
  676. * Array of indices to vectors in the dataset.
  677. */
  678. int** indices;
  679. /**
  680. * The distance
  681. */
  682. Distance distance;
  683. /**
  684. * Pooled memory allocator.
  685. *
  686. * Using a pooled memory allocator is more efficient
  687. * than allocating memory directly when there is a large
  688. * number small of memory allocations.
  689. */
  690. PooledAllocator pool;
  691. /**
  692. * Memory occupied by the index.
  693. */
  694. int memoryCounter;
  695. /** index parameters */
  696. int branching_;
  697. int trees_;
  698. flann_centers_init_t centers_init_;
  699. int leaf_size_;
  700. };
  701. }
  702. #endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */