kmeans_index.h 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  1. /***********************************************************************
  2. * Software License Agreement (BSD License)
  3. *
  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.
  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_KMEANS_INDEX_H_
  31. #define OPENCV_FLANN_KMEANS_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. #include "logger.h"
  47. #define BITS_PER_CHAR 8
  48. #define BITS_PER_BASE 2 // for DNA/RNA sequences
  49. #define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE)
  50. #define HISTOS_PER_BASE (1<<BITS_PER_BASE)
  51. namespace cvflann
  52. {
  53. struct KMeansIndexParams : public IndexParams
  54. {
  55. KMeansIndexParams(int branching = 32, int iterations = 11,
  56. flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM,
  57. float cb_index = 0.2, int trees = 1 )
  58. {
  59. (*this)["algorithm"] = FLANN_INDEX_KMEANS;
  60. // branching factor
  61. (*this)["branching"] = branching;
  62. // max iterations to perform in one kmeans clustering (kmeans tree)
  63. (*this)["iterations"] = iterations;
  64. // algorithm used for picking the initial cluster centers for kmeans tree
  65. (*this)["centers_init"] = centers_init;
  66. // cluster boundary index. Used when searching the kmeans tree
  67. (*this)["cb_index"] = cb_index;
  68. // number of kmeans trees to search in
  69. (*this)["trees"] = trees;
  70. }
  71. };
  72. /**
  73. * Hierarchical kmeans index
  74. *
  75. * Contains a tree constructed through a hierarchical kmeans clustering
  76. * and other information for indexing a set of points for nearest-neighbour matching.
  77. */
  78. template <typename Distance>
  79. class KMeansIndex : public NNIndex<Distance>
  80. {
  81. public:
  82. typedef typename Distance::ElementType ElementType;
  83. typedef typename Distance::ResultType DistanceType;
  84. typedef typename Distance::CentersType CentersType;
  85. typedef typename Distance::is_kdtree_distance is_kdtree_distance;
  86. typedef typename Distance::is_vector_space_distance is_vector_space_distance;
  87. typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&);
  88. /**
  89. * The function used for choosing the cluster centers.
  90. */
  91. centersAlgFunction chooseCenters;
  92. /**
  93. * Chooses the initial centers in the k-means clustering in a random manner.
  94. *
  95. * Params:
  96. * k = number of centers
  97. * vecs = the dataset of points
  98. * indices = indices in the dataset
  99. * indices_length = length of indices vector
  100. *
  101. */
  102. void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
  103. {
  104. UniqueRandom r(indices_length);
  105. int index;
  106. for (index=0; index<k; ++index) {
  107. bool duplicate = true;
  108. int rnd;
  109. while (duplicate) {
  110. duplicate = false;
  111. rnd = r.next();
  112. if (rnd<0) {
  113. centers_length = index;
  114. return;
  115. }
  116. centers[index] = indices[rnd];
  117. for (int j=0; j<index; ++j) {
  118. DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols);
  119. if (sq<1e-16) {
  120. duplicate = true;
  121. }
  122. }
  123. }
  124. }
  125. centers_length = index;
  126. }
  127. /**
  128. * Chooses the initial centers in the k-means using Gonzales' algorithm
  129. * so that the centers are spaced apart from each other.
  130. *
  131. * Params:
  132. * k = number of centers
  133. * vecs = the dataset of points
  134. * indices = indices in the dataset
  135. * Returns:
  136. */
  137. void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
  138. {
  139. int n = indices_length;
  140. int rnd = rand_int(n);
  141. CV_DbgAssert(rnd >=0 && rnd < n);
  142. centers[0] = indices[rnd];
  143. int index;
  144. for (index=1; index<k; ++index) {
  145. int best_index = -1;
  146. DistanceType best_val = 0;
  147. for (int j=0; j<n; ++j) {
  148. DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols);
  149. for (int i=1; i<index; ++i) {
  150. DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols);
  151. if (tmp_dist<dist) {
  152. dist = tmp_dist;
  153. }
  154. }
  155. if (dist>best_val) {
  156. best_val = dist;
  157. best_index = j;
  158. }
  159. }
  160. if (best_index!=-1) {
  161. centers[index] = indices[best_index];
  162. }
  163. else {
  164. break;
  165. }
  166. }
  167. centers_length = index;
  168. }
  169. /**
  170. * Chooses the initial centers in the k-means using the algorithm
  171. * proposed in the KMeans++ paper:
  172. * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
  173. *
  174. * Implementation of this function was converted from the one provided in Arthur's code.
  175. *
  176. * Params:
  177. * k = number of centers
  178. * vecs = the dataset of points
  179. * indices = indices in the dataset
  180. * Returns:
  181. */
  182. void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
  183. {
  184. int n = indices_length;
  185. double currentPot = 0;
  186. DistanceType* closestDistSq = new DistanceType[n];
  187. // Choose one random center and set the closestDistSq values
  188. int index = rand_int(n);
  189. CV_DbgAssert(index >=0 && index < n);
  190. centers[0] = indices[index];
  191. for (int i = 0; i < n; i++) {
  192. closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
  193. closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
  194. currentPot += closestDistSq[i];
  195. }
  196. const int numLocalTries = 1;
  197. // Choose each center
  198. int centerCount;
  199. for (centerCount = 1; centerCount < k; centerCount++) {
  200. // Repeat several trials
  201. double bestNewPot = -1;
  202. int bestNewIndex = -1;
  203. for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
  204. // Choose our center - have to be slightly careful to return a valid answer even accounting
  205. // for possible rounding errors
  206. double randVal = rand_double(currentPot);
  207. for (index = 0; index < n-1; index++) {
  208. if (randVal <= closestDistSq[index]) break;
  209. else randVal -= closestDistSq[index];
  210. }
  211. // Compute the new potential
  212. double newPot = 0;
  213. for (int i = 0; i < n; i++) {
  214. DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
  215. newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
  216. }
  217. // Store the best result
  218. if ((bestNewPot < 0)||(newPot < bestNewPot)) {
  219. bestNewPot = newPot;
  220. bestNewIndex = index;
  221. }
  222. }
  223. // Add the appropriate center
  224. centers[centerCount] = indices[bestNewIndex];
  225. currentPot = bestNewPot;
  226. for (int i = 0; i < n; i++) {
  227. DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols);
  228. closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
  229. }
  230. }
  231. centers_length = centerCount;
  232. delete[] closestDistSq;
  233. }
  234. public:
  235. flann_algorithm_t getType() const CV_OVERRIDE
  236. {
  237. return FLANN_INDEX_KMEANS;
  238. }
  239. template<class CentersContainerType>
  240. class KMeansDistanceComputer : public cv::ParallelLoopBody
  241. {
  242. public:
  243. KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
  244. const int _branching, const int* _indices, const CentersContainerType& _dcenters,
  245. const size_t _veclen, std::vector<int> &_new_centroids,
  246. std::vector<DistanceType> &_sq_dists)
  247. : distance(_distance)
  248. , dataset(_dataset)
  249. , branching(_branching)
  250. , indices(_indices)
  251. , dcenters(_dcenters)
  252. , veclen(_veclen)
  253. , new_centroids(_new_centroids)
  254. , sq_dists(_sq_dists)
  255. {
  256. }
  257. void operator()(const cv::Range& range) const CV_OVERRIDE
  258. {
  259. const int begin = range.start;
  260. const int end = range.end;
  261. for( int i = begin; i<end; ++i)
  262. {
  263. DistanceType sq_dist(distance(dataset[indices[i]], dcenters[0], veclen));
  264. int new_centroid(0);
  265. for (int j=1; j<branching; ++j) {
  266. DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
  267. if (sq_dist>new_sq_dist) {
  268. new_centroid = j;
  269. sq_dist = new_sq_dist;
  270. }
  271. }
  272. sq_dists[i] = sq_dist;
  273. new_centroids[i] = new_centroid;
  274. }
  275. }
  276. private:
  277. Distance distance;
  278. const Matrix<ElementType>& dataset;
  279. const int branching;
  280. const int* indices;
  281. const CentersContainerType& dcenters;
  282. const size_t veclen;
  283. std::vector<int> &new_centroids;
  284. std::vector<DistanceType> &sq_dists;
  285. KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
  286. };
  287. /**
  288. * Index constructor
  289. *
  290. * Params:
  291. * inputData = dataset with the input features
  292. * params = parameters passed to the hierarchical k-means algorithm
  293. */
  294. KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
  295. Distance d = Distance())
  296. : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
  297. {
  298. memoryCounter_ = 0;
  299. size_ = dataset_.rows;
  300. veclen_ = dataset_.cols;
  301. branching_ = get_param(params,"branching",32);
  302. trees_ = get_param(params,"trees",1);
  303. iterations_ = get_param(params,"iterations",11);
  304. if (iterations_<0) {
  305. iterations_ = (std::numeric_limits<int>::max)();
  306. }
  307. centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);
  308. if (centers_init_==FLANN_CENTERS_RANDOM) {
  309. chooseCenters = &KMeansIndex::chooseCentersRandom;
  310. }
  311. else if (centers_init_==FLANN_CENTERS_GONZALES) {
  312. chooseCenters = &KMeansIndex::chooseCentersGonzales;
  313. }
  314. else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
  315. chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
  316. }
  317. else {
  318. FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers.");
  319. }
  320. cb_index_ = 0.4f;
  321. root_ = new KMeansNodePtr[trees_];
  322. indices_ = new int*[trees_];
  323. for (int i=0; i<trees_; ++i) {
  324. root_[i] = NULL;
  325. indices_[i] = NULL;
  326. }
  327. }
  328. KMeansIndex(const KMeansIndex&);
  329. KMeansIndex& operator=(const KMeansIndex&);
  330. /**
  331. * Index destructor.
  332. *
  333. * Release the memory used by the index.
  334. */
  335. virtual ~KMeansIndex()
  336. {
  337. if (root_ != NULL) {
  338. free_centers();
  339. delete[] root_;
  340. }
  341. if (indices_!=NULL) {
  342. free_indices();
  343. delete[] indices_;
  344. }
  345. }
  346. /**
  347. * Returns size of index.
  348. */
  349. size_t size() const CV_OVERRIDE
  350. {
  351. return size_;
  352. }
  353. /**
  354. * Returns the length of an index feature.
  355. */
  356. size_t veclen() const CV_OVERRIDE
  357. {
  358. return veclen_;
  359. }
  360. void set_cb_index( float index)
  361. {
  362. cb_index_ = index;
  363. }
  364. /**
  365. * Computes the inde memory usage
  366. * Returns: memory used by the index
  367. */
  368. int usedMemory() const CV_OVERRIDE
  369. {
  370. return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
  371. }
  372. /**
  373. * Builds the index
  374. */
  375. void buildIndex() CV_OVERRIDE
  376. {
  377. if (branching_<2) {
  378. FLANN_THROW(cv::Error::StsError, "Branching factor must be at least 2");
  379. }
  380. free_indices();
  381. for (int i=0; i<trees_; ++i) {
  382. indices_[i] = new int[size_];
  383. for (size_t j=0; j<size_; ++j) {
  384. indices_[i][j] = int(j);
  385. }
  386. root_[i] = pool_.allocate<KMeansNode>();
  387. std::memset(root_[i], 0, sizeof(KMeansNode));
  388. Distance* dummy = NULL;
  389. computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy);
  390. computeClustering(root_[i], indices_[i], (int)size_, branching_,0);
  391. }
  392. }
  393. void saveIndex(FILE* stream) CV_OVERRIDE
  394. {
  395. save_value(stream, branching_);
  396. save_value(stream, iterations_);
  397. save_value(stream, memoryCounter_);
  398. save_value(stream, cb_index_);
  399. save_value(stream, trees_);
  400. for (int i=0; i<trees_; ++i) {
  401. save_value(stream, *indices_[i], (int)size_);
  402. save_tree(stream, root_[i], i);
  403. }
  404. }
  405. void loadIndex(FILE* stream) CV_OVERRIDE
  406. {
  407. if (indices_!=NULL) {
  408. free_indices();
  409. delete[] indices_;
  410. }
  411. if (root_!=NULL) {
  412. free_centers();
  413. }
  414. load_value(stream, branching_);
  415. load_value(stream, iterations_);
  416. load_value(stream, memoryCounter_);
  417. load_value(stream, cb_index_);
  418. load_value(stream, trees_);
  419. indices_ = new int*[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. index_params_["algorithm"] = getType();
  426. index_params_["branching"] = branching_;
  427. index_params_["trees"] = trees_;
  428. index_params_["iterations"] = iterations_;
  429. index_params_["centers_init"] = centers_init_;
  430. index_params_["cb_index"] = cb_index_;
  431. }
  432. /**
  433. * Find set of nearest neighbors to vec. Their indices are stored inside
  434. * the result object.
  435. *
  436. * Params:
  437. * result = the result object in which the indices of the nearest-neighbors are stored
  438. * vec = the vector for which to search the nearest neighbors
  439. * searchParams = parameters that influence the search algorithm (checks, cb_index)
  440. */
  441. void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
  442. {
  443. const int maxChecks = get_param(searchParams,"checks",32);
  444. if (maxChecks==FLANN_CHECKS_UNLIMITED) {
  445. findExactNN(root_[0], result, vec);
  446. }
  447. else {
  448. // Priority queue storing intermediate branches in the best-bin-first search
  449. const cv::Ptr<Heap<BranchSt>>& heap = Heap<BranchSt>::getPooledInstance(cv::utils::getThreadID(), (int)size_);
  450. int checks = 0;
  451. for (int i=0; i<trees_; ++i) {
  452. findNN(root_[i], result, vec, checks, maxChecks, heap);
  453. if ((checks >= maxChecks) && result.full())
  454. break;
  455. }
  456. BranchSt branch;
  457. while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
  458. KMeansNodePtr node = branch.node;
  459. findNN(node, result, vec, checks, maxChecks, heap);
  460. }
  461. CV_Assert(result.full());
  462. }
  463. }
  464. /**
  465. * Clustering function that takes a cut in the hierarchical k-means
  466. * tree and return the clusters centers of that clustering.
  467. * Params:
  468. * numClusters = number of clusters to have in the clustering computed
  469. * Returns: number of cluster centers
  470. */
  471. int getClusterCenters(Matrix<CentersType>& centers)
  472. {
  473. int numClusters = centers.rows;
  474. if (numClusters<1) {
  475. FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1");
  476. }
  477. DistanceType variance;
  478. KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
  479. int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance);
  480. Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
  481. for (int i=0; i<clusterCount; ++i) {
  482. CentersType* center = clusters[i]->pivot;
  483. for (size_t j=0; j<veclen_; ++j) {
  484. centers[i][j] = center[j];
  485. }
  486. }
  487. delete[] clusters;
  488. return clusterCount;
  489. }
  490. IndexParams getParameters() const CV_OVERRIDE
  491. {
  492. return index_params_;
  493. }
  494. private:
  495. /**
  496. * Structure representing a node in the hierarchical k-means tree.
  497. */
  498. struct KMeansNode
  499. {
  500. /**
  501. * The cluster center.
  502. */
  503. CentersType* pivot;
  504. /**
  505. * The cluster radius.
  506. */
  507. DistanceType radius;
  508. /**
  509. * The cluster mean radius.
  510. */
  511. DistanceType mean_radius;
  512. /**
  513. * The cluster variance.
  514. */
  515. DistanceType variance;
  516. /**
  517. * The cluster size (number of points in the cluster)
  518. */
  519. int size;
  520. /**
  521. * Child nodes (only for non-terminal nodes)
  522. */
  523. KMeansNode** childs;
  524. /**
  525. * Node points (only for terminal nodes)
  526. */
  527. int* indices;
  528. /**
  529. * Level
  530. */
  531. int level;
  532. };
  533. typedef KMeansNode* KMeansNodePtr;
  534. /**
  535. * Alias definition for a nicer syntax.
  536. */
  537. typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;
  538. void save_tree(FILE* stream, KMeansNodePtr node, int num)
  539. {
  540. save_value(stream, *node);
  541. save_value(stream, *(node->pivot), (int)veclen_);
  542. if (node->childs==NULL) {
  543. int indices_offset = (int)(node->indices - indices_[num]);
  544. save_value(stream, indices_offset);
  545. }
  546. else {
  547. for(int i=0; i<branching_; ++i) {
  548. save_tree(stream, node->childs[i], num);
  549. }
  550. }
  551. }
  552. void load_tree(FILE* stream, KMeansNodePtr& node, int num)
  553. {
  554. node = pool_.allocate<KMeansNode>();
  555. load_value(stream, *node);
  556. node->pivot = new CentersType[veclen_];
  557. load_value(stream, *(node->pivot), (int)veclen_);
  558. if (node->childs==NULL) {
  559. int indices_offset;
  560. load_value(stream, indices_offset);
  561. node->indices = indices_[num] + indices_offset;
  562. }
  563. else {
  564. node->childs = pool_.allocate<KMeansNodePtr>(branching_);
  565. for(int i=0; i<branching_; ++i) {
  566. load_tree(stream, node->childs[i], num);
  567. }
  568. }
  569. }
  570. /**
  571. * Helper function
  572. */
  573. void free_centers(KMeansNodePtr node)
  574. {
  575. delete[] node->pivot;
  576. if (node->childs!=NULL) {
  577. for (int k=0; k<branching_; ++k) {
  578. free_centers(node->childs[k]);
  579. }
  580. }
  581. }
  582. void free_centers()
  583. {
  584. if (root_ != NULL) {
  585. for(int i=0; i<trees_; ++i) {
  586. if (root_[i] != NULL) {
  587. free_centers(root_[i]);
  588. }
  589. }
  590. }
  591. }
  592. /**
  593. * Release the inner elements of indices[]
  594. */
  595. void free_indices()
  596. {
  597. if (indices_!=NULL) {
  598. for(int i=0; i<trees_; ++i) {
  599. if (indices_[i]!=NULL) {
  600. delete[] indices_[i];
  601. indices_[i] = NULL;
  602. }
  603. }
  604. }
  605. }
  606. /**
  607. * Computes the statistics of a node (mean, radius, variance).
  608. *
  609. * Params:
  610. * node = the node to use
  611. * indices = array of indices of the points belonging to the node
  612. * indices_length = number of indices in the array
  613. */
  614. void computeNodeStatistics(KMeansNodePtr node, int* indices, unsigned int indices_length)
  615. {
  616. DistanceType variance = 0;
  617. CentersType* mean = new CentersType[veclen_];
  618. memoryCounter_ += int(veclen_*sizeof(CentersType));
  619. memset(mean,0,veclen_*sizeof(CentersType));
  620. for (unsigned int i=0; i<indices_length; ++i) {
  621. ElementType* vec = dataset_[indices[i]];
  622. for (size_t j=0; j<veclen_; ++j) {
  623. mean[j] += vec[j];
  624. }
  625. variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
  626. }
  627. float length = static_cast<float>(indices_length);
  628. for (size_t j=0; j<veclen_; ++j) {
  629. mean[j] = cvflann::round<CentersType>( mean[j] / static_cast<double>(indices_length) );
  630. }
  631. variance /= static_cast<DistanceType>( length );
  632. variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
  633. DistanceType radius = 0;
  634. for (unsigned int i=0; i<indices_length; ++i) {
  635. DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
  636. if (tmp>radius) {
  637. radius = tmp;
  638. }
  639. }
  640. node->variance = variance;
  641. node->radius = radius;
  642. node->pivot = mean;
  643. }
  644. void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices,
  645. unsigned int indices_length)
  646. {
  647. const unsigned int accumulator_veclen = static_cast<unsigned int>(
  648. veclen_*sizeof(CentersType)*BITS_PER_CHAR);
  649. unsigned long long variance = 0ull;
  650. CentersType* mean = new CentersType[veclen_];
  651. memoryCounter_ += int(veclen_*sizeof(CentersType));
  652. unsigned int* mean_accumulator = new unsigned int[accumulator_veclen];
  653. memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen);
  654. for (unsigned int i=0; i<indices_length; ++i) {
  655. variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
  656. distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
  657. unsigned char* vec = (unsigned char*)dataset_[indices[i]];
  658. for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
  659. mean_accumulator[k] += (vec[l]) & 0x01;
  660. mean_accumulator[k+1] += (vec[l]>>1) & 0x01;
  661. mean_accumulator[k+2] += (vec[l]>>2) & 0x01;
  662. mean_accumulator[k+3] += (vec[l]>>3) & 0x01;
  663. mean_accumulator[k+4] += (vec[l]>>4) & 0x01;
  664. mean_accumulator[k+5] += (vec[l]>>5) & 0x01;
  665. mean_accumulator[k+6] += (vec[l]>>6) & 0x01;
  666. mean_accumulator[k+7] += (vec[l]>>7) & 0x01;
  667. }
  668. }
  669. double cnt = static_cast<double>(indices_length);
  670. unsigned char* char_mean = (unsigned char*)mean;
  671. for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
  672. char_mean[l] = static_cast<unsigned char>(
  673. (((int)(0.5 + (double)(mean_accumulator[k]) / cnt)))
  674. | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1)
  675. | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2)
  676. | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3)
  677. | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4)
  678. | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5)
  679. | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6)
  680. | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7));
  681. }
  682. variance = static_cast<unsigned long long>(
  683. 0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
  684. variance -= static_cast<unsigned long long>(
  685. ensureSquareDistance<Distance>(
  686. distance_(mean, ZeroIterator<ElementType>(), veclen_)));
  687. DistanceType radius = 0;
  688. for (unsigned int i=0; i<indices_length; ++i) {
  689. DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
  690. if (tmp>radius) {
  691. radius = tmp;
  692. }
  693. }
  694. node->variance = static_cast<DistanceType>(variance);
  695. node->radius = radius;
  696. node->pivot = mean;
  697. delete[] mean_accumulator;
  698. }
  699. void computeDnaNodeStatistics(KMeansNodePtr node, int* indices,
  700. unsigned int indices_length)
  701. {
  702. const unsigned int histos_veclen = static_cast<unsigned int>(
  703. veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
  704. unsigned long long variance = 0ull;
  705. unsigned int* histograms = new unsigned int[histos_veclen];
  706. memset(histograms, 0, sizeof(unsigned int)*histos_veclen);
  707. for (unsigned int i=0; i<indices_length; ++i) {
  708. variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
  709. distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
  710. unsigned char* vec = (unsigned char*)dataset_[indices[i]];
  711. for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
  712. histograms[k + ((vec[l]) & 0x03)]++;
  713. histograms[k + 4 + ((vec[l]>>2) & 0x03)]++;
  714. histograms[k + 8 + ((vec[l]>>4) & 0x03)]++;
  715. histograms[k +12 + ((vec[l]>>6) & 0x03)]++;
  716. }
  717. }
  718. CentersType* mean = new CentersType[veclen_];
  719. memoryCounter_ += int(veclen_*sizeof(CentersType));
  720. unsigned char* char_mean = (unsigned char*)mean;
  721. unsigned int* h = histograms;
  722. for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
  723. char_mean[l] = (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10
  724. : h[k] > h[k+3] ? 0x00 : 0x11
  725. : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
  726. : h[k+1] > h[k+3] ? 0x01 : 0x11)
  727. | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000
  728. : h[k+4] > h[k+7] ? 0x00 : 0x1100
  729. : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
  730. : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
  731. | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000
  732. : h[k+8] >h[k+11] ? 0x00 : 0x110000
  733. : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
  734. : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
  735. | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000
  736. : h[k+12] >h[k+15] ? 0x00 : 0x11000000
  737. : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
  738. : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
  739. }
  740. variance = static_cast<unsigned long long>(
  741. 0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
  742. variance -= static_cast<unsigned long long>(
  743. ensureSquareDistance<Distance>(
  744. distance_(mean, ZeroIterator<ElementType>(), veclen_)));
  745. DistanceType radius = 0;
  746. for (unsigned int i=0; i<indices_length; ++i) {
  747. DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
  748. if (tmp>radius) {
  749. radius = tmp;
  750. }
  751. }
  752. node->variance = static_cast<DistanceType>(variance);
  753. node->radius = radius;
  754. node->pivot = mean;
  755. delete[] histograms;
  756. }
  757. template<typename DistType>
  758. void computeNodeStatistics(KMeansNodePtr node, int* indices,
  759. unsigned int indices_length,
  760. const DistType* identifier)
  761. {
  762. (void)identifier;
  763. computeNodeStatistics(node, indices, indices_length);
  764. }
  765. void computeNodeStatistics(KMeansNodePtr node, int* indices,
  766. unsigned int indices_length,
  767. const cvflann::HammingLUT* identifier)
  768. {
  769. (void)identifier;
  770. computeBitfieldNodeStatistics(node, indices, indices_length);
  771. }
  772. void computeNodeStatistics(KMeansNodePtr node, int* indices,
  773. unsigned int indices_length,
  774. const cvflann::Hamming<unsigned char>* identifier)
  775. {
  776. (void)identifier;
  777. computeBitfieldNodeStatistics(node, indices, indices_length);
  778. }
  779. void computeNodeStatistics(KMeansNodePtr node, int* indices,
  780. unsigned int indices_length,
  781. const cvflann::Hamming2<unsigned char>* identifier)
  782. {
  783. (void)identifier;
  784. computeBitfieldNodeStatistics(node, indices, indices_length);
  785. }
  786. void computeNodeStatistics(KMeansNodePtr node, int* indices,
  787. unsigned int indices_length,
  788. const cvflann::DNAmmingLUT* identifier)
  789. {
  790. (void)identifier;
  791. computeDnaNodeStatistics(node, indices, indices_length);
  792. }
  793. void computeNodeStatistics(KMeansNodePtr node, int* indices,
  794. unsigned int indices_length,
  795. const cvflann::DNAmming2<unsigned char>* identifier)
  796. {
  797. (void)identifier;
  798. computeDnaNodeStatistics(node, indices, indices_length);
  799. }
  800. void refineClustering(int* indices, int indices_length, int branching, CentersType** centers,
  801. std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
  802. {
  803. cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
  804. Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);
  805. bool converged = false;
  806. int iteration = 0;
  807. while (!converged && iteration<iterations_) {
  808. converged = true;
  809. iteration++;
  810. // compute the new cluster centers
  811. for (int i=0; i<branching; ++i) {
  812. memset(dcenters[i],0,sizeof(double)*veclen_);
  813. radiuses[i] = 0;
  814. }
  815. for (int i=0; i<indices_length; ++i) {
  816. ElementType* vec = dataset_[indices[i]];
  817. double* center = dcenters[belongs_to[i]];
  818. for (size_t k=0; k<veclen_; ++k) {
  819. center[k] += vec[k];
  820. }
  821. }
  822. for (int i=0; i<branching; ++i) {
  823. int cnt = count[i];
  824. for (size_t k=0; k<veclen_; ++k) {
  825. dcenters[i][k] /= cnt;
  826. }
  827. }
  828. std::vector<int> new_centroids(indices_length);
  829. std::vector<DistanceType> sq_dists(indices_length);
  830. // reassign points to clusters
  831. KMeansDistanceComputer<Matrix<double> > invoker(
  832. distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
  833. parallel_for_(cv::Range(0, (int)indices_length), invoker);
  834. for (int i=0; i < (int)indices_length; ++i) {
  835. DistanceType sq_dist(sq_dists[i]);
  836. int new_centroid(new_centroids[i]);
  837. if (sq_dist > radiuses[new_centroid]) {
  838. radiuses[new_centroid] = sq_dist;
  839. }
  840. if (new_centroid != belongs_to[i]) {
  841. count[belongs_to[i]]--;
  842. count[new_centroid]++;
  843. belongs_to[i] = new_centroid;
  844. converged = false;
  845. }
  846. }
  847. for (int i=0; i<branching; ++i) {
  848. // if one cluster converges to an empty cluster,
  849. // move an element into that cluster
  850. if (count[i]==0) {
  851. int j = (i+1)%branching;
  852. while (count[j]<=1) {
  853. j = (j+1)%branching;
  854. }
  855. for (int k=0; k<indices_length; ++k) {
  856. if (belongs_to[k]==j) {
  857. // for cluster j, we move the furthest element from the center to the empty cluster i
  858. if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
  859. belongs_to[k] = i;
  860. count[j]--;
  861. count[i]++;
  862. break;
  863. }
  864. }
  865. }
  866. converged = false;
  867. }
  868. }
  869. }
  870. for (int i=0; i<branching; ++i) {
  871. centers[i] = new CentersType[veclen_];
  872. memoryCounter_ += (int)(veclen_*sizeof(CentersType));
  873. for (size_t k=0; k<veclen_; ++k) {
  874. centers[i][k] = (CentersType)dcenters[i][k];
  875. }
  876. }
  877. }
  878. void refineBitfieldClustering(int* indices, int indices_length, int branching, CentersType** centers,
  879. std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
  880. {
  881. for (int i=0; i<branching; ++i) {
  882. centers[i] = new CentersType[veclen_];
  883. memoryCounter_ += (int)(veclen_*sizeof(CentersType));
  884. }
  885. const unsigned int accumulator_veclen = static_cast<unsigned int>(
  886. veclen_*sizeof(ElementType)*BITS_PER_CHAR);
  887. cv::AutoBuffer<unsigned int> dcenters_buf(branching*accumulator_veclen);
  888. Matrix<unsigned int> dcenters(dcenters_buf.data(), branching, accumulator_veclen);
  889. bool converged = false;
  890. int iteration = 0;
  891. while (!converged && iteration<iterations_) {
  892. converged = true;
  893. iteration++;
  894. // compute the new cluster centers
  895. for (int i=0; i<branching; ++i) {
  896. memset(dcenters[i],0,sizeof(unsigned int)*accumulator_veclen);
  897. radiuses[i] = 0;
  898. }
  899. for (int i=0; i<indices_length; ++i) {
  900. unsigned char* vec = (unsigned char*)dataset_[indices[i]];
  901. unsigned int* dcenter = dcenters[belongs_to[i]];
  902. for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
  903. dcenter[k] += (vec[l]) & 0x01;
  904. dcenter[k+1] += (vec[l]>>1) & 0x01;
  905. dcenter[k+2] += (vec[l]>>2) & 0x01;
  906. dcenter[k+3] += (vec[l]>>3) & 0x01;
  907. dcenter[k+4] += (vec[l]>>4) & 0x01;
  908. dcenter[k+5] += (vec[l]>>5) & 0x01;
  909. dcenter[k+6] += (vec[l]>>6) & 0x01;
  910. dcenter[k+7] += (vec[l]>>7) & 0x01;
  911. }
  912. }
  913. for (int i=0; i<branching; ++i) {
  914. double cnt = static_cast<double>(count[i]);
  915. unsigned int* dcenter = dcenters[i];
  916. unsigned char* charCenter = (unsigned char*)centers[i];
  917. for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
  918. charCenter[l] = static_cast<unsigned char>(
  919. (((int)(0.5 + (double)(dcenter[k]) / cnt)))
  920. | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1)
  921. | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2)
  922. | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3)
  923. | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4)
  924. | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5)
  925. | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6)
  926. | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7));
  927. }
  928. }
  929. std::vector<int> new_centroids(indices_length);
  930. std::vector<DistanceType> dists(indices_length);
  931. // reassign points to clusters
  932. KMeansDistanceComputer<ElementType**> invoker(
  933. distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
  934. parallel_for_(cv::Range(0, (int)indices_length), invoker);
  935. for (int i=0; i < indices_length; ++i) {
  936. DistanceType dist(dists[i]);
  937. int new_centroid(new_centroids[i]);
  938. if (dist > radiuses[new_centroid]) {
  939. radiuses[new_centroid] = dist;
  940. }
  941. if (new_centroid != belongs_to[i]) {
  942. count[belongs_to[i]]--;
  943. count[new_centroid]++;
  944. belongs_to[i] = new_centroid;
  945. converged = false;
  946. }
  947. }
  948. for (int i=0; i<branching; ++i) {
  949. // if one cluster converges to an empty cluster,
  950. // move an element into that cluster
  951. if (count[i]==0) {
  952. int j = (i+1)%branching;
  953. while (count[j]<=1) {
  954. j = (j+1)%branching;
  955. }
  956. for (int k=0; k<indices_length; ++k) {
  957. if (belongs_to[k]==j) {
  958. // for cluster j, we move the furthest element from the center to the empty cluster i
  959. if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
  960. belongs_to[k] = i;
  961. count[j]--;
  962. count[i]++;
  963. break;
  964. }
  965. }
  966. }
  967. converged = false;
  968. }
  969. }
  970. }
  971. }
  972. void refineDnaClustering(int* indices, int indices_length, int branching, CentersType** centers,
  973. std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
  974. {
  975. for (int i=0; i<branching; ++i) {
  976. centers[i] = new CentersType[veclen_];
  977. memoryCounter_ += (int)(veclen_*sizeof(CentersType));
  978. }
  979. const unsigned int histos_veclen = static_cast<unsigned int>(
  980. veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
  981. cv::AutoBuffer<unsigned int> histos_buf(branching*histos_veclen);
  982. Matrix<unsigned int> histos(histos_buf.data(), branching, histos_veclen);
  983. bool converged = false;
  984. int iteration = 0;
  985. while (!converged && iteration<iterations_) {
  986. converged = true;
  987. iteration++;
  988. // compute the new cluster centers
  989. for (int i=0; i<branching; ++i) {
  990. memset(histos[i],0,sizeof(unsigned int)*histos_veclen);
  991. radiuses[i] = 0;
  992. }
  993. for (int i=0; i<indices_length; ++i) {
  994. unsigned char* vec = (unsigned char*)dataset_[indices[i]];
  995. unsigned int* h = histos[belongs_to[i]];
  996. for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
  997. h[k + ((vec[l]) & 0x03)]++;
  998. h[k + 4 + ((vec[l]>>2) & 0x03)]++;
  999. h[k + 8 + ((vec[l]>>4) & 0x03)]++;
  1000. h[k +12 + ((vec[l]>>6) & 0x03)]++;
  1001. }
  1002. }
  1003. for (int i=0; i<branching; ++i) {
  1004. unsigned int* h = histos[i];
  1005. unsigned char* charCenter = (unsigned char*)centers[i];
  1006. for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
  1007. charCenter[l]= (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10
  1008. : h[k] > h[k+3] ? 0x00 : 0x11
  1009. : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
  1010. : h[k+1] > h[k+3] ? 0x01 : 0x11)
  1011. | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000
  1012. : h[k+4] > h[k+7] ? 0x00 : 0x1100
  1013. : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
  1014. : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
  1015. | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000
  1016. : h[k+8] >h[k+11] ? 0x00 : 0x110000
  1017. : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
  1018. : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
  1019. | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000
  1020. : h[k+12] >h[k+15] ? 0x00 : 0x11000000
  1021. : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
  1022. : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
  1023. }
  1024. }
  1025. std::vector<int> new_centroids(indices_length);
  1026. std::vector<DistanceType> dists(indices_length);
  1027. // reassign points to clusters
  1028. KMeansDistanceComputer<ElementType**> invoker(
  1029. distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
  1030. parallel_for_(cv::Range(0, (int)indices_length), invoker);
  1031. for (int i=0; i < indices_length; ++i) {
  1032. DistanceType dist(dists[i]);
  1033. int new_centroid(new_centroids[i]);
  1034. if (dist > radiuses[new_centroid]) {
  1035. radiuses[new_centroid] = dist;
  1036. }
  1037. if (new_centroid != belongs_to[i]) {
  1038. count[belongs_to[i]]--;
  1039. count[new_centroid]++;
  1040. belongs_to[i] = new_centroid;
  1041. converged = false;
  1042. }
  1043. }
  1044. for (int i=0; i<branching; ++i) {
  1045. // if one cluster converges to an empty cluster,
  1046. // move an element into that cluster
  1047. if (count[i]==0) {
  1048. int j = (i+1)%branching;
  1049. while (count[j]<=1) {
  1050. j = (j+1)%branching;
  1051. }
  1052. for (int k=0; k<indices_length; ++k) {
  1053. if (belongs_to[k]==j) {
  1054. // for cluster j, we move the furthest element from the center to the empty cluster i
  1055. if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
  1056. belongs_to[k] = i;
  1057. count[j]--;
  1058. count[i]++;
  1059. break;
  1060. }
  1061. }
  1062. }
  1063. converged = false;
  1064. }
  1065. }
  1066. }
  1067. }
  1068. void computeSubClustering(KMeansNodePtr node, int* indices, int indices_length,
  1069. int branching, int level, CentersType** centers,
  1070. std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
  1071. {
  1072. // compute kmeans clustering for each of the resulting clusters
  1073. node->childs = pool_.allocate<KMeansNodePtr>(branching);
  1074. int start = 0;
  1075. int end = start;
  1076. for (int c=0; c<branching; ++c) {
  1077. int s = count[c];
  1078. DistanceType variance = 0;
  1079. DistanceType mean_radius =0;
  1080. for (int i=0; i<indices_length; ++i) {
  1081. if (belongs_to[i]==c) {
  1082. DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
  1083. variance += d;
  1084. mean_radius += static_cast<DistanceType>( sqrt(d) );
  1085. std::swap(indices[i],indices[end]);
  1086. std::swap(belongs_to[i],belongs_to[end]);
  1087. end++;
  1088. }
  1089. }
  1090. variance /= s;
  1091. mean_radius /= s;
  1092. variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
  1093. node->childs[c] = pool_.allocate<KMeansNode>();
  1094. std::memset(node->childs[c], 0, sizeof(KMeansNode));
  1095. node->childs[c]->radius = radiuses[c];
  1096. node->childs[c]->pivot = centers[c];
  1097. node->childs[c]->variance = variance;
  1098. node->childs[c]->mean_radius = mean_radius;
  1099. computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
  1100. start=end;
  1101. }
  1102. }
  1103. void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length,
  1104. int branching, int level, CentersType** centers,
  1105. std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
  1106. {
  1107. // compute kmeans clustering for each of the resulting clusters
  1108. node->childs = pool_.allocate<KMeansNodePtr>(branching);
  1109. int start = 0;
  1110. int end = start;
  1111. for (int c=0; c<branching; ++c) {
  1112. int s = count[c];
  1113. unsigned long long variance = 0ull;
  1114. DistanceType mean_radius =0;
  1115. for (int i=0; i<indices_length; ++i) {
  1116. if (belongs_to[i]==c) {
  1117. DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
  1118. variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(d) );
  1119. mean_radius += ensureSimpleDistance<Distance>(d);
  1120. std::swap(indices[i],indices[end]);
  1121. std::swap(belongs_to[i],belongs_to[end]);
  1122. end++;
  1123. }
  1124. }
  1125. mean_radius = static_cast<DistanceType>(
  1126. 0.5f + static_cast<float>(mean_radius) / static_cast<float>(s));
  1127. variance = static_cast<unsigned long long>(
  1128. 0.5 + static_cast<double>(variance) / static_cast<double>(s));
  1129. variance -= static_cast<unsigned long long>(
  1130. ensureSquareDistance<Distance>(
  1131. distance_(centers[c], ZeroIterator<ElementType>(), veclen_)));
  1132. node->childs[c] = pool_.allocate<KMeansNode>();
  1133. std::memset(node->childs[c], 0, sizeof(KMeansNode));
  1134. node->childs[c]->radius = radiuses[c];
  1135. node->childs[c]->pivot = centers[c];
  1136. node->childs[c]->variance = static_cast<DistanceType>(variance);
  1137. node->childs[c]->mean_radius = mean_radius;
  1138. computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
  1139. start=end;
  1140. }
  1141. }
  1142. template<typename DistType>
  1143. void refineAndSplitClustering(
  1144. KMeansNodePtr node, int* indices, int indices_length, int branching,
  1145. int level, CentersType** centers, std::vector<DistanceType>& radiuses,
  1146. int* belongs_to, int* count, const DistType* identifier)
  1147. {
  1148. (void)identifier;
  1149. refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count);
  1150. computeSubClustering(node, indices, indices_length, branching,
  1151. level, centers, radiuses, belongs_to, count);
  1152. }
  1153. /**
  1154. * The methods responsible with doing the recursive hierarchical clustering on
  1155. * binary vectors.
  1156. * As some might have heard that KMeans on binary data doesn't make sense,
  1157. * it's worth a little explanation why it actually fairly works. As
  1158. * with the Hierarchical Clustering algortihm, we seed several centers for the
  1159. * current node by picking some of its points. Then in a first pass each point
  1160. * of the node is then related to its closest center. Now let's have a look at
  1161. * the 5 central dimensions of the 9 following points:
  1162. *
  1163. * xxxxxx11100xxxxx (1)
  1164. * xxxxxx11010xxxxx (2)
  1165. * xxxxxx11001xxxxx (3)
  1166. * xxxxxx10110xxxxx (4)
  1167. * xxxxxx10101xxxxx (5)
  1168. * xxxxxx10011xxxxx (6)
  1169. * xxxxxx01110xxxxx (7)
  1170. * xxxxxx01101xxxxx (8)
  1171. * xxxxxx01011xxxxx (9)
  1172. * sum _____
  1173. * of 1: 66555
  1174. *
  1175. * Even if the barycenter notion doesn't apply, we can set a center
  1176. * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing
  1177. * on for these points.
  1178. *
  1179. * Note that convergence isn't ensured anymore. In practice, using Gonzales
  1180. * as seeding algorithm should be fine for getting convergence ("iterations"
  1181. * value can be set to -1). But with KMeans++ seeding you should definitely
  1182. * set a maximum number of iterations (but make it higher than the "iterations"
  1183. * default value of 11).
  1184. *
  1185. * Params:
  1186. * node = the node to cluster
  1187. * indices = indices of the points belonging to the current node
  1188. * indices_length = number of points in the current node
  1189. * branching = the branching factor to use in the clustering
  1190. * level = 0 for the root node, it increases with the subdivision levels
  1191. * centers = clusters centers to compute
  1192. * radiuses = radiuses of clusters
  1193. * belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to
  1194. * count = array storing the number of indices for a given center id
  1195. * identifier = dummy pointer on an instance of Distance (use to branch correctly among templates)
  1196. */
  1197. void refineAndSplitClustering(
  1198. KMeansNodePtr node, int* indices, int indices_length, int branching,
  1199. int level, CentersType** centers, std::vector<DistanceType>& radiuses,
  1200. int* belongs_to, int* count, const cvflann::HammingLUT* identifier)
  1201. {
  1202. (void)identifier;
  1203. refineBitfieldClustering(
  1204. indices, indices_length, branching, centers, radiuses, belongs_to, count);
  1205. computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
  1206. level, centers, radiuses, belongs_to, count);
  1207. }
  1208. void refineAndSplitClustering(
  1209. KMeansNodePtr node, int* indices, int indices_length, int branching,
  1210. int level, CentersType** centers, std::vector<DistanceType>& radiuses,
  1211. int* belongs_to, int* count, const cvflann::Hamming<unsigned char>* identifier)
  1212. {
  1213. (void)identifier;
  1214. refineBitfieldClustering(
  1215. indices, indices_length, branching, centers, radiuses, belongs_to, count);
  1216. computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
  1217. level, centers, radiuses, belongs_to, count);
  1218. }
  1219. void refineAndSplitClustering(
  1220. KMeansNodePtr node, int* indices, int indices_length, int branching,
  1221. int level, CentersType** centers, std::vector<DistanceType>& radiuses,
  1222. int* belongs_to, int* count, const cvflann::Hamming2<unsigned char>* identifier)
  1223. {
  1224. (void)identifier;
  1225. refineBitfieldClustering(
  1226. indices, indices_length, branching, centers, radiuses, belongs_to, count);
  1227. computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
  1228. level, centers, radiuses, belongs_to, count);
  1229. }
  1230. void refineAndSplitClustering(
  1231. KMeansNodePtr node, int* indices, int indices_length, int branching,
  1232. int level, CentersType** centers, std::vector<DistanceType>& radiuses,
  1233. int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier)
  1234. {
  1235. (void)identifier;
  1236. refineDnaClustering(
  1237. indices, indices_length, branching, centers, radiuses, belongs_to, count);
  1238. computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
  1239. level, centers, radiuses, belongs_to, count);
  1240. }
  1241. void refineAndSplitClustering(
  1242. KMeansNodePtr node, int* indices, int indices_length, int branching,
  1243. int level, CentersType** centers, std::vector<DistanceType>& radiuses,
  1244. int* belongs_to, int* count, const cvflann::DNAmming2<unsigned char>* identifier)
  1245. {
  1246. (void)identifier;
  1247. refineDnaClustering(
  1248. indices, indices_length, branching, centers, radiuses, belongs_to, count);
  1249. computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
  1250. level, centers, radiuses, belongs_to, count);
  1251. }
  1252. /**
  1253. * The method responsible with actually doing the recursive hierarchical
  1254. * clustering
  1255. *
  1256. * Params:
  1257. * node = the node to cluster
  1258. * indices = indices of the points belonging to the current node
  1259. * branching = the branching factor to use in the clustering
  1260. *
  1261. * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
  1262. */
  1263. void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
  1264. {
  1265. node->size = indices_length;
  1266. node->level = level;
  1267. if (indices_length < branching) {
  1268. node->indices = indices;
  1269. std::sort(node->indices,node->indices+indices_length);
  1270. node->childs = NULL;
  1271. return;
  1272. }
  1273. cv::AutoBuffer<int> centers_idx_buf(branching);
  1274. int* centers_idx = centers_idx_buf.data();
  1275. int centers_length;
  1276. (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
  1277. if (centers_length<branching) {
  1278. node->indices = indices;
  1279. std::sort(node->indices,node->indices+indices_length);
  1280. node->childs = NULL;
  1281. return;
  1282. }
  1283. std::vector<DistanceType> radiuses(branching);
  1284. cv::AutoBuffer<int> count_buf(branching);
  1285. int* count = count_buf.data();
  1286. for (int i=0; i<branching; ++i) {
  1287. radiuses[i] = 0;
  1288. count[i] = 0;
  1289. }
  1290. // assign points to clusters
  1291. cv::AutoBuffer<int> belongs_to_buf(indices_length);
  1292. int* belongs_to = belongs_to_buf.data();
  1293. for (int i=0; i<indices_length; ++i) {
  1294. DistanceType sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[0]], veclen_);
  1295. belongs_to[i] = 0;
  1296. for (int j=1; j<branching; ++j) {
  1297. DistanceType new_sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[j]], veclen_);
  1298. if (sq_dist>new_sq_dist) {
  1299. belongs_to[i] = j;
  1300. sq_dist = new_sq_dist;
  1301. }
  1302. }
  1303. if (sq_dist>radiuses[belongs_to[i]]) {
  1304. radiuses[belongs_to[i]] = sq_dist;
  1305. }
  1306. count[belongs_to[i]]++;
  1307. }
  1308. CentersType** centers = new CentersType*[branching];
  1309. Distance* dummy = NULL;
  1310. refineAndSplitClustering(node, indices, indices_length, branching, level,
  1311. centers, radiuses, belongs_to, count, dummy);
  1312. delete[] centers;
  1313. }
  1314. /**
  1315. * Performs one descent in the hierarchical k-means tree. The branches not
  1316. * visited are stored in a priority queue.
  1317. *
  1318. * Params:
  1319. * node = node to explore
  1320. * result = container for the k-nearest neighbors found
  1321. * vec = query points
  1322. * checks = how many points in the dataset have been checked so far
  1323. * maxChecks = maximum dataset points to checks
  1324. */
  1325. void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
  1326. const cv::Ptr<Heap<BranchSt>>& heap)
  1327. {
  1328. // Ignore those clusters that are too far away
  1329. {
  1330. DistanceType bsq = distance_(vec, node->pivot, veclen_);
  1331. DistanceType rsq = node->radius;
  1332. DistanceType wsq = result.worstDist();
  1333. if (isSquareDistance<Distance>())
  1334. {
  1335. DistanceType val = bsq-rsq-wsq;
  1336. if ((val>0) && (val*val > 4*rsq*wsq))
  1337. return;
  1338. }
  1339. else
  1340. {
  1341. if (bsq-rsq > wsq)
  1342. return;
  1343. }
  1344. }
  1345. if (node->childs==NULL) {
  1346. if ((checks>=maxChecks) && result.full()) {
  1347. return;
  1348. }
  1349. checks += node->size;
  1350. for (int i=0; i<node->size; ++i) {
  1351. int index = node->indices[i];
  1352. DistanceType dist = distance_(dataset_[index], vec, veclen_);
  1353. result.addPoint(dist, index);
  1354. }
  1355. }
  1356. else {
  1357. DistanceType* domain_distances = new DistanceType[branching_];
  1358. int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
  1359. delete[] domain_distances;
  1360. findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
  1361. }
  1362. }
  1363. /**
  1364. * Helper function that computes the nearest childs of a node to a given query point.
  1365. * Params:
  1366. * node = the node
  1367. * q = the query point
  1368. * distances = array with the distances to each child node.
  1369. * Returns:
  1370. */
  1371. int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr<Heap<BranchSt>>& heap)
  1372. {
  1373. int best_index = 0;
  1374. domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
  1375. for (int i=1; i<branching_; ++i) {
  1376. domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
  1377. if (domain_distances[i]<domain_distances[best_index]) {
  1378. best_index = i;
  1379. }
  1380. }
  1381. // float* best_center = node->childs[best_index]->pivot;
  1382. for (int i=0; i<branching_; ++i) {
  1383. if (i != best_index) {
  1384. domain_distances[i] -= cvflann::round<DistanceType>(
  1385. cb_index_*node->childs[i]->variance );
  1386. // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
  1387. // if (domain_distances[i]<dist_to_border) {
  1388. // domain_distances[i] = dist_to_border;
  1389. // }
  1390. heap->insert(BranchSt(node->childs[i],domain_distances[i]));
  1391. }
  1392. }
  1393. return best_index;
  1394. }
  1395. /**
  1396. * Function the performs exact nearest neighbor search by traversing the entire tree.
  1397. */
  1398. void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
  1399. {
  1400. // Ignore those clusters that are too far away
  1401. {
  1402. DistanceType bsq = distance_(vec, node->pivot, veclen_);
  1403. DistanceType rsq = node->radius;
  1404. DistanceType wsq = result.worstDist();
  1405. if (isSquareDistance<Distance>())
  1406. {
  1407. DistanceType val = bsq-rsq-wsq;
  1408. if ((val>0) && (val*val > 4*rsq*wsq))
  1409. return;
  1410. }
  1411. else
  1412. {
  1413. if (bsq-rsq > wsq)
  1414. return;
  1415. }
  1416. }
  1417. if (node->childs==NULL) {
  1418. for (int i=0; i<node->size; ++i) {
  1419. int index = node->indices[i];
  1420. DistanceType dist = distance_(dataset_[index], vec, veclen_);
  1421. result.addPoint(dist, index);
  1422. }
  1423. }
  1424. else {
  1425. int* sort_indices = new int[branching_];
  1426. getCenterOrdering(node, vec, sort_indices);
  1427. for (int i=0; i<branching_; ++i) {
  1428. findExactNN(node->childs[sort_indices[i]],result,vec);
  1429. }
  1430. delete[] sort_indices;
  1431. }
  1432. }
  1433. /**
  1434. * Helper function.
  1435. *
  1436. * I computes the order in which to traverse the child nodes of a particular node.
  1437. */
  1438. void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
  1439. {
  1440. DistanceType* domain_distances = new DistanceType[branching_];
  1441. for (int i=0; i<branching_; ++i) {
  1442. DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
  1443. int j=0;
  1444. while (domain_distances[j]<dist && j<i)
  1445. j++;
  1446. for (int k=i; k>j; --k) {
  1447. domain_distances[k] = domain_distances[k-1];
  1448. sort_indices[k] = sort_indices[k-1];
  1449. }
  1450. domain_distances[j] = dist;
  1451. sort_indices[j] = i;
  1452. }
  1453. delete[] domain_distances;
  1454. }
  1455. /**
  1456. * Method that computes the squared distance from the query point q
  1457. * from inside region with center c to the border between this
  1458. * region and the region with center p
  1459. */
  1460. DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
  1461. {
  1462. DistanceType sum = 0;
  1463. DistanceType sum2 = 0;
  1464. for (int i=0; i<veclen_; ++i) {
  1465. DistanceType t = c[i]-p[i];
  1466. sum += t*(q[i]-(c[i]+p[i])/2);
  1467. sum2 += t*t;
  1468. }
  1469. return sum*sum/sum2;
  1470. }
  1471. /**
  1472. * Helper function the descends in the hierarchical k-means tree by splitting those clusters that minimize
  1473. * the overall variance of the clustering.
  1474. * Params:
  1475. * root = root node
  1476. * clusters = array with clusters centers (return value)
  1477. * varianceValue = variance of the clustering (return value)
  1478. * Returns:
  1479. */
  1480. int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
  1481. {
  1482. int clusterCount = 1;
  1483. clusters[0] = root;
  1484. DistanceType meanVariance = root->variance*root->size;
  1485. while (clusterCount<clusters_length) {
  1486. DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
  1487. int splitIndex = -1;
  1488. for (int i=0; i<clusterCount; ++i) {
  1489. if (clusters[i]->childs != NULL) {
  1490. DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;
  1491. for (int j=0; j<branching_; ++j) {
  1492. variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
  1493. }
  1494. if (variance<minVariance) {
  1495. minVariance = variance;
  1496. splitIndex = i;
  1497. }
  1498. }
  1499. }
  1500. if (splitIndex==-1) break;
  1501. if ( (branching_+clusterCount-1) > clusters_length) break;
  1502. meanVariance = minVariance;
  1503. // split node
  1504. KMeansNodePtr toSplit = clusters[splitIndex];
  1505. clusters[splitIndex] = toSplit->childs[0];
  1506. for (int i=1; i<branching_; ++i) {
  1507. clusters[clusterCount++] = toSplit->childs[i];
  1508. }
  1509. }
  1510. varianceValue = meanVariance/root->size;
  1511. return clusterCount;
  1512. }
  1513. private:
  1514. /** The branching factor used in the hierarchical k-means clustering */
  1515. int branching_;
  1516. /** Number of kmeans trees (default is one) */
  1517. int trees_;
  1518. /** Maximum number of iterations to use when performing k-means clustering */
  1519. int iterations_;
  1520. /** Algorithm for choosing the cluster centers */
  1521. flann_centers_init_t centers_init_;
  1522. /**
  1523. * Cluster border index. This is used in the tree search phase when determining
  1524. * the closest cluster to explore next. A zero value takes into account only
  1525. * the cluster centres, a value greater then zero also take into account the size
  1526. * of the cluster.
  1527. */
  1528. float cb_index_;
  1529. /**
  1530. * The dataset used by this index
  1531. */
  1532. const Matrix<ElementType> dataset_;
  1533. /** Index parameters */
  1534. IndexParams index_params_;
  1535. /**
  1536. * Number of features in the dataset.
  1537. */
  1538. size_t size_;
  1539. /**
  1540. * Length of each feature.
  1541. */
  1542. size_t veclen_;
  1543. /**
  1544. * The root node in the tree.
  1545. */
  1546. KMeansNodePtr* root_;
  1547. /**
  1548. * Array of indices to vectors in the dataset.
  1549. */
  1550. int** indices_;
  1551. /**
  1552. * The distance
  1553. */
  1554. Distance distance_;
  1555. /**
  1556. * Pooled memory allocator.
  1557. */
  1558. PooledAllocator pool_;
  1559. /**
  1560. * Memory occupied by the index.
  1561. */
  1562. int memoryCounter_;
  1563. };
  1564. }
  1565. //! @endcond
  1566. #endif //OPENCV_FLANN_KMEANS_INDEX_H_