EstervQrCode 1.1.1
Library for qr code manipulation
kmeans_index.h
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 
31 #ifndef OPENCV_FLANN_KMEANS_INDEX_H_
32 #define OPENCV_FLANN_KMEANS_INDEX_H_
33 
35 
36 #include <algorithm>
37 #include <map>
38 #include <limits>
39 #include <cmath>
40 
41 #include "general.h"
42 #include "nn_index.h"
43 #include "dist.h"
44 #include "matrix.h"
45 #include "result_set.h"
46 #include "heap.h"
47 #include "allocator.h"
48 #include "random.h"
49 #include "saving.h"
50 #include "logger.h"
51 
52 #define BITS_PER_CHAR 8
53 #define BITS_PER_BASE 2 // for DNA/RNA sequences
54 #define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE)
55 #define HISTOS_PER_BASE (1<<BITS_PER_BASE)
56 
57 
58 namespace cvflann
59 {
60 
61 struct KMeansIndexParams : public IndexParams
62 {
63  KMeansIndexParams(int branching = 32, int iterations = 11,
64  flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM,
65  float cb_index = 0.2, int trees = 1 )
66  {
67  (*this)["algorithm"] = FLANN_INDEX_KMEANS;
68  // branching factor
69  (*this)["branching"] = branching;
70  // max iterations to perform in one kmeans clustering (kmeans tree)
71  (*this)["iterations"] = iterations;
72  // algorithm used for picking the initial cluster centers for kmeans tree
73  (*this)["centers_init"] = centers_init;
74  // cluster boundary index. Used when searching the kmeans tree
75  (*this)["cb_index"] = cb_index;
76  // number of kmeans trees to search in
77  (*this)["trees"] = trees;
78  }
79 };
80 
81 
88 template <typename Distance>
89 class KMeansIndex : public NNIndex<Distance>
90 {
91 public:
92  typedef typename Distance::ElementType ElementType;
93  typedef typename Distance::ResultType DistanceType;
94  typedef typename Distance::CentersType CentersType;
95 
96  typedef typename Distance::is_kdtree_distance is_kdtree_distance;
97  typedef typename Distance::is_vector_space_distance is_vector_space_distance;
98 
99 
100 
101  typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&);
102 
106  centersAlgFunction chooseCenters;
107 
108 
109 
120  void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
121  {
122  UniqueRandom r(indices_length);
123 
124  int index;
125  for (index=0; index<k; ++index) {
126  bool duplicate = true;
127  int rnd;
128  while (duplicate) {
129  duplicate = false;
130  rnd = r.next();
131  if (rnd<0) {
132  centers_length = index;
133  return;
134  }
135 
136  centers[index] = indices[rnd];
137 
138  for (int j=0; j<index; ++j) {
139  DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols);
140  if (sq<1e-16) {
141  duplicate = true;
142  }
143  }
144  }
145  }
146 
147  centers_length = index;
148  }
149 
150 
161  void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
162  {
163  int n = indices_length;
164 
165  int rnd = rand_int(n);
166  CV_DbgAssert(rnd >=0 && rnd < n);
167 
168  centers[0] = indices[rnd];
169 
170  int index;
171  for (index=1; index<k; ++index) {
172 
173  int best_index = -1;
174  DistanceType best_val = 0;
175  for (int j=0; j<n; ++j) {
176  DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols);
177  for (int i=1; i<index; ++i) {
178  DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols);
179  if (tmp_dist<dist) {
180  dist = tmp_dist;
181  }
182  }
183  if (dist>best_val) {
184  best_val = dist;
185  best_index = j;
186  }
187  }
188  if (best_index!=-1) {
189  centers[index] = indices[best_index];
190  }
191  else {
192  break;
193  }
194  }
195  centers_length = index;
196  }
197 
198 
212  void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
213  {
214  int n = indices_length;
215 
216  double currentPot = 0;
217  DistanceType* closestDistSq = new DistanceType[n];
218 
219  // Choose one random center and set the closestDistSq values
220  int index = rand_int(n);
221  CV_DbgAssert(index >=0 && index < n);
222  centers[0] = indices[index];
223 
224  for (int i = 0; i < n; i++) {
225  closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
226  closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
227  currentPot += closestDistSq[i];
228  }
229 
230 
231  const int numLocalTries = 1;
232 
233  // Choose each center
234  int centerCount;
235  for (centerCount = 1; centerCount < k; centerCount++) {
236 
237  // Repeat several trials
238  double bestNewPot = -1;
239  int bestNewIndex = -1;
240  for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
241 
242  // Choose our center - have to be slightly careful to return a valid answer even accounting
243  // for possible rounding errors
244  double randVal = rand_double(currentPot);
245  for (index = 0; index < n-1; index++) {
246  if (randVal <= closestDistSq[index]) break;
247  else randVal -= closestDistSq[index];
248  }
249 
250  // Compute the new potential
251  double newPot = 0;
252  for (int i = 0; i < n; i++) {
253  DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
254  newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
255  }
256 
257  // Store the best result
258  if ((bestNewPot < 0)||(newPot < bestNewPot)) {
259  bestNewPot = newPot;
260  bestNewIndex = index;
261  }
262  }
263 
264  // Add the appropriate center
265  centers[centerCount] = indices[bestNewIndex];
266  currentPot = bestNewPot;
267  for (int i = 0; i < n; i++) {
268  DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols);
269  closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
270  }
271  }
272 
273  centers_length = centerCount;
274 
275  delete[] closestDistSq;
276  }
277 
278 
279 
280 public:
281 
282  flann_algorithm_t getType() const CV_OVERRIDE
283  {
284  return FLANN_INDEX_KMEANS;
285  }
286 
287  template<class CentersContainerType>
288  class KMeansDistanceComputer : public cv::ParallelLoopBody
289  {
290  public:
291  KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
292  const int _branching, const int* _indices, const CentersContainerType& _dcenters,
293  const size_t _veclen, std::vector<int> &_new_centroids,
294  std::vector<DistanceType> &_sq_dists)
295  : distance(_distance)
296  , dataset(_dataset)
297  , branching(_branching)
298  , indices(_indices)
299  , dcenters(_dcenters)
300  , veclen(_veclen)
301  , new_centroids(_new_centroids)
302  , sq_dists(_sq_dists)
303  {
304  }
305 
306  void operator()(const cv::Range& range) const CV_OVERRIDE
307  {
308  const int begin = range.start;
309  const int end = range.end;
310 
311  for( int i = begin; i<end; ++i)
312  {
313  DistanceType sq_dist(distance(dataset[indices[i]], dcenters[0], veclen));
314  int new_centroid(0);
315  for (int j=1; j<branching; ++j) {
316  DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
317  if (sq_dist>new_sq_dist) {
318  new_centroid = j;
319  sq_dist = new_sq_dist;
320  }
321  }
322  sq_dists[i] = sq_dist;
323  new_centroids[i] = new_centroid;
324  }
325  }
326 
327  private:
328  Distance distance;
329  const Matrix<ElementType>& dataset;
330  const int branching;
331  const int* indices;
332  const CentersContainerType& dcenters;
333  const size_t veclen;
334  std::vector<int> &new_centroids;
335  std::vector<DistanceType> &sq_dists;
336  KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
337  };
338 
346  KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
347  Distance d = Distance())
348  : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
349  {
350  memoryCounter_ = 0;
351 
352  size_ = dataset_.rows;
353  veclen_ = dataset_.cols;
354 
355  branching_ = get_param(params,"branching",32);
356  trees_ = get_param(params,"trees",1);
357  iterations_ = get_param(params,"iterations",11);
358  if (iterations_<0) {
359  iterations_ = (std::numeric_limits<int>::max)();
360  }
361  centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);
362 
363  if (centers_init_==FLANN_CENTERS_RANDOM) {
364  chooseCenters = &KMeansIndex::chooseCentersRandom;
365  }
366  else if (centers_init_==FLANN_CENTERS_GONZALES) {
367  chooseCenters = &KMeansIndex::chooseCentersGonzales;
368  }
369  else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
370  chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
371  }
372  else {
373  FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers.");
374  }
375  cb_index_ = 0.4f;
376 
377  root_ = new KMeansNodePtr[trees_];
378  indices_ = new int*[trees_];
379 
380  for (int i=0; i<trees_; ++i) {
381  root_[i] = NULL;
382  indices_[i] = NULL;
383  }
384  }
385 
386 
387  KMeansIndex(const KMeansIndex&);
388  KMeansIndex& operator=(const KMeansIndex&);
389 
390 
396  virtual ~KMeansIndex()
397  {
398  if (root_ != NULL) {
399  free_centers();
400  delete[] root_;
401  }
402  if (indices_!=NULL) {
403  free_indices();
404  delete[] indices_;
405  }
406  }
407 
411  size_t size() const CV_OVERRIDE
412  {
413  return size_;
414  }
415 
419  size_t veclen() const CV_OVERRIDE
420  {
421  return veclen_;
422  }
423 
424 
425  void set_cb_index( float index)
426  {
427  cb_index_ = index;
428  }
429 
434  int usedMemory() const CV_OVERRIDE
435  {
436  return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
437  }
438 
442  void buildIndex() CV_OVERRIDE
443  {
444  if (branching_<2) {
445  FLANN_THROW(cv::Error::StsError, "Branching factor must be at least 2");
446  }
447 
448  free_indices();
449 
450  for (int i=0; i<trees_; ++i) {
451  indices_[i] = new int[size_];
452  for (size_t j=0; j<size_; ++j) {
453  indices_[i][j] = int(j);
454  }
455  root_[i] = pool_.allocate<KMeansNode>();
456  std::memset(root_[i], 0, sizeof(KMeansNode));
457 
458  Distance* dummy = NULL;
459  computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy);
460 
461  computeClustering(root_[i], indices_[i], (int)size_, branching_,0);
462  }
463  }
464 
465 
466  void saveIndex(FILE* stream) CV_OVERRIDE
467  {
468  save_value(stream, branching_);
469  save_value(stream, iterations_);
470  save_value(stream, memoryCounter_);
471  save_value(stream, cb_index_);
472  save_value(stream, trees_);
473  for (int i=0; i<trees_; ++i) {
474  save_value(stream, *indices_[i], (int)size_);
475  save_tree(stream, root_[i], i);
476  }
477  }
478 
479 
480  void loadIndex(FILE* stream) CV_OVERRIDE
481  {
482  if (indices_!=NULL) {
483  free_indices();
484  delete[] indices_;
485  }
486  if (root_!=NULL) {
487  free_centers();
488  }
489 
490  load_value(stream, branching_);
491  load_value(stream, iterations_);
492  load_value(stream, memoryCounter_);
493  load_value(stream, cb_index_);
494  load_value(stream, trees_);
495 
496  indices_ = new int*[trees_];
497  for (int i=0; i<trees_; ++i) {
498  indices_[i] = new int[size_];
499  load_value(stream, *indices_[i], size_);
500  load_tree(stream, root_[i], i);
501  }
502 
503  index_params_["algorithm"] = getType();
504  index_params_["branching"] = branching_;
505  index_params_["trees"] = trees_;
506  index_params_["iterations"] = iterations_;
507  index_params_["centers_init"] = centers_init_;
508  index_params_["cb_index"] = cb_index_;
509  }
510 
511 
521  void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
522  {
523 
524  const int maxChecks = get_param(searchParams,"checks",32);
525 
526  if (maxChecks==FLANN_CHECKS_UNLIMITED) {
527  findExactNN(root_[0], result, vec);
528  }
529  else {
530  // Priority queue storing intermediate branches in the best-bin-first search
531  const cv::Ptr<Heap<BranchSt>>& heap = Heap<BranchSt>::getPooledInstance(cv::utils::getThreadID(), (int)size_);
532 
533  int checks = 0;
534  for (int i=0; i<trees_; ++i) {
535  findNN(root_[i], result, vec, checks, maxChecks, heap);
536  if ((checks >= maxChecks) && result.full())
537  break;
538  }
539 
540  BranchSt branch;
541  while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
542  KMeansNodePtr node = branch.node;
543  findNN(node, result, vec, checks, maxChecks, heap);
544  }
545  CV_Assert(result.full());
546  }
547  }
548 
556  int getClusterCenters(Matrix<CentersType>& centers)
557  {
558  int numClusters = centers.rows;
559  if (numClusters<1) {
560  FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1");
561  }
562 
563  DistanceType variance;
564  KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
565 
566  int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance);
567 
568  Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
569 
570  for (int i=0; i<clusterCount; ++i) {
571  CentersType* center = clusters[i]->pivot;
572  for (size_t j=0; j<veclen_; ++j) {
573  centers[i][j] = center[j];
574  }
575  }
576  delete[] clusters;
577 
578  return clusterCount;
579  }
580 
581  IndexParams getParameters() const CV_OVERRIDE
582  {
583  return index_params_;
584  }
585 
586 
587 private:
591  struct KMeansNode
592  {
596  CentersType* pivot;
600  DistanceType radius;
604  DistanceType mean_radius;
608  DistanceType variance;
612  int size;
616  KMeansNode** childs;
620  int* indices;
624  int level;
625  };
626  typedef KMeansNode* KMeansNodePtr;
627 
631  typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;
632 
633 
634 
635 
636  void save_tree(FILE* stream, KMeansNodePtr node, int num)
637  {
638  save_value(stream, *node);
639  save_value(stream, *(node->pivot), (int)veclen_);
640  if (node->childs==NULL) {
641  int indices_offset = (int)(node->indices - indices_[num]);
642  save_value(stream, indices_offset);
643  }
644  else {
645  for(int i=0; i<branching_; ++i) {
646  save_tree(stream, node->childs[i], num);
647  }
648  }
649  }
650 
651 
652  void load_tree(FILE* stream, KMeansNodePtr& node, int num)
653  {
654  node = pool_.allocate<KMeansNode>();
655  load_value(stream, *node);
656  node->pivot = new CentersType[veclen_];
657  load_value(stream, *(node->pivot), (int)veclen_);
658  if (node->childs==NULL) {
659  int indices_offset;
660  load_value(stream, indices_offset);
661  node->indices = indices_[num] + indices_offset;
662  }
663  else {
664  node->childs = pool_.allocate<KMeansNodePtr>(branching_);
665  for(int i=0; i<branching_; ++i) {
666  load_tree(stream, node->childs[i], num);
667  }
668  }
669  }
670 
671 
675  void free_centers(KMeansNodePtr node)
676  {
677  delete[] node->pivot;
678  if (node->childs!=NULL) {
679  for (int k=0; k<branching_; ++k) {
680  free_centers(node->childs[k]);
681  }
682  }
683  }
684 
685  void free_centers()
686  {
687  if (root_ != NULL) {
688  for(int i=0; i<trees_; ++i) {
689  if (root_[i] != NULL) {
690  free_centers(root_[i]);
691  }
692  }
693  }
694  }
695 
699  void free_indices()
700  {
701  if (indices_!=NULL) {
702  for(int i=0; i<trees_; ++i) {
703  if (indices_[i]!=NULL) {
704  delete[] indices_[i];
705  indices_[i] = NULL;
706  }
707  }
708  }
709  }
710 
719  void computeNodeStatistics(KMeansNodePtr node, int* indices, unsigned int indices_length)
720  {
721  DistanceType variance = 0;
722  CentersType* mean = new CentersType[veclen_];
723  memoryCounter_ += int(veclen_*sizeof(CentersType));
724 
725  memset(mean,0,veclen_*sizeof(CentersType));
726 
727  for (unsigned int i=0; i<indices_length; ++i) {
728  ElementType* vec = dataset_[indices[i]];
729  for (size_t j=0; j<veclen_; ++j) {
730  mean[j] += vec[j];
731  }
732  variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
733  }
734  float length = static_cast<float>(indices_length);
735  for (size_t j=0; j<veclen_; ++j) {
736  mean[j] = cvflann::round<CentersType>( mean[j] / static_cast<double>(indices_length) );
737  }
738  variance /= static_cast<DistanceType>( length );
739  variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
740 
741  DistanceType radius = 0;
742  for (unsigned int i=0; i<indices_length; ++i) {
743  DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
744  if (tmp>radius) {
745  radius = tmp;
746  }
747  }
748 
749  node->variance = variance;
750  node->radius = radius;
751  node->pivot = mean;
752  }
753 
754 
755  void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices,
756  unsigned int indices_length)
757  {
758  const unsigned int accumulator_veclen = static_cast<unsigned int>(
759  veclen_*sizeof(CentersType)*BITS_PER_CHAR);
760 
761  unsigned long long variance = 0ull;
762  CentersType* mean = new CentersType[veclen_];
763  memoryCounter_ += int(veclen_*sizeof(CentersType));
764  unsigned int* mean_accumulator = new unsigned int[accumulator_veclen];
765 
766  memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen);
767 
768  for (unsigned int i=0; i<indices_length; ++i) {
769  variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
770  distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
771  unsigned char* vec = (unsigned char*)dataset_[indices[i]];
772  for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
773  mean_accumulator[k] += (vec[l]) & 0x01;
774  mean_accumulator[k+1] += (vec[l]>>1) & 0x01;
775  mean_accumulator[k+2] += (vec[l]>>2) & 0x01;
776  mean_accumulator[k+3] += (vec[l]>>3) & 0x01;
777  mean_accumulator[k+4] += (vec[l]>>4) & 0x01;
778  mean_accumulator[k+5] += (vec[l]>>5) & 0x01;
779  mean_accumulator[k+6] += (vec[l]>>6) & 0x01;
780  mean_accumulator[k+7] += (vec[l]>>7) & 0x01;
781  }
782  }
783  double cnt = static_cast<double>(indices_length);
784  unsigned char* char_mean = (unsigned char*)mean;
785  for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
786  char_mean[l] = static_cast<unsigned char>(
787  (((int)(0.5 + (double)(mean_accumulator[k]) / cnt)))
788  | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1)
789  | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2)
790  | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3)
791  | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4)
792  | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5)
793  | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6)
794  | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7));
795  }
796  variance = static_cast<unsigned long long>(
797  0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
798  variance -= static_cast<unsigned long long>(
799  ensureSquareDistance<Distance>(
800  distance_(mean, ZeroIterator<ElementType>(), veclen_)));
801 
802  DistanceType radius = 0;
803  for (unsigned int i=0; i<indices_length; ++i) {
804  DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
805  if (tmp>radius) {
806  radius = tmp;
807  }
808  }
809 
810  node->variance = static_cast<DistanceType>(variance);
811  node->radius = radius;
812  node->pivot = mean;
813 
814  delete[] mean_accumulator;
815  }
816 
817 
818  void computeDnaNodeStatistics(KMeansNodePtr node, int* indices,
819  unsigned int indices_length)
820  {
821  const unsigned int histos_veclen = static_cast<unsigned int>(
822  veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
823 
824  unsigned long long variance = 0ull;
825  unsigned int* histograms = new unsigned int[histos_veclen];
826  memset(histograms, 0, sizeof(unsigned int)*histos_veclen);
827 
828  for (unsigned int i=0; i<indices_length; ++i) {
829  variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
830  distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
831 
832  unsigned char* vec = (unsigned char*)dataset_[indices[i]];
833  for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
834  histograms[k + ((vec[l]) & 0x03)]++;
835  histograms[k + 4 + ((vec[l]>>2) & 0x03)]++;
836  histograms[k + 8 + ((vec[l]>>4) & 0x03)]++;
837  histograms[k +12 + ((vec[l]>>6) & 0x03)]++;
838  }
839  }
840 
841  CentersType* mean = new CentersType[veclen_];
842  memoryCounter_ += int(veclen_*sizeof(CentersType));
843  unsigned char* char_mean = (unsigned char*)mean;
844  unsigned int* h = histograms;
845  for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
846  char_mean[l] = (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10
847  : h[k] > h[k+3] ? 0x00 : 0x11
848  : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
849  : h[k+1] > h[k+3] ? 0x01 : 0x11)
850  | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000
851  : h[k+4] > h[k+7] ? 0x00 : 0x1100
852  : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
853  : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
854  | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000
855  : h[k+8] >h[k+11] ? 0x00 : 0x110000
856  : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
857  : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
858  | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000
859  : h[k+12] >h[k+15] ? 0x00 : 0x11000000
860  : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
861  : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
862  }
863  variance = static_cast<unsigned long long>(
864  0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
865  variance -= static_cast<unsigned long long>(
866  ensureSquareDistance<Distance>(
867  distance_(mean, ZeroIterator<ElementType>(), veclen_)));
868 
869  DistanceType radius = 0;
870  for (unsigned int i=0; i<indices_length; ++i) {
871  DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
872  if (tmp>radius) {
873  radius = tmp;
874  }
875  }
876 
877  node->variance = static_cast<DistanceType>(variance);
878  node->radius = radius;
879  node->pivot = mean;
880 
881  delete[] histograms;
882  }
883 
884 
885  template<typename DistType>
886  void computeNodeStatistics(KMeansNodePtr node, int* indices,
887  unsigned int indices_length,
888  const DistType* identifier)
889  {
890  (void)identifier;
891  computeNodeStatistics(node, indices, indices_length);
892  }
893 
894  void computeNodeStatistics(KMeansNodePtr node, int* indices,
895  unsigned int indices_length,
896  const cvflann::HammingLUT* identifier)
897  {
898  (void)identifier;
899  computeBitfieldNodeStatistics(node, indices, indices_length);
900  }
901 
902  void computeNodeStatistics(KMeansNodePtr node, int* indices,
903  unsigned int indices_length,
904  const cvflann::Hamming<unsigned char>* identifier)
905  {
906  (void)identifier;
907  computeBitfieldNodeStatistics(node, indices, indices_length);
908  }
909 
910  void computeNodeStatistics(KMeansNodePtr node, int* indices,
911  unsigned int indices_length,
912  const cvflann::Hamming2<unsigned char>* identifier)
913  {
914  (void)identifier;
915  computeBitfieldNodeStatistics(node, indices, indices_length);
916  }
917 
918  void computeNodeStatistics(KMeansNodePtr node, int* indices,
919  unsigned int indices_length,
920  const cvflann::DNAmmingLUT* identifier)
921  {
922  (void)identifier;
923  computeDnaNodeStatistics(node, indices, indices_length);
924  }
925 
926  void computeNodeStatistics(KMeansNodePtr node, int* indices,
927  unsigned int indices_length,
928  const cvflann::DNAmming2<unsigned char>* identifier)
929  {
930  (void)identifier;
931  computeDnaNodeStatistics(node, indices, indices_length);
932  }
933 
934 
935  void refineClustering(int* indices, int indices_length, int branching, CentersType** centers,
936  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
937  {
938  cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
939  Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);
940 
941  bool converged = false;
942  int iteration = 0;
943  while (!converged && iteration<iterations_) {
944  converged = true;
945  iteration++;
946 
947  // compute the new cluster centers
948  for (int i=0; i<branching; ++i) {
949  memset(dcenters[i],0,sizeof(double)*veclen_);
950  radiuses[i] = 0;
951  }
952  for (int i=0; i<indices_length; ++i) {
953  ElementType* vec = dataset_[indices[i]];
954  double* center = dcenters[belongs_to[i]];
955  for (size_t k=0; k<veclen_; ++k) {
956  center[k] += vec[k];
957  }
958  }
959  for (int i=0; i<branching; ++i) {
960  int cnt = count[i];
961  for (size_t k=0; k<veclen_; ++k) {
962  dcenters[i][k] /= cnt;
963  }
964  }
965 
966  std::vector<int> new_centroids(indices_length);
967  std::vector<DistanceType> sq_dists(indices_length);
968 
969  // reassign points to clusters
970  KMeansDistanceComputer<Matrix<double> > invoker(
971  distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
972  parallel_for_(cv::Range(0, (int)indices_length), invoker);
973 
974  for (int i=0; i < (int)indices_length; ++i) {
975  DistanceType sq_dist(sq_dists[i]);
976  int new_centroid(new_centroids[i]);
977  if (sq_dist > radiuses[new_centroid]) {
978  radiuses[new_centroid] = sq_dist;
979  }
980  if (new_centroid != belongs_to[i]) {
981  count[belongs_to[i]]--;
982  count[new_centroid]++;
983  belongs_to[i] = new_centroid;
984  converged = false;
985  }
986  }
987 
988  for (int i=0; i<branching; ++i) {
989  // if one cluster converges to an empty cluster,
990  // move an element into that cluster
991  if (count[i]==0) {
992  int j = (i+1)%branching;
993  while (count[j]<=1) {
994  j = (j+1)%branching;
995  }
996 
997  for (int k=0; k<indices_length; ++k) {
998  if (belongs_to[k]==j) {
999  // for cluster j, we move the furthest element from the center to the empty cluster i
1000  if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
1001  belongs_to[k] = i;
1002  count[j]--;
1003  count[i]++;
1004  break;
1005  }
1006  }
1007  }
1008  converged = false;
1009  }
1010  }
1011  }
1012 
1013  for (int i=0; i<branching; ++i) {
1014  centers[i] = new CentersType[veclen_];
1015  memoryCounter_ += (int)(veclen_*sizeof(CentersType));
1016  for (size_t k=0; k<veclen_; ++k) {
1017  centers[i][k] = (CentersType)dcenters[i][k];
1018  }
1019  }
1020  }
1021 
1022 
1023  void refineBitfieldClustering(int* indices, int indices_length, int branching, CentersType** centers,
1024  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
1025  {
1026  for (int i=0; i<branching; ++i) {
1027  centers[i] = new CentersType[veclen_];
1028  memoryCounter_ += (int)(veclen_*sizeof(CentersType));
1029  }
1030 
1031  const unsigned int accumulator_veclen = static_cast<unsigned int>(
1032  veclen_*sizeof(ElementType)*BITS_PER_CHAR);
1033  cv::AutoBuffer<unsigned int> dcenters_buf(branching*accumulator_veclen);
1034  Matrix<unsigned int> dcenters(dcenters_buf.data(), branching, accumulator_veclen);
1035 
1036  bool converged = false;
1037  int iteration = 0;
1038  while (!converged && iteration<iterations_) {
1039  converged = true;
1040  iteration++;
1041 
1042  // compute the new cluster centers
1043  for (int i=0; i<branching; ++i) {
1044  memset(dcenters[i],0,sizeof(unsigned int)*accumulator_veclen);
1045  radiuses[i] = 0;
1046  }
1047  for (int i=0; i<indices_length; ++i) {
1048  unsigned char* vec = (unsigned char*)dataset_[indices[i]];
1049  unsigned int* dcenter = dcenters[belongs_to[i]];
1050  for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
1051  dcenter[k] += (vec[l]) & 0x01;
1052  dcenter[k+1] += (vec[l]>>1) & 0x01;
1053  dcenter[k+2] += (vec[l]>>2) & 0x01;
1054  dcenter[k+3] += (vec[l]>>3) & 0x01;
1055  dcenter[k+4] += (vec[l]>>4) & 0x01;
1056  dcenter[k+5] += (vec[l]>>5) & 0x01;
1057  dcenter[k+6] += (vec[l]>>6) & 0x01;
1058  dcenter[k+7] += (vec[l]>>7) & 0x01;
1059  }
1060  }
1061  for (int i=0; i<branching; ++i) {
1062  double cnt = static_cast<double>(count[i]);
1063  unsigned int* dcenter = dcenters[i];
1064  unsigned char* charCenter = (unsigned char*)centers[i];
1065  for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
1066  charCenter[l] = static_cast<unsigned char>(
1067  (((int)(0.5 + (double)(dcenter[k]) / cnt)))
1068  | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1)
1069  | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2)
1070  | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3)
1071  | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4)
1072  | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5)
1073  | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6)
1074  | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7));
1075  }
1076  }
1077 
1078  std::vector<int> new_centroids(indices_length);
1079  std::vector<DistanceType> dists(indices_length);
1080 
1081  // reassign points to clusters
1082  KMeansDistanceComputer<ElementType**> invoker(
1083  distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
1084  parallel_for_(cv::Range(0, (int)indices_length), invoker);
1085 
1086  for (int i=0; i < indices_length; ++i) {
1087  DistanceType dist(dists[i]);
1088  int new_centroid(new_centroids[i]);
1089  if (dist > radiuses[new_centroid]) {
1090  radiuses[new_centroid] = dist;
1091  }
1092  if (new_centroid != belongs_to[i]) {
1093  count[belongs_to[i]]--;
1094  count[new_centroid]++;
1095  belongs_to[i] = new_centroid;
1096  converged = false;
1097  }
1098  }
1099 
1100  for (int i=0; i<branching; ++i) {
1101  // if one cluster converges to an empty cluster,
1102  // move an element into that cluster
1103  if (count[i]==0) {
1104  int j = (i+1)%branching;
1105  while (count[j]<=1) {
1106  j = (j+1)%branching;
1107  }
1108 
1109  for (int k=0; k<indices_length; ++k) {
1110  if (belongs_to[k]==j) {
1111  // for cluster j, we move the furthest element from the center to the empty cluster i
1112  if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
1113  belongs_to[k] = i;
1114  count[j]--;
1115  count[i]++;
1116  break;
1117  }
1118  }
1119  }
1120  converged = false;
1121  }
1122  }
1123  }
1124  }
1125 
1126 
1127  void refineDnaClustering(int* indices, int indices_length, int branching, CentersType** centers,
1128  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
1129  {
1130  for (int i=0; i<branching; ++i) {
1131  centers[i] = new CentersType[veclen_];
1132  memoryCounter_ += (int)(veclen_*sizeof(CentersType));
1133  }
1134 
1135  const unsigned int histos_veclen = static_cast<unsigned int>(
1136  veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
1137  cv::AutoBuffer<unsigned int> histos_buf(branching*histos_veclen);
1138  Matrix<unsigned int> histos(histos_buf.data(), branching, histos_veclen);
1139 
1140  bool converged = false;
1141  int iteration = 0;
1142  while (!converged && iteration<iterations_) {
1143  converged = true;
1144  iteration++;
1145 
1146  // compute the new cluster centers
1147  for (int i=0; i<branching; ++i) {
1148  memset(histos[i],0,sizeof(unsigned int)*histos_veclen);
1149  radiuses[i] = 0;
1150  }
1151  for (int i=0; i<indices_length; ++i) {
1152  unsigned char* vec = (unsigned char*)dataset_[indices[i]];
1153  unsigned int* h = histos[belongs_to[i]];
1154  for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
1155  h[k + ((vec[l]) & 0x03)]++;
1156  h[k + 4 + ((vec[l]>>2) & 0x03)]++;
1157  h[k + 8 + ((vec[l]>>4) & 0x03)]++;
1158  h[k +12 + ((vec[l]>>6) & 0x03)]++;
1159  }
1160  }
1161  for (int i=0; i<branching; ++i) {
1162  unsigned int* h = histos[i];
1163  unsigned char* charCenter = (unsigned char*)centers[i];
1164  for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
1165  charCenter[l]= (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10
1166  : h[k] > h[k+3] ? 0x00 : 0x11
1167  : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
1168  : h[k+1] > h[k+3] ? 0x01 : 0x11)
1169  | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000
1170  : h[k+4] > h[k+7] ? 0x00 : 0x1100
1171  : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
1172  : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
1173  | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000
1174  : h[k+8] >h[k+11] ? 0x00 : 0x110000
1175  : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
1176  : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
1177  | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000
1178  : h[k+12] >h[k+15] ? 0x00 : 0x11000000
1179  : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
1180  : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
1181  }
1182  }
1183 
1184  std::vector<int> new_centroids(indices_length);
1185  std::vector<DistanceType> dists(indices_length);
1186 
1187  // reassign points to clusters
1188  KMeansDistanceComputer<ElementType**> invoker(
1189  distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
1190  parallel_for_(cv::Range(0, (int)indices_length), invoker);
1191 
1192  for (int i=0; i < indices_length; ++i) {
1193  DistanceType dist(dists[i]);
1194  int new_centroid(new_centroids[i]);
1195  if (dist > radiuses[new_centroid]) {
1196  radiuses[new_centroid] = dist;
1197  }
1198  if (new_centroid != belongs_to[i]) {
1199  count[belongs_to[i]]--;
1200  count[new_centroid]++;
1201  belongs_to[i] = new_centroid;
1202  converged = false;
1203  }
1204  }
1205 
1206  for (int i=0; i<branching; ++i) {
1207  // if one cluster converges to an empty cluster,
1208  // move an element into that cluster
1209  if (count[i]==0) {
1210  int j = (i+1)%branching;
1211  while (count[j]<=1) {
1212  j = (j+1)%branching;
1213  }
1214 
1215  for (int k=0; k<indices_length; ++k) {
1216  if (belongs_to[k]==j) {
1217  // for cluster j, we move the furthest element from the center to the empty cluster i
1218  if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
1219  belongs_to[k] = i;
1220  count[j]--;
1221  count[i]++;
1222  break;
1223  }
1224  }
1225  }
1226  converged = false;
1227  }
1228  }
1229  }
1230  }
1231 
1232 
1233  void computeSubClustering(KMeansNodePtr node, int* indices, int indices_length,
1234  int branching, int level, CentersType** centers,
1235  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
1236  {
1237  // compute kmeans clustering for each of the resulting clusters
1238  node->childs = pool_.allocate<KMeansNodePtr>(branching);
1239  int start = 0;
1240  int end = start;
1241  for (int c=0; c<branching; ++c) {
1242  int s = count[c];
1243 
1244  DistanceType variance = 0;
1245  DistanceType mean_radius =0;
1246  for (int i=0; i<indices_length; ++i) {
1247  if (belongs_to[i]==c) {
1248  DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
1249  variance += d;
1250  mean_radius += static_cast<DistanceType>( sqrt(d) );
1251  std::swap(indices[i],indices[end]);
1252  std::swap(belongs_to[i],belongs_to[end]);
1253  end++;
1254  }
1255  }
1256  variance /= s;
1257  mean_radius /= s;
1258  variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
1259 
1260  node->childs[c] = pool_.allocate<KMeansNode>();
1261  std::memset(node->childs[c], 0, sizeof(KMeansNode));
1262  node->childs[c]->radius = radiuses[c];
1263  node->childs[c]->pivot = centers[c];
1264  node->childs[c]->variance = variance;
1265  node->childs[c]->mean_radius = mean_radius;
1266  computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
1267  start=end;
1268  }
1269  }
1270 
1271 
1272  void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length,
1273  int branching, int level, CentersType** centers,
1274  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
1275  {
1276  // compute kmeans clustering for each of the resulting clusters
1277  node->childs = pool_.allocate<KMeansNodePtr>(branching);
1278  int start = 0;
1279  int end = start;
1280  for (int c=0; c<branching; ++c) {
1281  int s = count[c];
1282 
1283  unsigned long long variance = 0ull;
1284  DistanceType mean_radius =0;
1285  for (int i=0; i<indices_length; ++i) {
1286  if (belongs_to[i]==c) {
1287  DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
1288  variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(d) );
1289  mean_radius += ensureSimpleDistance<Distance>(d);
1290  std::swap(indices[i],indices[end]);
1291  std::swap(belongs_to[i],belongs_to[end]);
1292  end++;
1293  }
1294  }
1295  mean_radius = static_cast<DistanceType>(
1296  0.5f + static_cast<float>(mean_radius) / static_cast<float>(s));
1297  variance = static_cast<unsigned long long>(
1298  0.5 + static_cast<double>(variance) / static_cast<double>(s));
1299  variance -= static_cast<unsigned long long>(
1300  ensureSquareDistance<Distance>(
1301  distance_(centers[c], ZeroIterator<ElementType>(), veclen_)));
1302 
1303  node->childs[c] = pool_.allocate<KMeansNode>();
1304  std::memset(node->childs[c], 0, sizeof(KMeansNode));
1305  node->childs[c]->radius = radiuses[c];
1306  node->childs[c]->pivot = centers[c];
1307  node->childs[c]->variance = static_cast<DistanceType>(variance);
1308  node->childs[c]->mean_radius = mean_radius;
1309  computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
1310  start=end;
1311  }
1312  }
1313 
1314 
1315  template<typename DistType>
1316  void refineAndSplitClustering(
1317  KMeansNodePtr node, int* indices, int indices_length, int branching,
1318  int level, CentersType** centers, std::vector<DistanceType>& radiuses,
1319  int* belongs_to, int* count, const DistType* identifier)
1320  {
1321  (void)identifier;
1322  refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count);
1323 
1324  computeSubClustering(node, indices, indices_length, branching,
1325  level, centers, radiuses, belongs_to, count);
1326  }
1327 
1328 
1373  void refineAndSplitClustering(
1374  KMeansNodePtr node, int* indices, int indices_length, int branching,
1375  int level, CentersType** centers, std::vector<DistanceType>& radiuses,
1376  int* belongs_to, int* count, const cvflann::HammingLUT* identifier)
1377  {
1378  (void)identifier;
1379  refineBitfieldClustering(
1380  indices, indices_length, branching, centers, radiuses, belongs_to, count);
1381 
1382  computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
1383  level, centers, radiuses, belongs_to, count);
1384  }
1385 
1386 
1387  void refineAndSplitClustering(
1388  KMeansNodePtr node, int* indices, int indices_length, int branching,
1389  int level, CentersType** centers, std::vector<DistanceType>& radiuses,
1390  int* belongs_to, int* count, const cvflann::Hamming<unsigned char>* identifier)
1391  {
1392  (void)identifier;
1393  refineBitfieldClustering(
1394  indices, indices_length, branching, centers, radiuses, belongs_to, count);
1395 
1396  computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
1397  level, centers, radiuses, belongs_to, count);
1398  }
1399 
1400 
1401  void refineAndSplitClustering(
1402  KMeansNodePtr node, int* indices, int indices_length, int branching,
1403  int level, CentersType** centers, std::vector<DistanceType>& radiuses,
1404  int* belongs_to, int* count, const cvflann::Hamming2<unsigned char>* identifier)
1405  {
1406  (void)identifier;
1407  refineBitfieldClustering(
1408  indices, indices_length, branching, centers, radiuses, belongs_to, count);
1409 
1410  computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
1411  level, centers, radiuses, belongs_to, count);
1412  }
1413 
1414 
1415  void refineAndSplitClustering(
1416  KMeansNodePtr node, int* indices, int indices_length, int branching,
1417  int level, CentersType** centers, std::vector<DistanceType>& radiuses,
1418  int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier)
1419  {
1420  (void)identifier;
1421  refineDnaClustering(
1422  indices, indices_length, branching, centers, radiuses, belongs_to, count);
1423 
1424  computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
1425  level, centers, radiuses, belongs_to, count);
1426  }
1427 
1428 
1429  void refineAndSplitClustering(
1430  KMeansNodePtr node, int* indices, int indices_length, int branching,
1431  int level, CentersType** centers, std::vector<DistanceType>& radiuses,
1432  int* belongs_to, int* count, const cvflann::DNAmming2<unsigned char>* identifier)
1433  {
1434  (void)identifier;
1435  refineDnaClustering(
1436  indices, indices_length, branching, centers, radiuses, belongs_to, count);
1437 
1438  computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
1439  level, centers, radiuses, belongs_to, count);
1440  }
1441 
1442 
1454  void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
1455  {
1456  node->size = indices_length;
1457  node->level = level;
1458 
1459  if (indices_length < branching) {
1460  node->indices = indices;
1461  std::sort(node->indices,node->indices+indices_length);
1462  node->childs = NULL;
1463  return;
1464  }
1465 
1466  cv::AutoBuffer<int> centers_idx_buf(branching);
1467  int* centers_idx = centers_idx_buf.data();
1468  int centers_length;
1469  (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
1470 
1471  if (centers_length<branching) {
1472  node->indices = indices;
1473  std::sort(node->indices,node->indices+indices_length);
1474  node->childs = NULL;
1475  return;
1476  }
1477 
1478 
1479  std::vector<DistanceType> radiuses(branching);
1480  cv::AutoBuffer<int> count_buf(branching);
1481  int* count = count_buf.data();
1482  for (int i=0; i<branching; ++i) {
1483  radiuses[i] = 0;
1484  count[i] = 0;
1485  }
1486 
1487  // assign points to clusters
1488  cv::AutoBuffer<int> belongs_to_buf(indices_length);
1489  int* belongs_to = belongs_to_buf.data();
1490  for (int i=0; i<indices_length; ++i) {
1491  DistanceType sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[0]], veclen_);
1492  belongs_to[i] = 0;
1493  for (int j=1; j<branching; ++j) {
1494  DistanceType new_sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[j]], veclen_);
1495  if (sq_dist>new_sq_dist) {
1496  belongs_to[i] = j;
1497  sq_dist = new_sq_dist;
1498  }
1499  }
1500  if (sq_dist>radiuses[belongs_to[i]]) {
1501  radiuses[belongs_to[i]] = sq_dist;
1502  }
1503  count[belongs_to[i]]++;
1504  }
1505 
1506  CentersType** centers = new CentersType*[branching];
1507 
1508  Distance* dummy = NULL;
1509  refineAndSplitClustering(node, indices, indices_length, branching, level,
1510  centers, radiuses, belongs_to, count, dummy);
1511 
1512  delete[] centers;
1513  }
1514 
1515 
1529  void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
1530  const cv::Ptr<Heap<BranchSt>>& heap)
1531  {
1532  // Ignore those clusters that are too far away
1533  {
1534  DistanceType bsq = distance_(vec, node->pivot, veclen_);
1535  DistanceType rsq = node->radius;
1536  DistanceType wsq = result.worstDist();
1537 
1538  if (isSquareDistance<Distance>())
1539  {
1540  DistanceType val = bsq-rsq-wsq;
1541  if ((val>0) && (val*val > 4*rsq*wsq))
1542  return;
1543  }
1544  else
1545  {
1546  if (bsq-rsq > wsq)
1547  return;
1548  }
1549  }
1550 
1551  if (node->childs==NULL) {
1552  if ((checks>=maxChecks) && result.full()) {
1553  return;
1554  }
1555  checks += node->size;
1556  for (int i=0; i<node->size; ++i) {
1557  int index = node->indices[i];
1558  DistanceType dist = distance_(dataset_[index], vec, veclen_);
1559  result.addPoint(dist, index);
1560  }
1561  }
1562  else {
1563  DistanceType* domain_distances = new DistanceType[branching_];
1564  int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
1565  delete[] domain_distances;
1566  findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
1567  }
1568  }
1569 
1578  int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr<Heap<BranchSt>>& heap)
1579  {
1580 
1581  int best_index = 0;
1582  domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
1583  for (int i=1; i<branching_; ++i) {
1584  domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
1585  if (domain_distances[i]<domain_distances[best_index]) {
1586  best_index = i;
1587  }
1588  }
1589 
1590  // float* best_center = node->childs[best_index]->pivot;
1591  for (int i=0; i<branching_; ++i) {
1592  if (i != best_index) {
1593  domain_distances[i] -= cvflann::round<DistanceType>(
1594  cb_index_*node->childs[i]->variance );
1595 
1596  // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
1597  // if (domain_distances[i]<dist_to_border) {
1598  // domain_distances[i] = dist_to_border;
1599  // }
1600  heap->insert(BranchSt(node->childs[i],domain_distances[i]));
1601  }
1602  }
1603 
1604  return best_index;
1605  }
1606 
1607 
1611  void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
1612  {
1613  // Ignore those clusters that are too far away
1614  {
1615  DistanceType bsq = distance_(vec, node->pivot, veclen_);
1616  DistanceType rsq = node->radius;
1617  DistanceType wsq = result.worstDist();
1618 
1619  if (isSquareDistance<Distance>())
1620  {
1621  DistanceType val = bsq-rsq-wsq;
1622  if ((val>0) && (val*val > 4*rsq*wsq))
1623  return;
1624  }
1625  else
1626  {
1627  if (bsq-rsq > wsq)
1628  return;
1629  }
1630  }
1631 
1632 
1633  if (node->childs==NULL) {
1634  for (int i=0; i<node->size; ++i) {
1635  int index = node->indices[i];
1636  DistanceType dist = distance_(dataset_[index], vec, veclen_);
1637  result.addPoint(dist, index);
1638  }
1639  }
1640  else {
1641  int* sort_indices = new int[branching_];
1642 
1643  getCenterOrdering(node, vec, sort_indices);
1644 
1645  for (int i=0; i<branching_; ++i) {
1646  findExactNN(node->childs[sort_indices[i]],result,vec);
1647  }
1648 
1649  delete[] sort_indices;
1650  }
1651  }
1652 
1653 
1659  void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
1660  {
1661  DistanceType* domain_distances = new DistanceType[branching_];
1662  for (int i=0; i<branching_; ++i) {
1663  DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
1664 
1665  int j=0;
1666  while (domain_distances[j]<dist && j<i)
1667  j++;
1668  for (int k=i; k>j; --k) {
1669  domain_distances[k] = domain_distances[k-1];
1670  sort_indices[k] = sort_indices[k-1];
1671  }
1672  domain_distances[j] = dist;
1673  sort_indices[j] = i;
1674  }
1675  delete[] domain_distances;
1676  }
1677 
1683  DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
1684  {
1685  DistanceType sum = 0;
1686  DistanceType sum2 = 0;
1687 
1688  for (int i=0; i<veclen_; ++i) {
1689  DistanceType t = c[i]-p[i];
1690  sum += t*(q[i]-(c[i]+p[i])/2);
1691  sum2 += t*t;
1692  }
1693 
1694  return sum*sum/sum2;
1695  }
1696 
1697 
1707  int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
1708  {
1709  int clusterCount = 1;
1710  clusters[0] = root;
1711 
1712  DistanceType meanVariance = root->variance*root->size;
1713 
1714  while (clusterCount<clusters_length) {
1715  DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
1716  int splitIndex = -1;
1717 
1718  for (int i=0; i<clusterCount; ++i) {
1719  if (clusters[i]->childs != NULL) {
1720 
1721  DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;
1722 
1723  for (int j=0; j<branching_; ++j) {
1724  variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
1725  }
1726  if (variance<minVariance) {
1727  minVariance = variance;
1728  splitIndex = i;
1729  }
1730  }
1731  }
1732 
1733  if (splitIndex==-1) break;
1734  if ( (branching_+clusterCount-1) > clusters_length) break;
1735 
1736  meanVariance = minVariance;
1737 
1738  // split node
1739  KMeansNodePtr toSplit = clusters[splitIndex];
1740  clusters[splitIndex] = toSplit->childs[0];
1741  for (int i=1; i<branching_; ++i) {
1742  clusters[clusterCount++] = toSplit->childs[i];
1743  }
1744  }
1745 
1746  varianceValue = meanVariance/root->size;
1747  return clusterCount;
1748  }
1749 
1750 private:
1752  int branching_;
1753 
1755  int trees_;
1756 
1758  int iterations_;
1759 
1761  flann_centers_init_t centers_init_;
1762 
1769  float cb_index_;
1770 
1774  const Matrix<ElementType> dataset_;
1775 
1777  IndexParams index_params_;
1778 
1782  size_t size_;
1783 
1787  size_t veclen_;
1788 
1792  KMeansNodePtr* root_;
1793 
1797  int** indices_;
1798 
1802  Distance distance_;
1803 
1807  PooledAllocator pool_;
1808 
1812  int memoryCounter_;
1813 };
1814 
1815 }
1816 
1818 
1819 #endif //OPENCV_FLANN_KMEANS_INDEX_H_
T begin(T... args)
Automatically Allocated Buffer Class.
Definition: utility.hpp:102
Base class for parallel data processors.
Definition: utility.hpp:577
Template class specifying a continuous subsequence (slice) of a sequence.
Definition: types.hpp:623
T distance(T... args)
double double end
Definition: core_c.h:1381
double start
Definition: core_c.h:1381
int index
Definition: core_c.h:634
CvSize size
Definition: core_c.h:112
int count
Definition: core_c.h:1413
CvArr * mean
Definition: core_c.h:1419
const CvArr const CvArr CvArr * result
Definition: core_c.h:1423
CV_EXPORTS void parallel_for_(const Range &range, const ParallelLoopBody &body, double nstripes=-1.)
Parallel data processor.
#define CV_OVERRIDE
Definition: cvdef.h:792
Hamming HammingLUT
Definition: base.hpp:393
#define CV_Assert(expr)
Checks a condition at runtime and throws exception if it fails.
Definition: base.hpp:342
#define CV_DbgAssert(expr)
Definition: base.hpp:375
Quat< S > sqrt(const Quat< S > &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT)
CvRect r
Definition: imgproc_c.h:984
CvArr * sum
Definition: imgproc_c.h:61
CvPoint2D32f float * radius
Definition: imgproc_c.h:534
CvArr CvSize range
Definition: imgproc_c.h:781
CvArr CvPoint2D32f center
Definition: imgproc_c.h:270
CV_EXPORTS OutputArray int double double InputArray OutputArray int int bool double k
Definition: imgproc.hpp:2133
T memset(T... args)
T min(T... args)
@ StsError
unknown /unspecified error
Definition: base.hpp:71
@ StsBadArg
function arg/param is bad
Definition: base.hpp:74
CV_EXPORTS int getThreadID()
Definition: flann.hpp:60
T sort(T... args)
Definition: cvstd_wrapper.hpp:74
T swap(T... args)