flann.hpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Third party copyrights are property of their respective owners.
  16. //
  17. // Redistribution and use in source and binary forms, with or without modification,
  18. // are permitted provided that the following conditions are met:
  19. //
  20. // * Redistribution's of source code must retain the above copyright notice,
  21. // this list of conditions and the following disclaimer.
  22. //
  23. // * Redistribution's in binary form must reproduce the above copyright notice,
  24. // this list of conditions and the following disclaimer in the documentation
  25. // and/or other materials provided with the distribution.
  26. //
  27. // * The name of the copyright holders may not be used to endorse or promote products
  28. // derived from this software without specific prior written permission.
  29. //
  30. // This software is provided by the copyright holders and contributors "as is" and
  31. // any express or implied warranties, including, but not limited to, the implied
  32. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  33. // In no event shall the Intel Corporation or contributors be liable for any direct,
  34. // indirect, incidental, special, exemplary, or consequential damages
  35. // (including, but not limited to, procurement of substitute goods or services;
  36. // loss of use, data, or profits; or business interruption) however caused
  37. // and on any theory of liability, whether in contract, strict liability,
  38. // or tort (including negligence or otherwise) arising in any way out of
  39. // the use of this software, even if advised of the possibility of such damage.
  40. //
  41. //M*/
  42. #ifndef OPENCV_FLANN_HPP
  43. #define OPENCV_FLANN_HPP
  44. #include "opencv2/core.hpp"
  45. #include "opencv2/flann/miniflann.hpp"
  46. #include "opencv2/flann/flann_base.hpp"
  47. /**
  48. @defgroup flann Clustering and Search in Multi-Dimensional Spaces
  49. This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate
  50. Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest
  51. neighbor search in large datasets and for high dimensional features. More information about FLANN
  52. can be found in @cite Muja2009 .
  53. */
  54. namespace cvflann
  55. {
  56. CV_EXPORTS flann_distance_t flann_distance_type();
  57. CV_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order);
  58. }
  59. namespace cv
  60. {
  61. namespace flann
  62. {
  63. //! @addtogroup flann
  64. //! @{
  65. template <typename T> struct CvType {};
  66. template <> struct CvType<unsigned char> { static int type() { return CV_8U; } };
  67. template <> struct CvType<char> { static int type() { return CV_8S; } };
  68. template <> struct CvType<unsigned short> { static int type() { return CV_16U; } };
  69. template <> struct CvType<short> { static int type() { return CV_16S; } };
  70. template <> struct CvType<int> { static int type() { return CV_32S; } };
  71. template <> struct CvType<float> { static int type() { return CV_32F; } };
  72. template <> struct CvType<double> { static int type() { return CV_64F; } };
  73. // bring the flann parameters into this namespace
  74. using ::cvflann::get_param;
  75. using ::cvflann::print_params;
  76. // bring the flann distances into this namespace
  77. using ::cvflann::L2_Simple;
  78. using ::cvflann::L2;
  79. using ::cvflann::L1;
  80. using ::cvflann::MinkowskiDistance;
  81. using ::cvflann::MaxDistance;
  82. using ::cvflann::HammingLUT;
  83. using ::cvflann::Hamming;
  84. using ::cvflann::Hamming2;
  85. using ::cvflann::DNAmmingLUT;
  86. using ::cvflann::DNAmming2;
  87. using ::cvflann::HistIntersectionDistance;
  88. using ::cvflann::HellingerDistance;
  89. using ::cvflann::ChiSquareDistance;
  90. using ::cvflann::KL_Divergence;
  91. /** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which
  92. the index is built.
  93. `Distance` functor specifies the metric to be used to calculate the distance between two points.
  94. There are several `Distance` functors that are readily available:
  95. cv::cvflann::L2_Simple - Squared Euclidean distance functor.
  96. This is the simpler, unrolled version. This is preferable for very low dimensionality data (eg 3D points)
  97. cv::flann::L2 - Squared Euclidean distance functor, optimized version.
  98. cv::flann::L1 - Manhattan distance functor, optimized version.
  99. cv::flann::MinkowskiDistance - The Minkowski distance functor.
  100. This is highly optimised with loop unrolling.
  101. The computation of squared root at the end is omitted for efficiency.
  102. cv::flann::MaxDistance - The max distance functor. It computes the
  103. maximum distance between two vectors. This distance is not a valid kdtree distance, it's not
  104. dimensionwise additive.
  105. cv::flann::HammingLUT - %Hamming distance functor. It counts the bit
  106. differences between two strings using a lookup table implementation.
  107. cv::flann::Hamming - %Hamming distance functor. Population count is
  108. performed using library calls, if available. Lookup table implementation is used as a fallback.
  109. cv::flann::Hamming2 - %Hamming distance functor. Population count is
  110. implemented in 12 arithmetic operations (one of which is multiplication).
  111. cv::flann::DNAmmingLUT - %Adaptation of the Hamming distance functor to DNA comparison.
  112. As the four bases A, C, G, T of the DNA (or A, G, C, U for RNA) can be coded on 2 bits,
  113. it counts the bits pairs differences between two sequences using a lookup table implementation.
  114. cv::flann::DNAmming2 - %Adaptation of the Hamming distance functor to DNA comparison.
  115. Bases differences count are vectorised thanks to arithmetic operations using standard
  116. registers (AVX2 and AVX-512 should come in a near future).
  117. cv::flann::HistIntersectionDistance - The histogram
  118. intersection distance functor.
  119. cv::flann::HellingerDistance - The Hellinger distance functor.
  120. cv::flann::ChiSquareDistance - The chi-square distance functor.
  121. cv::flann::KL_Divergence - The Kullback-Leibler divergence functor.
  122. Although the provided implementations cover a vast range of cases, it is also possible to use
  123. a custom implementation. The distance functor is a class whose `operator()` computes the distance
  124. between two features. If the distance is also a kd-tree compatible distance, it should also provide an
  125. `accum_dist()` method that computes the distance between individual feature dimensions.
  126. In addition to `operator()` and `accum_dist()`, a distance functor should also define the
  127. `ElementType` and the `ResultType` as the types of the elements it operates on and the type of the
  128. result it computes. If a distance functor can be used as a kd-tree distance (meaning that the full
  129. distance between a pair of features can be accumulated from the partial distances between the
  130. individual dimensions) a typedef `is_kdtree_distance` should be present inside the distance functor.
  131. If the distance is not a kd-tree distance, but it's a distance in a vector space (the individual
  132. dimensions of the elements it operates on can be accessed independently) a typedef
  133. `is_vector_space_distance` should be defined inside the functor. If neither typedef is defined, the
  134. distance is assumed to be a metric distance and will only be used with indexes operating on
  135. generic metric distances.
  136. */
  137. template <typename Distance>
  138. class GenericIndex
  139. {
  140. public:
  141. typedef typename Distance::ElementType ElementType;
  142. typedef typename Distance::ResultType DistanceType;
  143. /** @brief Constructs a nearest neighbor search index for a given dataset.
  144. @param features Matrix of containing the features(points) to index. The size of the matrix is
  145. num_features x feature_dimensionality and the data type of the elements in the matrix must
  146. coincide with the type of the index.
  147. @param params Structure containing the index parameters. The type of index that will be
  148. constructed depends on the type of this parameter. See the description.
  149. @param distance
  150. The method constructs a fast search structure from a set of features using the specified algorithm
  151. with specified parameters, as defined by params. params is a reference to one of the following class
  152. IndexParams descendants:
  153. - **LinearIndexParams** When passing an object of this type, the index will perform a linear,
  154. brute-force search. :
  155. @code
  156. struct LinearIndexParams : public IndexParams
  157. {
  158. };
  159. @endcode
  160. - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of
  161. a set of randomized kd-trees which will be searched in parallel. :
  162. @code
  163. struct KDTreeIndexParams : public IndexParams
  164. {
  165. KDTreeIndexParams( int trees = 4 );
  166. };
  167. @endcode
  168. - **HierarchicalClusteringIndexParams** When passing an object of this type the index constructed
  169. will be a hierarchical tree of clusters, dividing each set of points into n clusters whose centers
  170. are picked among the points without further refinement of their position.
  171. This algorithm fits both floating, integer and binary vectors. :
  172. @code
  173. struct HierarchicalClusteringIndexParams : public IndexParams
  174. {
  175. HierarchicalClusteringIndexParams(
  176. int branching = 32,
  177. flann_centers_init_t centers_init = CENTERS_RANDOM,
  178. int trees = 4,
  179. int leaf_size = 100);
  180. };
  181. @endcode
  182. - **KMeansIndexParams** When passing an object of this type the index constructed will be a
  183. hierarchical k-means tree (one tree by default), dividing each set of points into n clusters
  184. whose barycenters are refined iteratively.
  185. Note that this algorithm has been extended to the support of binary vectors as an alternative
  186. to LSH when knn search speed is the criterium. It will also outperform LSH when processing
  187. directly (i.e. without the use of MCA/PCA) datasets whose points share mostly the same values
  188. for most of the dimensions. It is recommended to set more than one tree with binary data. :
  189. @code
  190. struct KMeansIndexParams : public IndexParams
  191. {
  192. KMeansIndexParams(
  193. int branching = 32,
  194. int iterations = 11,
  195. flann_centers_init_t centers_init = CENTERS_RANDOM,
  196. float cb_index = 0.2,
  197. int trees = 1);
  198. };
  199. @endcode
  200. - **CompositeIndexParams** When using a parameters object of this type the index created
  201. combines the randomized kd-trees and the hierarchical k-means tree. :
  202. @code
  203. struct CompositeIndexParams : public IndexParams
  204. {
  205. CompositeIndexParams(
  206. int trees = 4,
  207. int branching = 32,
  208. int iterations = 11,
  209. flann_centers_init_t centers_init = CENTERS_RANDOM,
  210. float cb_index = 0.2 );
  211. };
  212. @endcode
  213. - **LshIndexParams** When using a parameters object of this type the index created uses
  214. multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search
  215. by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd
  216. International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007).
  217. This algorithm is designed for binary vectors. :
  218. @code
  219. struct LshIndexParams : public IndexParams
  220. {
  221. LshIndexParams(
  222. int table_number,
  223. int key_size,
  224. int multi_probe_level );
  225. };
  226. @endcode
  227. - **AutotunedIndexParams** When passing an object of this type the index created is
  228. automatically tuned to offer the best performance, by choosing the optimal index type
  229. (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. :
  230. @code
  231. struct AutotunedIndexParams : public IndexParams
  232. {
  233. AutotunedIndexParams(
  234. float target_precision = 0.9,
  235. float build_weight = 0.01,
  236. float memory_weight = 0,
  237. float sample_fraction = 0.1 );
  238. };
  239. @endcode
  240. - **SavedIndexParams** This object type is used for loading a previously saved index from the
  241. disk. :
  242. @code
  243. struct SavedIndexParams : public IndexParams
  244. {
  245. SavedIndexParams( String filename );
  246. };
  247. @endcode
  248. */
  249. GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance());
  250. ~GenericIndex();
  251. /** @brief Performs a K-nearest neighbor search for a given query point using the index.
  252. @param query The query point
  253. @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have
  254. at least knn size.
  255. @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have
  256. at least knn size.
  257. @param knn Number of nearest neighbors to search for.
  258. @param params SearchParams
  259. */
  260. void knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices,
  261. std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& params);
  262. void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params);
  263. /** @brief Performs a radius nearest neighbor search for a given query point using the index.
  264. @param query The query point.
  265. @param indices Vector that will contain the indices of the nearest neighbors found.
  266. @param dists Vector that will contain the distances to the nearest neighbors found. It has the same
  267. number of elements as indices.
  268. @param radius The search radius.
  269. @param params SearchParams
  270. This function returns the number of nearest neighbors found.
  271. */
  272. int radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices,
  273. std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& params);
  274. int radiusSearch(const Mat& query, Mat& indices, Mat& dists,
  275. DistanceType radius, const ::cvflann::SearchParams& params);
  276. void save(String filename) { nnIndex->save(filename); }
  277. int veclen() const { return nnIndex->veclen(); }
  278. int size() const { return (int)nnIndex->size(); }
  279. ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); }
  280. CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); }
  281. private:
  282. ::cvflann::Index<Distance>* nnIndex;
  283. Mat _dataset;
  284. };
  285. //! @cond IGNORED
  286. #define FLANN_DISTANCE_CHECK \
  287. if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \
  288. printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\
  289. "the distance using cvflann::set_distance_type. This is no longer working as expected "\
  290. "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\
  291. "for example for L1 distance use: GenericIndex< L1<float> > \n"); \
  292. }
  293. template <typename Distance>
  294. GenericIndex<Distance>::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance)
  295. : _dataset(dataset)
  296. {
  297. CV_Assert(dataset.type() == CvType<ElementType>::type());
  298. CV_Assert(dataset.isContinuous());
  299. ::cvflann::Matrix<ElementType> m_dataset((ElementType*)_dataset.ptr<ElementType>(0), _dataset.rows, _dataset.cols);
  300. nnIndex = new ::cvflann::Index<Distance>(m_dataset, params, distance);
  301. FLANN_DISTANCE_CHECK
  302. nnIndex->buildIndex();
  303. }
  304. template <typename Distance>
  305. GenericIndex<Distance>::~GenericIndex()
  306. {
  307. delete nnIndex;
  308. }
  309. template <typename Distance>
  310. void GenericIndex<Distance>::knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& searchParams)
  311. {
  312. ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
  313. ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
  314. ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
  315. FLANN_DISTANCE_CHECK
  316. nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
  317. }
  318. template <typename Distance>
  319. void GenericIndex<Distance>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams)
  320. {
  321. CV_Assert(queries.type() == CvType<ElementType>::type());
  322. CV_Assert(queries.isContinuous());
  323. ::cvflann::Matrix<ElementType> m_queries((ElementType*)queries.ptr<ElementType>(0), queries.rows, queries.cols);
  324. CV_Assert(indices.type() == CV_32S);
  325. CV_Assert(indices.isContinuous());
  326. ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
  327. CV_Assert(dists.type() == CvType<DistanceType>::type());
  328. CV_Assert(dists.isContinuous());
  329. ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
  330. FLANN_DISTANCE_CHECK
  331. nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
  332. }
  333. template <typename Distance>
  334. int GenericIndex<Distance>::radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
  335. {
  336. ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
  337. ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
  338. ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
  339. FLANN_DISTANCE_CHECK
  340. return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
  341. }
  342. template <typename Distance>
  343. int GenericIndex<Distance>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
  344. {
  345. CV_Assert(query.type() == CvType<ElementType>::type());
  346. CV_Assert(query.isContinuous());
  347. ::cvflann::Matrix<ElementType> m_query((ElementType*)query.ptr<ElementType>(0), query.rows, query.cols);
  348. CV_Assert(indices.type() == CV_32S);
  349. CV_Assert(indices.isContinuous());
  350. ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
  351. CV_Assert(dists.type() == CvType<DistanceType>::type());
  352. CV_Assert(dists.isContinuous());
  353. ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
  354. FLANN_DISTANCE_CHECK
  355. return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
  356. }
  357. /**
  358. * @deprecated Use GenericIndex class instead
  359. */
  360. template <typename T>
  361. class Index_
  362. {
  363. public:
  364. typedef typename L2<T>::ElementType ElementType;
  365. typedef typename L2<T>::ResultType DistanceType;
  366. CV_DEPRECATED Index_(const Mat& dataset, const ::cvflann::IndexParams& params)
  367. {
  368. printf("[WARNING] The cv::flann::Index_<T> class is deperecated, use cv::flann::GenericIndex<Distance> instead\n");
  369. CV_Assert(dataset.type() == CvType<ElementType>::type());
  370. CV_Assert(dataset.isContinuous());
  371. ::cvflann::Matrix<ElementType> m_dataset((ElementType*)dataset.ptr<ElementType>(0), dataset.rows, dataset.cols);
  372. if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) {
  373. nnIndex_L1 = NULL;
  374. nnIndex_L2 = new ::cvflann::Index< L2<ElementType> >(m_dataset, params);
  375. }
  376. else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) {
  377. nnIndex_L1 = new ::cvflann::Index< L1<ElementType> >(m_dataset, params);
  378. nnIndex_L2 = NULL;
  379. }
  380. else {
  381. printf("[ERROR] cv::flann::Index_<T> only provides backwards compatibility for the L1 and L2 distances. "
  382. "For other distance types you must use cv::flann::GenericIndex<Distance>\n");
  383. CV_Assert(0);
  384. }
  385. if (nnIndex_L1) nnIndex_L1->buildIndex();
  386. if (nnIndex_L2) nnIndex_L2->buildIndex();
  387. }
  388. CV_DEPRECATED ~Index_()
  389. {
  390. if (nnIndex_L1) delete nnIndex_L1;
  391. if (nnIndex_L2) delete nnIndex_L2;
  392. }
  393. CV_DEPRECATED void knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& searchParams)
  394. {
  395. ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
  396. ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
  397. ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
  398. if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
  399. if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
  400. }
  401. CV_DEPRECATED void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams)
  402. {
  403. CV_Assert(queries.type() == CvType<ElementType>::type());
  404. CV_Assert(queries.isContinuous());
  405. ::cvflann::Matrix<ElementType> m_queries((ElementType*)queries.ptr<ElementType>(0), queries.rows, queries.cols);
  406. CV_Assert(indices.type() == CV_32S);
  407. CV_Assert(indices.isContinuous());
  408. ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
  409. CV_Assert(dists.type() == CvType<DistanceType>::type());
  410. CV_Assert(dists.isContinuous());
  411. ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
  412. if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
  413. if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
  414. }
  415. CV_DEPRECATED int radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
  416. {
  417. ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
  418. ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
  419. ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
  420. if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
  421. if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
  422. }
  423. CV_DEPRECATED int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
  424. {
  425. CV_Assert(query.type() == CvType<ElementType>::type());
  426. CV_Assert(query.isContinuous());
  427. ::cvflann::Matrix<ElementType> m_query((ElementType*)query.ptr<ElementType>(0), query.rows, query.cols);
  428. CV_Assert(indices.type() == CV_32S);
  429. CV_Assert(indices.isContinuous());
  430. ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
  431. CV_Assert(dists.type() == CvType<DistanceType>::type());
  432. CV_Assert(dists.isContinuous());
  433. ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
  434. if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
  435. if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
  436. }
  437. CV_DEPRECATED void save(String filename)
  438. {
  439. if (nnIndex_L1) nnIndex_L1->save(filename);
  440. if (nnIndex_L2) nnIndex_L2->save(filename);
  441. }
  442. CV_DEPRECATED int veclen() const
  443. {
  444. if (nnIndex_L1) return nnIndex_L1->veclen();
  445. if (nnIndex_L2) return nnIndex_L2->veclen();
  446. }
  447. CV_DEPRECATED int size() const
  448. {
  449. if (nnIndex_L1) return nnIndex_L1->size();
  450. if (nnIndex_L2) return nnIndex_L2->size();
  451. }
  452. CV_DEPRECATED ::cvflann::IndexParams getParameters()
  453. {
  454. if (nnIndex_L1) return nnIndex_L1->getParameters();
  455. if (nnIndex_L2) return nnIndex_L2->getParameters();
  456. }
  457. CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters()
  458. {
  459. if (nnIndex_L1) return nnIndex_L1->getIndexParameters();
  460. if (nnIndex_L2) return nnIndex_L2->getIndexParameters();
  461. }
  462. private:
  463. // providing backwards compatibility for L2 and L1 distances (most common)
  464. ::cvflann::Index< L2<ElementType> >* nnIndex_L2;
  465. ::cvflann::Index< L1<ElementType> >* nnIndex_L1;
  466. };
  467. //! @endcond
  468. /** @brief Clusters features using hierarchical k-means algorithm.
  469. @param features The points to be clustered. The matrix must have elements of type
  470. Distance::ElementType.
  471. @param centers The centers of the clusters obtained. The matrix must have type
  472. Distance::CentersType. The number of rows in this matrix represents the number of clusters desired,
  473. however, because of the way the cut in the hierarchical tree is chosen, the number of clusters
  474. computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of
  475. clusters desired, where branching is the tree's branching factor (see description of the
  476. KMeansIndexParams).
  477. @param params Parameters used in the construction of the hierarchical k-means tree.
  478. @param d Distance to be used for clustering.
  479. The method clusters the given feature vectors by constructing a hierarchical k-means tree and
  480. choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters
  481. found.
  482. */
  483. template <typename Distance>
  484. int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params,
  485. Distance d = Distance())
  486. {
  487. typedef typename Distance::ElementType ElementType;
  488. typedef typename Distance::CentersType CentersType;
  489. CV_Assert(features.type() == CvType<ElementType>::type());
  490. CV_Assert(features.isContinuous());
  491. ::cvflann::Matrix<ElementType> m_features((ElementType*)features.ptr<ElementType>(0), features.rows, features.cols);
  492. CV_Assert(centers.type() == CvType<CentersType>::type());
  493. CV_Assert(centers.isContinuous());
  494. ::cvflann::Matrix<CentersType> m_centers((CentersType*)centers.ptr<CentersType>(0), centers.rows, centers.cols);
  495. return ::cvflann::hierarchicalClustering<Distance>(m_features, m_centers, params, d);
  496. }
  497. //! @cond IGNORED
  498. template <typename ELEM_TYPE, typename DIST_TYPE>
  499. CV_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params)
  500. {
  501. printf("[WARNING] cv::flann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE> is deprecated, use "
  502. "cv::flann::hierarchicalClustering<Distance> instead\n");
  503. if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) {
  504. return hierarchicalClustering< L2<ELEM_TYPE> >(features, centers, params);
  505. }
  506. else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) {
  507. return hierarchicalClustering< L1<ELEM_TYPE> >(features, centers, params);
  508. }
  509. else {
  510. printf("[ERROR] cv::flann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE> only provides backwards "
  511. "compatibility for the L1 and L2 distances. "
  512. "For other distance types you must use cv::flann::hierarchicalClustering<Distance>\n");
  513. CV_Assert(0);
  514. }
  515. }
  516. //! @endcond
  517. //! @} flann
  518. } } // namespace cv::flann
  519. #endif