flann_base.hpp 8.7 KB

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