sparse_matching_gpc.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. By downloading, copying, installing or using the software you agree to this
  3. license. If you do not agree to this license, do not download, install,
  4. copy or use the software.
  5. License Agreement
  6. For Open Source Computer Vision Library
  7. (3-clause BSD License)
  8. Copyright (C) 2016, OpenCV Foundation, all rights reserved.
  9. Third party copyrights are property of their respective owners.
  10. Redistribution and use in source and binary forms, with or without modification,
  11. are permitted provided that the following conditions are met:
  12. * Redistributions of source code must retain the above copyright notice,
  13. this list of conditions and the following disclaimer.
  14. * Redistributions in binary form must reproduce the above copyright notice,
  15. this list of conditions and the following disclaimer in the documentation
  16. and/or other materials provided with the distribution.
  17. * Neither the names of the copyright holders nor the names of the contributors
  18. may be used to endorse or promote products derived from this software
  19. without specific prior written permission.
  20. This software is provided by the copyright holders and contributors "as is" and
  21. any express or implied warranties, including, but not limited to, the implied
  22. warranties of merchantability and fitness for a particular purpose are
  23. disclaimed. In no event shall copyright holders or contributors be liable for
  24. any direct, indirect, incidental, special, exemplary, or consequential damages
  25. (including, but not limited to, procurement of substitute goods or services;
  26. loss of use, data, or profits; or business interruption) however caused
  27. and on any theory of liability, whether in contract, strict liability,
  28. or tort (including negligence or otherwise) arising in any way out of
  29. the use of this software, even if advised of the possibility of such damage.
  30. */
  31. /**
  32. * @file sparse_matching_gpc.hpp
  33. * @author Vladislav Samsonov <vvladxx@gmail.com>
  34. * @brief Implementation of the Global Patch Collider.
  35. *
  36. * Implementation of the Global Patch Collider algorithm from the following paper:
  37. * http://research.microsoft.com/en-us/um/people/pkohli/papers/wfrik_cvpr2016.pdf
  38. *
  39. * @cite Wang_2016_CVPR
  40. */
  41. #ifndef __OPENCV_OPTFLOW_SPARSE_MATCHING_GPC_HPP__
  42. #define __OPENCV_OPTFLOW_SPARSE_MATCHING_GPC_HPP__
  43. #include "opencv2/core.hpp"
  44. #include "opencv2/imgproc.hpp"
  45. namespace cv
  46. {
  47. namespace optflow
  48. {
  49. //! @addtogroup optflow
  50. //! @{
  51. struct CV_EXPORTS_W GPCPatchDescriptor
  52. {
  53. static const unsigned nFeatures = 18; //!< number of features in a patch descriptor
  54. Vec< double, nFeatures > feature;
  55. double dot( const Vec< double, nFeatures > &coef ) const;
  56. void markAsSeparated() { feature[0] = std::numeric_limits< double >::quiet_NaN(); }
  57. bool isSeparated() const { return cvIsNaN( feature[0] ) != 0; }
  58. };
  59. struct CV_EXPORTS_W GPCPatchSample
  60. {
  61. GPCPatchDescriptor ref;
  62. GPCPatchDescriptor pos;
  63. GPCPatchDescriptor neg;
  64. void getDirections( bool &refdir, bool &posdir, bool &negdir, const Vec< double, GPCPatchDescriptor::nFeatures > &coef, double rhs ) const;
  65. };
  66. typedef std::vector< GPCPatchSample > GPCSamplesVector;
  67. /** @brief Descriptor types for the Global Patch Collider.
  68. */
  69. enum GPCDescType
  70. {
  71. GPC_DESCRIPTOR_DCT = 0, //!< Better quality but slow
  72. GPC_DESCRIPTOR_WHT //!< Worse quality but much faster
  73. };
  74. /** @brief Class encapsulating training samples.
  75. */
  76. class CV_EXPORTS_W GPCTrainingSamples
  77. {
  78. private:
  79. GPCSamplesVector samples;
  80. int descriptorType;
  81. public:
  82. /** @brief This function can be used to extract samples from a pair of images and a ground truth flow.
  83. * Sizes of all the provided vectors must be equal.
  84. */
  85. static Ptr< GPCTrainingSamples > create( const std::vector< String > &imagesFrom, const std::vector< String > &imagesTo,
  86. const std::vector< String > &gt, int descriptorType );
  87. static Ptr< GPCTrainingSamples > create( InputArrayOfArrays imagesFrom, InputArrayOfArrays imagesTo, InputArrayOfArrays gt,
  88. int descriptorType );
  89. size_t size() const { return samples.size(); }
  90. int type() const { return descriptorType; }
  91. operator GPCSamplesVector &() { return samples; }
  92. };
  93. /** @brief Class encapsulating training parameters.
  94. */
  95. struct GPCTrainingParams
  96. {
  97. unsigned maxTreeDepth; //!< Maximum tree depth to stop partitioning.
  98. int minNumberOfSamples; //!< Minimum number of samples in the node to stop partitioning.
  99. int descriptorType; //!< Type of descriptors to use.
  100. bool printProgress; //!< Print progress to stdout.
  101. GPCTrainingParams( unsigned _maxTreeDepth = 20, int _minNumberOfSamples = 3, GPCDescType _descriptorType = GPC_DESCRIPTOR_DCT,
  102. bool _printProgress = true )
  103. : maxTreeDepth( _maxTreeDepth ), minNumberOfSamples( _minNumberOfSamples ), descriptorType( _descriptorType ),
  104. printProgress( _printProgress )
  105. {
  106. CV_Assert( check() );
  107. }
  108. GPCTrainingParams( const GPCTrainingParams &params )
  109. : maxTreeDepth( params.maxTreeDepth ), minNumberOfSamples( params.minNumberOfSamples ), descriptorType( params.descriptorType ),
  110. printProgress( params.printProgress )
  111. {
  112. CV_Assert( check() );
  113. }
  114. bool check() const { return maxTreeDepth > 1 && minNumberOfSamples > 1; }
  115. };
  116. /** @brief Class encapsulating matching parameters.
  117. */
  118. struct GPCMatchingParams
  119. {
  120. bool useOpenCL; //!< Whether to use OpenCL to speed up the matching.
  121. GPCMatchingParams( bool _useOpenCL = false ) : useOpenCL( _useOpenCL ) {}
  122. GPCMatchingParams( const GPCMatchingParams &params ) : useOpenCL( params.useOpenCL ) {}
  123. };
  124. /** @brief Class for individual tree.
  125. */
  126. class CV_EXPORTS_W GPCTree : public Algorithm
  127. {
  128. public:
  129. struct Node
  130. {
  131. Vec< double, GPCPatchDescriptor::nFeatures > coef; //!< Hyperplane coefficients
  132. double rhs; //!< Bias term of the hyperplane
  133. unsigned left;
  134. unsigned right;
  135. bool operator==( const Node &n ) const { return coef == n.coef && rhs == n.rhs && left == n.left && right == n.right; }
  136. };
  137. private:
  138. typedef GPCSamplesVector::iterator SIter;
  139. std::vector< Node > nodes;
  140. GPCTrainingParams params;
  141. bool trainNode( size_t nodeId, SIter begin, SIter end, unsigned depth );
  142. public:
  143. void train( GPCTrainingSamples &samples, const GPCTrainingParams params = GPCTrainingParams() );
  144. void write( FileStorage &fs ) const;
  145. void read( const FileNode &fn );
  146. unsigned findLeafForPatch( const GPCPatchDescriptor &descr ) const;
  147. static Ptr< GPCTree > create() { return makePtr< GPCTree >(); }
  148. bool operator==( const GPCTree &t ) const { return nodes == t.nodes; }
  149. int getDescriptorType() const { return params.descriptorType; }
  150. };
  151. template < int T > class CV_EXPORTS_W GPCForest : public Algorithm
  152. {
  153. private:
  154. struct Trail
  155. {
  156. unsigned leaf[T]; //!< Inside which leaf of the tree 0..T the patch fell?
  157. Point2i coord; //!< Patch coordinates.
  158. bool operator==( const Trail &trail ) const { return memcmp( leaf, trail.leaf, sizeof( leaf ) ) == 0; }
  159. bool operator<( const Trail &trail ) const
  160. {
  161. for ( int i = 0; i < T - 1; ++i )
  162. if ( leaf[i] != trail.leaf[i] )
  163. return leaf[i] < trail.leaf[i];
  164. return leaf[T - 1] < trail.leaf[T - 1];
  165. }
  166. };
  167. class ParallelTrailsFilling : public ParallelLoopBody
  168. {
  169. private:
  170. const GPCForest *forest;
  171. const std::vector< GPCPatchDescriptor > *descr;
  172. std::vector< Trail > *trails;
  173. ParallelTrailsFilling &operator=( const ParallelTrailsFilling & );
  174. public:
  175. ParallelTrailsFilling( const GPCForest *_forest, const std::vector< GPCPatchDescriptor > *_descr, std::vector< Trail > *_trails )
  176. : forest( _forest ), descr( _descr ), trails( _trails ){};
  177. void operator()( const Range &range ) const
  178. {
  179. for ( int t = range.start; t < range.end; ++t )
  180. for ( size_t i = 0; i < descr->size(); ++i )
  181. trails->at( i ).leaf[t] = forest->tree[t].findLeafForPatch( descr->at( i ) );
  182. }
  183. };
  184. GPCTree tree[T];
  185. public:
  186. /** @brief Train the forest using one sample set for every tree.
  187. * Please, consider using the next method instead of this one for better quality.
  188. */
  189. void train( GPCTrainingSamples &samples, const GPCTrainingParams params = GPCTrainingParams() )
  190. {
  191. for ( int i = 0; i < T; ++i )
  192. tree[i].train( samples, params );
  193. }
  194. /** @brief Train the forest using individual samples for each tree.
  195. * It is generally better to use this instead of the first method.
  196. */
  197. void train( const std::vector< String > &imagesFrom, const std::vector< String > &imagesTo, const std::vector< String > &gt,
  198. const GPCTrainingParams params = GPCTrainingParams() )
  199. {
  200. for ( int i = 0; i < T; ++i )
  201. {
  202. Ptr< GPCTrainingSamples > samples =
  203. GPCTrainingSamples::create( imagesFrom, imagesTo, gt, params.descriptorType ); // Create training set for the tree
  204. tree[i].train( *samples, params );
  205. }
  206. }
  207. void train( InputArrayOfArrays imagesFrom, InputArrayOfArrays imagesTo, InputArrayOfArrays gt,
  208. const GPCTrainingParams params = GPCTrainingParams() )
  209. {
  210. for ( int i = 0; i < T; ++i )
  211. {
  212. Ptr< GPCTrainingSamples > samples =
  213. GPCTrainingSamples::create( imagesFrom, imagesTo, gt, params.descriptorType ); // Create training set for the tree
  214. tree[i].train( *samples, params );
  215. }
  216. }
  217. void write( FileStorage &fs ) const
  218. {
  219. fs << "ntrees" << T << "trees"
  220. << "[";
  221. for ( int i = 0; i < T; ++i )
  222. {
  223. fs << "{";
  224. tree[i].write( fs );
  225. fs << "}";
  226. }
  227. fs << "]";
  228. }
  229. void read( const FileNode &fn )
  230. {
  231. CV_Assert( T <= (int)fn["ntrees"] );
  232. FileNodeIterator it = fn["trees"].begin();
  233. for ( int i = 0; i < T; ++i, ++it )
  234. tree[i].read( *it );
  235. }
  236. /** @brief Find correspondences between two images.
  237. * @param[in] imgFrom First image in a sequence.
  238. * @param[in] imgTo Second image in a sequence.
  239. * @param[out] corr Output vector with pairs of corresponding points.
  240. * @param[in] params Additional matching parameters for fine-tuning.
  241. */
  242. void findCorrespondences( InputArray imgFrom, InputArray imgTo, std::vector< std::pair< Point2i, Point2i > > &corr,
  243. const GPCMatchingParams params = GPCMatchingParams() ) const;
  244. static Ptr< GPCForest > create() { return makePtr< GPCForest >(); }
  245. };
  246. class CV_EXPORTS_W GPCDetails
  247. {
  248. public:
  249. static void dropOutliers( std::vector< std::pair< Point2i, Point2i > > &corr );
  250. static void getAllDescriptorsForImage( const Mat *imgCh, std::vector< GPCPatchDescriptor > &descr, const GPCMatchingParams &mp,
  251. int type );
  252. static void getCoordinatesFromIndex( size_t index, Size sz, int &x, int &y );
  253. };
  254. template < int T >
  255. void GPCForest< T >::findCorrespondences( InputArray imgFrom, InputArray imgTo, std::vector< std::pair< Point2i, Point2i > > &corr,
  256. const GPCMatchingParams params ) const
  257. {
  258. CV_Assert( imgFrom.channels() == 3 );
  259. CV_Assert( imgTo.channels() == 3 );
  260. Mat from, to;
  261. imgFrom.getMat().convertTo( from, CV_32FC3 );
  262. imgTo.getMat().convertTo( to, CV_32FC3 );
  263. cvtColor( from, from, COLOR_BGR2YCrCb );
  264. cvtColor( to, to, COLOR_BGR2YCrCb );
  265. Mat fromCh[3], toCh[3];
  266. split( from, fromCh );
  267. split( to, toCh );
  268. std::vector< GPCPatchDescriptor > descr;
  269. GPCDetails::getAllDescriptorsForImage( fromCh, descr, params, tree[0].getDescriptorType() );
  270. std::vector< Trail > trailsFrom( descr.size() ), trailsTo( descr.size() );
  271. for ( size_t i = 0; i < descr.size(); ++i )
  272. GPCDetails::getCoordinatesFromIndex( i, from.size(), trailsFrom[i].coord.x, trailsFrom[i].coord.y );
  273. parallel_for_( Range( 0, T ), ParallelTrailsFilling( this, &descr, &trailsFrom ) );
  274. descr.clear();
  275. GPCDetails::getAllDescriptorsForImage( toCh, descr, params, tree[0].getDescriptorType() );
  276. for ( size_t i = 0; i < descr.size(); ++i )
  277. GPCDetails::getCoordinatesFromIndex( i, to.size(), trailsTo[i].coord.x, trailsTo[i].coord.y );
  278. parallel_for_( Range( 0, T ), ParallelTrailsFilling( this, &descr, &trailsTo ) );
  279. std::sort( trailsFrom.begin(), trailsFrom.end() );
  280. std::sort( trailsTo.begin(), trailsTo.end() );
  281. for ( size_t i = 0; i < trailsFrom.size(); ++i )
  282. {
  283. bool uniq = true;
  284. while ( i + 1 < trailsFrom.size() && trailsFrom[i] == trailsFrom[i + 1] )
  285. ++i, uniq = false;
  286. if ( uniq )
  287. {
  288. typename std::vector< Trail >::const_iterator lb = std::lower_bound( trailsTo.begin(), trailsTo.end(), trailsFrom[i] );
  289. if ( lb != trailsTo.end() && *lb == trailsFrom[i] && ( ( lb + 1 ) == trailsTo.end() || !( *lb == *( lb + 1 ) ) ) )
  290. corr.push_back( std::make_pair( trailsFrom[i].coord, lb->coord ) );
  291. }
  292. }
  293. GPCDetails::dropOutliers( corr );
  294. }
  295. //! @}
  296. } // namespace optflow
  297. CV_EXPORTS void write( FileStorage &fs, const String &name, const optflow::GPCTree::Node &node );
  298. CV_EXPORTS void read( const FileNode &fn, optflow::GPCTree::Node &node, optflow::GPCTree::Node );
  299. } // namespace cv
  300. #endif