flann_base.hpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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_BASE_HPP_
  31. #define OPENCV_FLANN_BASE_HPP_
  32. #include <vector>
  33. #include <cassert>
  34. #include <cstdio>
  35. #include "general.h"
  36. #include "matrix.h"
  37. #include "params.h"
  38. #include "saving.h"
  39. #include "all_indices.h"
  40. namespace cvflann
  41. {
  42. /**
  43. * Sets the log level used for all flann functions
  44. * @param level Verbosity level
  45. */
  46. inline void log_verbosity(int level)
  47. {
  48. if (level >= 0) {
  49. Logger::setLevel(level);
  50. }
  51. }
  52. /**
  53. * (Deprecated) Index parameters for creating a saved index.
  54. */
  55. struct SavedIndexParams : public IndexParams
  56. {
  57. SavedIndexParams(cv::String filename)
  58. {
  59. (* this)["algorithm"] = FLANN_INDEX_SAVED;
  60. (*this)["filename"] = filename;
  61. }
  62. };
  63. template<typename Distance>
  64. NNIndex<Distance>* load_saved_index(const Matrix<typename Distance::ElementType>& dataset, const cv::String& filename, Distance distance)
  65. {
  66. typedef typename Distance::ElementType ElementType;
  67. FILE* fin = fopen(filename.c_str(), "rb");
  68. if (fin == NULL) {
  69. return NULL;
  70. }
  71. IndexHeader header = load_header(fin);
  72. if (header.data_type != Datatype<ElementType>::type()) {
  73. fclose(fin);
  74. throw FLANNException("Datatype of saved index is different than of the one to be created.");
  75. }
  76. if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) {
  77. fclose(fin);
  78. throw FLANNException("The index saved belongs to a different dataset");
  79. }
  80. IndexParams params;
  81. params["algorithm"] = header.index_type;
  82. NNIndex<Distance>* nnIndex = create_index_by_type<Distance>(dataset, params, distance);
  83. nnIndex->loadIndex(fin);
  84. fclose(fin);
  85. return nnIndex;
  86. }
  87. template<typename Distance>
  88. class Index : public NNIndex<Distance>
  89. {
  90. public:
  91. typedef typename Distance::ElementType ElementType;
  92. typedef typename Distance::ResultType DistanceType;
  93. Index(const Matrix<ElementType>& features, const IndexParams& params, Distance distance = Distance() )
  94. : index_params_(params)
  95. {
  96. flann_algorithm_t index_type = get_param<flann_algorithm_t>(params,"algorithm");
  97. loaded_ = false;
  98. if (index_type == FLANN_INDEX_SAVED) {
  99. nnIndex_ = load_saved_index<Distance>(features, get_param<cv::String>(params,"filename"), distance);
  100. loaded_ = true;
  101. }
  102. else {
  103. nnIndex_ = create_index_by_type<Distance>(features, params, distance);
  104. }
  105. }
  106. ~Index()
  107. {
  108. delete nnIndex_;
  109. }
  110. /**
  111. * Builds the index.
  112. */
  113. void buildIndex() CV_OVERRIDE
  114. {
  115. if (!loaded_) {
  116. nnIndex_->buildIndex();
  117. }
  118. }
  119. void save(cv::String filename)
  120. {
  121. FILE* fout = fopen(filename.c_str(), "wb");
  122. if (fout == NULL) {
  123. throw FLANNException("Cannot open file");
  124. }
  125. save_header(fout, *nnIndex_);
  126. saveIndex(fout);
  127. fclose(fout);
  128. }
  129. /**
  130. * \brief Saves the index to a stream
  131. * \param stream The stream to save the index to
  132. */
  133. virtual void saveIndex(FILE* stream) CV_OVERRIDE
  134. {
  135. nnIndex_->saveIndex(stream);
  136. }
  137. /**
  138. * \brief Loads the index from a stream
  139. * \param stream The stream from which the index is loaded
  140. */
  141. virtual void loadIndex(FILE* stream) CV_OVERRIDE
  142. {
  143. nnIndex_->loadIndex(stream);
  144. }
  145. /**
  146. * \returns number of features in this index.
  147. */
  148. size_t veclen() const CV_OVERRIDE
  149. {
  150. return nnIndex_->veclen();
  151. }
  152. /**
  153. * \returns The dimensionality of the features in this index.
  154. */
  155. size_t size() const CV_OVERRIDE
  156. {
  157. return nnIndex_->size();
  158. }
  159. /**
  160. * \returns The index type (kdtree, kmeans,...)
  161. */
  162. flann_algorithm_t getType() const CV_OVERRIDE
  163. {
  164. return nnIndex_->getType();
  165. }
  166. /**
  167. * \returns The amount of memory (in bytes) used by the index.
  168. */
  169. virtual int usedMemory() const CV_OVERRIDE
  170. {
  171. return nnIndex_->usedMemory();
  172. }
  173. /**
  174. * \returns The index parameters
  175. */
  176. IndexParams getParameters() const CV_OVERRIDE
  177. {
  178. return nnIndex_->getParameters();
  179. }
  180. /**
  181. * \brief Perform k-nearest neighbor search
  182. * \param[in] queries The query points for which to find the nearest neighbors
  183. * \param[out] indices The indices of the nearest neighbors found
  184. * \param[out] dists Distances to the nearest neighbors found
  185. * \param[in] knn Number of nearest neighbors to return
  186. * \param[in] params Search parameters
  187. */
  188. void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params) CV_OVERRIDE
  189. {
  190. nnIndex_->knnSearch(queries, indices, dists, knn, params);
  191. }
  192. /**
  193. * \brief Perform radius search
  194. * \param[in] query The query point
  195. * \param[out] indices The indinces of the neighbors found within the given radius
  196. * \param[out] dists The distances to the nearest neighbors found
  197. * \param[in] radius The radius used for search
  198. * \param[in] params Search parameters
  199. * \returns Number of neighbors found
  200. */
  201. int radiusSearch(const Matrix<ElementType>& query, Matrix<int>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) CV_OVERRIDE
  202. {
  203. return nnIndex_->radiusSearch(query, indices, dists, radius, params);
  204. }
  205. /**
  206. * \brief Method that searches for nearest-neighbours
  207. */
  208. void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
  209. {
  210. nnIndex_->findNeighbors(result, vec, searchParams);
  211. }
  212. /**
  213. * \brief Returns actual index
  214. */
  215. CV_DEPRECATED NNIndex<Distance>* getIndex()
  216. {
  217. return nnIndex_;
  218. }
  219. /**
  220. * \brief Returns index parameters.
  221. * \deprecated use getParameters() instead.
  222. */
  223. CV_DEPRECATED const IndexParams* getIndexParameters()
  224. {
  225. return &index_params_;
  226. }
  227. private:
  228. /** Pointer to actual index class */
  229. NNIndex<Distance>* nnIndex_;
  230. /** Indices if the index was loaded from a file */
  231. bool loaded_;
  232. /** Parameters passed to the index */
  233. IndexParams index_params_;
  234. Index(const Index &); // copy disabled
  235. Index& operator=(const Index &); // assign disabled
  236. };
  237. /**
  238. * Performs a hierarchical clustering of the points passed as argument and then takes a cut in the
  239. * the clustering tree to return a flat clustering.
  240. * @param[in] points Points to be clustered
  241. * @param centers The computed cluster centres. Matrix should be preallocated and centers.rows is the
  242. * number of clusters requested.
  243. * @param params Clustering parameters (The same as for cvflann::KMeansIndex)
  244. * @param d Distance to be used for clustering (eg: cvflann::L2)
  245. * @return number of clusters computed (can be different than clusters.rows and is the highest number
  246. * of the form (branching-1)*K+1 smaller than clusters.rows).
  247. */
  248. template <typename Distance>
  249. int hierarchicalClustering(const Matrix<typename Distance::ElementType>& points, Matrix<typename Distance::ResultType>& centers,
  250. const KMeansIndexParams& params, Distance d = Distance())
  251. {
  252. KMeansIndex<Distance> kmeans(points, params, d);
  253. kmeans.buildIndex();
  254. int clusterNum = kmeans.getClusterCenters(centers);
  255. return clusterNum;
  256. }
  257. }
  258. #endif /* OPENCV_FLANN_BASE_HPP_ */