hierarchical_clustering_index.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. //! @cond IGNORED
  33. #include <algorithm>
  34. #include <map>
  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. CV_DbgAssert(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. CV_DbgAssert(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. CV_DbgAssert(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. FLANN_THROW(cv::Error::StsError, "Unknown algorithm for choosing initial centers.");
  323. }
  324. root = new NodePtr[trees_];
  325. indices = new int*[trees_];
  326. for (int i=0; i<trees_; ++i) {
  327. root[i] = NULL;
  328. indices[i] = NULL;
  329. }
  330. }
  331. HierarchicalClusteringIndex(const HierarchicalClusteringIndex&);
  332. HierarchicalClusteringIndex& operator=(const HierarchicalClusteringIndex&);
  333. /**
  334. * Index destructor.
  335. *
  336. * Release the memory used by the index.
  337. */
  338. virtual ~HierarchicalClusteringIndex()
  339. {
  340. if (root!=NULL) {
  341. delete[] root;
  342. }
  343. if (indices!=NULL) {
  344. free_indices();
  345. delete[] indices;
  346. }
  347. }
  348. /**
  349. * Returns size of index.
  350. */
  351. size_t size() const CV_OVERRIDE
  352. {
  353. return size_;
  354. }
  355. /**
  356. * Returns the length of an index feature.
  357. */
  358. size_t veclen() const CV_OVERRIDE
  359. {
  360. return veclen_;
  361. }
  362. /**
  363. * Computes the inde memory usage
  364. * Returns: memory used by the index
  365. */
  366. int usedMemory() const CV_OVERRIDE
  367. {
  368. return pool.usedMemory+pool.wastedMemory+memoryCounter;
  369. }
  370. /**
  371. * Builds the index
  372. */
  373. void buildIndex() CV_OVERRIDE
  374. {
  375. if (branching_<2) {
  376. FLANN_THROW(cv::Error::StsError, "Branching factor must be at least 2");
  377. }
  378. free_indices();
  379. for (int i=0; i<trees_; ++i) {
  380. indices[i] = new int[size_];
  381. for (size_t j=0; j<size_; ++j) {
  382. indices[i][j] = (int)j;
  383. }
  384. root[i] = pool.allocate<Node>();
  385. computeClustering(root[i], indices[i], (int)size_, branching_,0);
  386. }
  387. }
  388. flann_algorithm_t getType() const CV_OVERRIDE
  389. {
  390. return FLANN_INDEX_HIERARCHICAL;
  391. }
  392. void saveIndex(FILE* stream) CV_OVERRIDE
  393. {
  394. save_value(stream, branching_);
  395. save_value(stream, trees_);
  396. save_value(stream, centers_init_);
  397. save_value(stream, leaf_size_);
  398. save_value(stream, memoryCounter);
  399. for (int i=0; i<trees_; ++i) {
  400. save_value(stream, *indices[i], size_);
  401. save_tree(stream, root[i], i);
  402. }
  403. }
  404. void loadIndex(FILE* stream) CV_OVERRIDE
  405. {
  406. if (root!=NULL) {
  407. delete[] root;
  408. }
  409. if (indices!=NULL) {
  410. free_indices();
  411. delete[] indices;
  412. }
  413. load_value(stream, branching_);
  414. load_value(stream, trees_);
  415. load_value(stream, centers_init_);
  416. load_value(stream, leaf_size_);
  417. load_value(stream, memoryCounter);
  418. indices = new int*[trees_];
  419. root = new NodePtr[trees_];
  420. for (int i=0; i<trees_; ++i) {
  421. indices[i] = new int[size_];
  422. load_value(stream, *indices[i], size_);
  423. load_tree(stream, root[i], i);
  424. }
  425. params["algorithm"] = getType();
  426. params["branching"] = branching_;
  427. params["trees"] = trees_;
  428. params["centers_init"] = centers_init_;
  429. params["leaf_size"] = leaf_size_;
  430. }
  431. /**
  432. * Find set of nearest neighbors to vec. Their indices are stored inside
  433. * the result object.
  434. *
  435. * Params:
  436. * result = the result object in which the indices of the nearest-neighbors are stored
  437. * vec = the vector for which to search the nearest neighbors
  438. * searchParams = parameters that influence the search algorithm (checks)
  439. */
  440. void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
  441. {
  442. const int maxChecks = get_param(searchParams,"checks",32);
  443. const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false);
  444. // Priority queue storing intermediate branches in the best-bin-first search
  445. const cv::Ptr<Heap<BranchSt>>& heap = Heap<BranchSt>::getPooledInstance(cv::utils::getThreadID(), (int)size_);
  446. std::vector<bool> checked(size_,false);
  447. int checks = 0;
  448. for (int i=0; i<trees_; ++i) {
  449. findNN(root[i], result, vec, checks, maxChecks, heap, checked, explore_all_trees);
  450. if (!explore_all_trees && (checks >= maxChecks) && result.full())
  451. break;
  452. }
  453. BranchSt branch;
  454. while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
  455. NodePtr node = branch.node;
  456. findNN(node, result, vec, checks, maxChecks, heap, checked, false);
  457. }
  458. CV_Assert(result.full());
  459. }
  460. IndexParams getParameters() const CV_OVERRIDE
  461. {
  462. return params;
  463. }
  464. private:
  465. /**
  466. * Structure representing a node in the hierarchical k-means tree.
  467. */
  468. struct Node
  469. {
  470. /**
  471. * The cluster center index
  472. */
  473. int pivot;
  474. /**
  475. * The cluster size (number of points in the cluster)
  476. */
  477. int size;
  478. /**
  479. * Child nodes (only for non-terminal nodes)
  480. */
  481. Node** childs;
  482. /**
  483. * Node points (only for terminal nodes)
  484. */
  485. int* indices;
  486. /**
  487. * Level
  488. */
  489. int level;
  490. };
  491. typedef Node* NodePtr;
  492. /**
  493. * Alias definition for a nicer syntax.
  494. */
  495. typedef BranchStruct<NodePtr, DistanceType> BranchSt;
  496. void save_tree(FILE* stream, NodePtr node, int num)
  497. {
  498. save_value(stream, *node);
  499. if (node->childs==NULL) {
  500. int indices_offset = (int)(node->indices - indices[num]);
  501. save_value(stream, indices_offset);
  502. }
  503. else {
  504. for(int i=0; i<branching_; ++i) {
  505. save_tree(stream, node->childs[i], num);
  506. }
  507. }
  508. }
  509. void load_tree(FILE* stream, NodePtr& node, int num)
  510. {
  511. node = pool.allocate<Node>();
  512. load_value(stream, *node);
  513. if (node->childs==NULL) {
  514. int indices_offset;
  515. load_value(stream, indices_offset);
  516. node->indices = indices[num] + indices_offset;
  517. }
  518. else {
  519. node->childs = pool.allocate<NodePtr>(branching_);
  520. for(int i=0; i<branching_; ++i) {
  521. load_tree(stream, node->childs[i], num);
  522. }
  523. }
  524. }
  525. /**
  526. * Release the inner elements of indices[]
  527. */
  528. void free_indices()
  529. {
  530. if (indices!=NULL) {
  531. for(int i=0; i<trees_; ++i) {
  532. if (indices[i]!=NULL) {
  533. delete[] indices[i];
  534. indices[i] = NULL;
  535. }
  536. }
  537. }
  538. }
  539. void computeLabels(int* dsindices, int indices_length, int* centers, int centers_length, int* labels, DistanceType& cost)
  540. {
  541. cost = 0;
  542. for (int i=0; i<indices_length; ++i) {
  543. ElementType* point = dataset[dsindices[i]];
  544. DistanceType dist = distance(point, dataset[centers[0]], veclen_);
  545. labels[i] = 0;
  546. for (int j=1; j<centers_length; ++j) {
  547. DistanceType new_dist = distance(point, dataset[centers[j]], veclen_);
  548. if (dist>new_dist) {
  549. labels[i] = j;
  550. dist = new_dist;
  551. }
  552. }
  553. cost += dist;
  554. }
  555. }
  556. /**
  557. * The method responsible with actually doing the recursive hierarchical
  558. * clustering
  559. *
  560. * Params:
  561. * node = the node to cluster
  562. * indices = indices of the points belonging to the current node
  563. * branching = the branching factor to use in the clustering
  564. *
  565. * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
  566. */
  567. void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level)
  568. {
  569. node->size = indices_length;
  570. node->level = level;
  571. if (indices_length < leaf_size_) { // leaf node
  572. node->indices = dsindices;
  573. std::sort(node->indices,node->indices+indices_length);
  574. node->childs = NULL;
  575. return;
  576. }
  577. std::vector<int> centers(branching);
  578. std::vector<int> labels(indices_length);
  579. int centers_length;
  580. (this->*chooseCenters)(branching, dsindices, indices_length, &centers[0], centers_length);
  581. if (centers_length<branching) {
  582. node->indices = dsindices;
  583. std::sort(node->indices,node->indices+indices_length);
  584. node->childs = NULL;
  585. return;
  586. }
  587. // assign points to clusters
  588. DistanceType cost;
  589. computeLabels(dsindices, indices_length, &centers[0], centers_length, &labels[0], cost);
  590. node->childs = pool.allocate<NodePtr>(branching);
  591. int start = 0;
  592. int end = start;
  593. for (int i=0; i<branching; ++i) {
  594. for (int j=0; j<indices_length; ++j) {
  595. if (labels[j]==i) {
  596. std::swap(dsindices[j],dsindices[end]);
  597. std::swap(labels[j],labels[end]);
  598. end++;
  599. }
  600. }
  601. node->childs[i] = pool.allocate<Node>();
  602. node->childs[i]->pivot = centers[i];
  603. node->childs[i]->indices = NULL;
  604. computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1);
  605. start=end;
  606. }
  607. }
  608. /**
  609. * Performs one descent in the hierarchical k-means tree. The branches not
  610. * visited are stored in a priority queue.
  611. *
  612. * Params:
  613. * node = node to explore
  614. * result = container for the k-nearest neighbors found
  615. * vec = query points
  616. * checks = how many points in the dataset have been checked so far
  617. * maxChecks = maximum dataset points to checks
  618. */
  619. void findNN(NodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
  620. const cv::Ptr<Heap<BranchSt>>& heap, std::vector<bool>& checked, bool explore_all_trees = false)
  621. {
  622. if (node->childs==NULL) {
  623. if (!explore_all_trees && (checks>=maxChecks) && result.full()) {
  624. return;
  625. }
  626. for (int i=0; i<node->size; ++i) {
  627. int index = node->indices[i];
  628. if (!checked[index]) {
  629. DistanceType dist = distance(dataset[index], vec, veclen_);
  630. result.addPoint(dist, index);
  631. checked[index] = true;
  632. ++checks;
  633. }
  634. }
  635. }
  636. else {
  637. DistanceType* domain_distances = new DistanceType[branching_];
  638. int best_index = 0;
  639. domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_);
  640. for (int i=1; i<branching_; ++i) {
  641. domain_distances[i] = distance(vec, dataset[node->childs[i]->pivot], veclen_);
  642. if (domain_distances[i]<domain_distances[best_index]) {
  643. best_index = i;
  644. }
  645. }
  646. for (int i=0; i<branching_; ++i) {
  647. if (i!=best_index) {
  648. heap->insert(BranchSt(node->childs[i],domain_distances[i]));
  649. }
  650. }
  651. delete[] domain_distances;
  652. findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked, explore_all_trees);
  653. }
  654. }
  655. private:
  656. /**
  657. * The dataset used by this index
  658. */
  659. const Matrix<ElementType> dataset;
  660. /**
  661. * Parameters used by this index
  662. */
  663. IndexParams params;
  664. /**
  665. * Number of features in the dataset.
  666. */
  667. size_t size_;
  668. /**
  669. * Length of each feature.
  670. */
  671. size_t veclen_;
  672. /**
  673. * The root node in the tree.
  674. */
  675. NodePtr* root;
  676. /**
  677. * Array of indices to vectors in the dataset.
  678. */
  679. int** indices;
  680. /**
  681. * The distance
  682. */
  683. Distance distance;
  684. /**
  685. * Pooled memory allocator.
  686. *
  687. * Using a pooled memory allocator is more efficient
  688. * than allocating memory directly when there is a large
  689. * number small of memory allocations.
  690. */
  691. PooledAllocator pool;
  692. /**
  693. * Memory occupied by the index.
  694. */
  695. int memoryCounter;
  696. /** index parameters */
  697. int branching_;
  698. int trees_;
  699. flann_centers_init_t centers_init_;
  700. int leaf_size_;
  701. };
  702. }
  703. //! @endcond
  704. #endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */