flann_base.hpp 9.1 KB

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