tracking_internals.hpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. #ifndef OPENCV_TRACKING_DETAIL_HPP
  5. #define OPENCV_TRACKING_DETAIL_HPP
  6. /*
  7. * Partially based on:
  8. * ====================================================================================================================
  9. * - [AAM] S. Salti, A. Cavallaro, L. Di Stefano, Adaptive Appearance Modeling for Video Tracking: Survey and Evaluation
  10. * - [AMVOT] X. Li, W. Hu, C. Shen, Z. Zhang, A. Dick, A. van den Hengel, A Survey of Appearance Models in Visual Object Tracking
  11. *
  12. * This Tracking API has been designed with PlantUML. If you modify this API please change UML files under modules/tracking/doc/uml
  13. *
  14. */
  15. #include "opencv2/video/detail/tracking.detail.hpp"
  16. #include "feature.hpp" // CvHaarEvaluator
  17. #include "onlineBoosting.hpp" // StrongClassifierDirectSelection
  18. namespace cv {
  19. namespace detail {
  20. inline namespace tracking {
  21. /** @addtogroup tracking_detail
  22. @{
  23. Long-term optical tracking API
  24. ------------------------------
  25. Long-term optical tracking is an important issue for many computer vision applications in
  26. real world scenario. The development in this area is very fragmented and this API is an unique
  27. interface useful for plug several algorithms and compare them. This work is partially based on
  28. @cite AAM and @cite AMVOT .
  29. These algorithms start from a bounding box of the target and with their internal representation they
  30. avoid the drift during the tracking. These long-term trackers are able to evaluate online the
  31. quality of the location of the target in the new frame, without ground truth.
  32. There are three main components: the TrackerContribSampler, the TrackerContribFeatureSet and the TrackerModel. The
  33. first component is the object that computes the patches over the frame based on the last target
  34. location. The TrackerContribFeatureSet is the class that manages the Features, is possible plug many kind
  35. of these (HAAR, HOG, LBP, Feature2D, etc). The last component is the internal representation of the
  36. target, it is the appearance model. It stores all state candidates and compute the trajectory (the
  37. most likely target states). The class TrackerTargetState represents a possible state of the target.
  38. The TrackerContribSampler and the TrackerContribFeatureSet are the visual representation of the target, instead
  39. the TrackerModel is the statistical model.
  40. A recent benchmark between these algorithms can be found in @cite OOT
  41. Creating Your Own %Tracker
  42. --------------------
  43. If you want to create a new tracker, here's what you have to do. First, decide on the name of the class
  44. for the tracker (to meet the existing style, we suggest something with prefix "tracker", e.g.
  45. trackerMIL, trackerBoosting) -- we shall refer to this choice as to "classname" in subsequent.
  46. - Declare your tracker in modules/tracking/include/opencv2/tracking/tracker.hpp. Your tracker should inherit from
  47. Tracker (please, see the example below). You should declare the specialized Param structure,
  48. where you probably will want to put the data, needed to initialize your tracker. You should
  49. get something similar to :
  50. @code
  51. class CV_EXPORTS_W TrackerMIL : public Tracker
  52. {
  53. public:
  54. struct CV_EXPORTS Params
  55. {
  56. Params();
  57. //parameters for sampler
  58. float samplerInitInRadius; // radius for gathering positive instances during init
  59. int samplerInitMaxNegNum; // # negative samples to use during init
  60. float samplerSearchWinSize; // size of search window
  61. float samplerTrackInRadius; // radius for gathering positive instances during tracking
  62. int samplerTrackMaxPosNum; // # positive samples to use during tracking
  63. int samplerTrackMaxNegNum; // # negative samples to use during tracking
  64. int featureSetNumFeatures; // #features
  65. void read( const FileNode& fn );
  66. void write( FileStorage& fs ) const;
  67. };
  68. @endcode
  69. of course, you can also add any additional methods of your choice. It should be pointed out,
  70. however, that it is not expected to have a constructor declared, as creation should be done via
  71. the corresponding create() method.
  72. - Finally, you should implement the function with signature :
  73. @code
  74. Ptr<classname> classname::create(const classname::Params &parameters){
  75. ...
  76. }
  77. @endcode
  78. That function can (and probably will) return a pointer to some derived class of "classname",
  79. which will probably have a real constructor.
  80. Every tracker has three component TrackerContribSampler, TrackerContribFeatureSet and TrackerModel. The first two
  81. are instantiated from Tracker base class, instead the last component is abstract, so you must
  82. implement your TrackerModel.
  83. ### TrackerContribSampler
  84. TrackerContribSampler is already instantiated, but you should define the sampling algorithm and add the
  85. classes (or single class) to TrackerContribSampler. You can choose one of the ready implementation as
  86. TrackerContribSamplerCSC or you can implement your sampling method, in this case the class must inherit
  87. TrackerContribSamplerAlgorithm. Fill the samplingImpl method that writes the result in "sample" output
  88. argument.
  89. Example of creating specialized TrackerContribSamplerAlgorithm TrackerContribSamplerCSC : :
  90. @code
  91. class CV_EXPORTS_W TrackerContribSamplerCSC : public TrackerContribSamplerAlgorithm
  92. {
  93. public:
  94. TrackerContribSamplerCSC( const TrackerContribSamplerCSC::Params &parameters = TrackerContribSamplerCSC::Params() );
  95. ~TrackerContribSamplerCSC();
  96. ...
  97. protected:
  98. bool samplingImpl( const Mat& image, Rect boundingBox, std::vector<Mat>& sample );
  99. ...
  100. };
  101. @endcode
  102. Example of adding TrackerContribSamplerAlgorithm to TrackerContribSampler : :
  103. @code
  104. //sampler is the TrackerContribSampler
  105. Ptr<TrackerContribSamplerAlgorithm> CSCSampler = new TrackerContribSamplerCSC( CSCparameters );
  106. if( !sampler->addTrackerSamplerAlgorithm( CSCSampler ) )
  107. return false;
  108. //or add CSC sampler with default parameters
  109. //sampler->addTrackerSamplerAlgorithm( "CSC" );
  110. @endcode
  111. @sa
  112. TrackerContribSamplerCSC, TrackerContribSamplerAlgorithm
  113. ### TrackerContribFeatureSet
  114. TrackerContribFeatureSet is already instantiated (as first) , but you should define what kinds of features
  115. you'll use in your tracker. You can use multiple feature types, so you can add a ready
  116. implementation as TrackerContribFeatureHAAR in your TrackerContribFeatureSet or develop your own implementation.
  117. In this case, in the computeImpl method put the code that extract the features and in the selection
  118. method optionally put the code for the refinement and selection of the features.
  119. Example of creating specialized TrackerFeature TrackerContribFeatureHAAR : :
  120. @code
  121. class CV_EXPORTS_W TrackerContribFeatureHAAR : public TrackerFeature
  122. {
  123. public:
  124. TrackerContribFeatureHAAR( const TrackerContribFeatureHAAR::Params &parameters = TrackerContribFeatureHAAR::Params() );
  125. ~TrackerContribFeatureHAAR();
  126. void selection( Mat& response, int npoints );
  127. ...
  128. protected:
  129. bool computeImpl( const std::vector<Mat>& images, Mat& response );
  130. ...
  131. };
  132. @endcode
  133. Example of adding TrackerFeature to TrackerContribFeatureSet : :
  134. @code
  135. //featureSet is the TrackerContribFeatureSet
  136. Ptr<TrackerFeature> trackerFeature = new TrackerContribFeatureHAAR( HAARparameters );
  137. featureSet->addTrackerFeature( trackerFeature );
  138. @endcode
  139. @sa
  140. TrackerContribFeatureHAAR, TrackerContribFeatureSet
  141. ### TrackerModel
  142. TrackerModel is abstract, so in your implementation you must develop your TrackerModel that inherit
  143. from TrackerModel. Fill the method for the estimation of the state "modelEstimationImpl", that
  144. estimates the most likely target location, see @cite AAM table I (ME) for further information. Fill
  145. "modelUpdateImpl" in order to update the model, see @cite AAM table I (MU). In this class you can use
  146. the :cConfidenceMap and :cTrajectory to storing the model. The first represents the model on the all
  147. possible candidate states and the second represents the list of all estimated states.
  148. Example of creating specialized TrackerModel TrackerMILModel : :
  149. @code
  150. class TrackerMILModel : public TrackerModel
  151. {
  152. public:
  153. TrackerMILModel( const Rect& boundingBox );
  154. ~TrackerMILModel();
  155. ...
  156. protected:
  157. void modelEstimationImpl( const std::vector<Mat>& responses );
  158. void modelUpdateImpl();
  159. ...
  160. };
  161. @endcode
  162. And add it in your Tracker : :
  163. @code
  164. bool TrackerMIL::initImpl( const Mat& image, const Rect2d& boundingBox )
  165. {
  166. ...
  167. //model is the general TrackerModel field of the general Tracker
  168. model = new TrackerMILModel( boundingBox );
  169. ...
  170. }
  171. @endcode
  172. In the last step you should define the TrackerStateEstimator based on your implementation or you can
  173. use one of ready class as TrackerStateEstimatorMILBoosting. It represent the statistical part of the
  174. model that estimates the most likely target state.
  175. Example of creating specialized TrackerStateEstimator TrackerStateEstimatorMILBoosting : :
  176. @code
  177. class CV_EXPORTS_W TrackerStateEstimatorMILBoosting : public TrackerStateEstimator
  178. {
  179. class TrackerMILTargetState : public TrackerTargetState
  180. {
  181. ...
  182. };
  183. public:
  184. TrackerStateEstimatorMILBoosting( int nFeatures = 250 );
  185. ~TrackerStateEstimatorMILBoosting();
  186. ...
  187. protected:
  188. Ptr<TrackerTargetState> estimateImpl( const std::vector<ConfidenceMap>& confidenceMaps );
  189. void updateImpl( std::vector<ConfidenceMap>& confidenceMaps );
  190. ...
  191. };
  192. @endcode
  193. And add it in your TrackerModel : :
  194. @code
  195. //model is the TrackerModel of your Tracker
  196. Ptr<TrackerStateEstimatorMILBoosting> stateEstimator = new TrackerStateEstimatorMILBoosting( params.featureSetNumFeatures );
  197. model->setTrackerStateEstimator( stateEstimator );
  198. @endcode
  199. @sa
  200. TrackerModel, TrackerStateEstimatorMILBoosting, TrackerTargetState
  201. During this step, you should define your TrackerTargetState based on your implementation.
  202. TrackerTargetState base class has only the bounding box (upper-left position, width and height), you
  203. can enrich it adding scale factor, target rotation, etc.
  204. Example of creating specialized TrackerTargetState TrackerMILTargetState : :
  205. @code
  206. class TrackerMILTargetState : public TrackerTargetState
  207. {
  208. public:
  209. TrackerMILTargetState( const Point2f& position, int targetWidth, int targetHeight, bool foreground, const Mat& features );
  210. ~TrackerMILTargetState();
  211. ...
  212. private:
  213. bool isTarget;
  214. Mat targetFeatures;
  215. ...
  216. };
  217. @endcode
  218. */
  219. /************************************ TrackerContribFeature Base Classes ************************************/
  220. /** @brief Abstract base class for TrackerContribFeature that represents the feature.
  221. */
  222. class CV_EXPORTS TrackerContribFeature : public TrackerFeature
  223. {
  224. public:
  225. virtual ~TrackerContribFeature();
  226. /** @brief Create TrackerContribFeature by tracker feature type
  227. @param trackerFeatureType The TrackerContribFeature name
  228. The modes available now:
  229. - "HAAR" -- Haar Feature-based
  230. The modes that will be available soon:
  231. - "HOG" -- Histogram of Oriented Gradients features
  232. - "LBP" -- Local Binary Pattern features
  233. - "FEATURE2D" -- All types of Feature2D
  234. */
  235. static Ptr<TrackerContribFeature> create( const String& trackerFeatureType );
  236. /** @brief Identify most effective features
  237. @param response Collection of response for the specific TrackerContribFeature
  238. @param npoints Max number of features
  239. @note This method modifies the response parameter
  240. */
  241. virtual void selection( Mat& response, int npoints ) = 0;
  242. /** @brief Get the name of the specific TrackerContribFeature
  243. */
  244. String getClassName() const;
  245. protected:
  246. String className;
  247. };
  248. /** @brief Class that manages the extraction and selection of features
  249. @cite AAM Feature Extraction and Feature Set Refinement (Feature Processing and Feature Selection).
  250. See table I and section III C @cite AMVOT Appearance modelling -\> Visual representation (Table II,
  251. section 3.1 - 3.2)
  252. TrackerContribFeatureSet is an aggregation of TrackerContribFeature
  253. @sa
  254. TrackerContribFeature
  255. */
  256. class CV_EXPORTS TrackerContribFeatureSet
  257. {
  258. public:
  259. TrackerContribFeatureSet();
  260. ~TrackerContribFeatureSet();
  261. /** @brief Extract features from the images collection
  262. @param images The input images
  263. */
  264. void extraction( const std::vector<Mat>& images );
  265. /** @brief Identify most effective features for all feature types (optional)
  266. */
  267. void selection();
  268. /** @brief Remove outliers for all feature types (optional)
  269. */
  270. void removeOutliers();
  271. /** @brief Add TrackerContribFeature in the collection. Return true if TrackerContribFeature is added, false otherwise
  272. @param trackerFeatureType The TrackerContribFeature name
  273. The modes available now:
  274. - "HAAR" -- Haar Feature-based
  275. The modes that will be available soon:
  276. - "HOG" -- Histogram of Oriented Gradients features
  277. - "LBP" -- Local Binary Pattern features
  278. - "FEATURE2D" -- All types of Feature2D
  279. Example TrackerContribFeatureSet::addTrackerFeature : :
  280. @code
  281. //sample usage:
  282. Ptr<TrackerContribFeature> trackerFeature = ...;
  283. featureSet->addTrackerFeature( trackerFeature );
  284. //or add CSC sampler with default parameters
  285. //featureSet->addTrackerFeature( "HAAR" );
  286. @endcode
  287. @note If you use the second method, you must initialize the TrackerContribFeature
  288. */
  289. bool addTrackerFeature( String trackerFeatureType );
  290. /** @overload
  291. @param feature The TrackerContribFeature class
  292. */
  293. bool addTrackerFeature( Ptr<TrackerContribFeature>& feature );
  294. /** @brief Get the TrackerContribFeature collection (TrackerContribFeature name, TrackerContribFeature pointer)
  295. */
  296. const std::vector<std::pair<String, Ptr<TrackerContribFeature> > >& getTrackerFeature() const;
  297. /** @brief Get the responses
  298. @note Be sure to call extraction before getResponses Example TrackerContribFeatureSet::getResponses : :
  299. */
  300. const std::vector<Mat>& getResponses() const;
  301. private:
  302. void clearResponses();
  303. bool blockAddTrackerFeature;
  304. std::vector<std::pair<String, Ptr<TrackerContribFeature> > > features; //list of features
  305. std::vector<Mat> responses; //list of response after compute
  306. };
  307. /************************************ TrackerContribSampler Base Classes ************************************/
  308. /** @brief Abstract base class for TrackerContribSamplerAlgorithm that represents the algorithm for the specific
  309. sampler.
  310. */
  311. class CV_EXPORTS TrackerContribSamplerAlgorithm : public TrackerSamplerAlgorithm
  312. {
  313. public:
  314. /**
  315. * \brief Destructor
  316. */
  317. virtual ~TrackerContribSamplerAlgorithm();
  318. /** @brief Create TrackerContribSamplerAlgorithm by tracker sampler type.
  319. @param trackerSamplerType The trackerSamplerType name
  320. The modes available now:
  321. - "CSC" -- Current State Center
  322. - "CS" -- Current State
  323. */
  324. static Ptr<TrackerContribSamplerAlgorithm> create( const String& trackerSamplerType );
  325. /** @brief Computes the regions starting from a position in an image.
  326. Return true if samples are computed, false otherwise
  327. @param image The current frame
  328. @param boundingBox The bounding box from which regions can be calculated
  329. @param sample The computed samples @cite AAM Fig. 1 variable Sk
  330. */
  331. virtual bool sampling(const Mat& image, const Rect& boundingBox, std::vector<Mat>& sample) CV_OVERRIDE;
  332. /** @brief Get the name of the specific TrackerContribSamplerAlgorithm
  333. */
  334. String getClassName() const;
  335. protected:
  336. String className;
  337. virtual bool samplingImpl( const Mat& image, Rect boundingBox, std::vector<Mat>& sample ) = 0;
  338. };
  339. /**
  340. * \brief Class that manages the sampler in order to select regions for the update the model of the tracker
  341. * [AAM] Sampling e Labeling. See table I and section III B
  342. */
  343. /** @brief Class that manages the sampler in order to select regions for the update the model of the tracker
  344. @cite AAM Sampling e Labeling. See table I and section III B
  345. TrackerContribSampler is an aggregation of TrackerContribSamplerAlgorithm
  346. @sa
  347. TrackerContribSamplerAlgorithm
  348. */
  349. class CV_EXPORTS TrackerContribSampler
  350. {
  351. public:
  352. /**
  353. * \brief Constructor
  354. */
  355. TrackerContribSampler();
  356. /**
  357. * \brief Destructor
  358. */
  359. ~TrackerContribSampler();
  360. /** @brief Computes the regions starting from a position in an image
  361. @param image The current frame
  362. @param boundingBox The bounding box from which regions can be calculated
  363. */
  364. void sampling( const Mat& image, Rect boundingBox );
  365. /** @brief Return the collection of the TrackerContribSamplerAlgorithm
  366. */
  367. const std::vector<std::pair<String, Ptr<TrackerContribSamplerAlgorithm> > >& getSamplers() const;
  368. /** @brief Return the samples from all TrackerContribSamplerAlgorithm, @cite AAM Fig. 1 variable Sk
  369. */
  370. const std::vector<Mat>& getSamples() const;
  371. /** @brief Add TrackerContribSamplerAlgorithm in the collection. Return true if sampler is added, false otherwise
  372. @param trackerSamplerAlgorithmType The TrackerContribSamplerAlgorithm name
  373. The modes available now:
  374. - "CSC" -- Current State Center
  375. - "CS" -- Current State
  376. - "PF" -- Particle Filtering
  377. Example TrackerContribSamplerAlgorithm::addTrackerContribSamplerAlgorithm : :
  378. @code
  379. TrackerContribSamplerCSC::Params CSCparameters;
  380. Ptr<TrackerContribSamplerAlgorithm> CSCSampler = new TrackerContribSamplerCSC( CSCparameters );
  381. if( !sampler->addTrackerSamplerAlgorithm( CSCSampler ) )
  382. return false;
  383. //or add CSC sampler with default parameters
  384. //sampler->addTrackerSamplerAlgorithm( "CSC" );
  385. @endcode
  386. @note If you use the second method, you must initialize the TrackerContribSamplerAlgorithm
  387. */
  388. bool addTrackerSamplerAlgorithm( String trackerSamplerAlgorithmType );
  389. /** @overload
  390. @param sampler The TrackerContribSamplerAlgorithm
  391. */
  392. bool addTrackerSamplerAlgorithm( Ptr<TrackerContribSamplerAlgorithm>& sampler );
  393. private:
  394. std::vector<std::pair<String, Ptr<TrackerContribSamplerAlgorithm> > > samplers;
  395. std::vector<Mat> samples;
  396. bool blockAddTrackerSampler;
  397. void clearSamples();
  398. };
  399. /** @brief TrackerStateEstimatorAdaBoosting based on ADA-Boosting
  400. */
  401. class CV_EXPORTS TrackerStateEstimatorAdaBoosting : public TrackerStateEstimator
  402. {
  403. public:
  404. /** @brief Implementation of the target state for TrackerAdaBoostingTargetState
  405. */
  406. class CV_EXPORTS TrackerAdaBoostingTargetState : public TrackerTargetState
  407. {
  408. public:
  409. /**
  410. * \brief Constructor
  411. * \param position Top left corner of the bounding box
  412. * \param width Width of the bounding box
  413. * \param height Height of the bounding box
  414. * \param foreground label for target or background
  415. * \param responses list of features
  416. */
  417. TrackerAdaBoostingTargetState( const Point2f& position, int width, int height, bool foreground, const Mat& responses );
  418. /**
  419. * \brief Destructor
  420. */
  421. ~TrackerAdaBoostingTargetState()
  422. {
  423. }
  424. ;
  425. /** @brief Set the features extracted from TrackerContribFeatureSet
  426. @param responses The features extracted
  427. */
  428. void setTargetResponses( const Mat& responses );
  429. /** @brief Set label: true for target foreground, false for background
  430. @param foreground Label for background/foreground
  431. */
  432. void setTargetFg( bool foreground );
  433. /** @brief Get the features extracted
  434. */
  435. Mat getTargetResponses() const;
  436. /** @brief Get the label. Return true for target foreground, false for background
  437. */
  438. bool isTargetFg() const;
  439. private:
  440. bool isTarget;
  441. Mat targetResponses;
  442. };
  443. /** @brief Constructor
  444. @param numClassifer Number of base classifiers
  445. @param initIterations Number of iterations in the initialization
  446. @param nFeatures Number of features/weak classifiers
  447. @param patchSize tracking rect
  448. @param ROI initial ROI
  449. */
  450. TrackerStateEstimatorAdaBoosting( int numClassifer, int initIterations, int nFeatures, Size patchSize, const Rect& ROI );
  451. /**
  452. * \brief Destructor
  453. */
  454. ~TrackerStateEstimatorAdaBoosting();
  455. /** @brief Get the sampling ROI
  456. */
  457. Rect getSampleROI() const;
  458. /** @brief Set the sampling ROI
  459. @param ROI the sampling ROI
  460. */
  461. void setSampleROI( const Rect& ROI );
  462. /** @brief Set the current confidenceMap
  463. @param confidenceMap The current :cConfidenceMap
  464. */
  465. void setCurrentConfidenceMap( ConfidenceMap& confidenceMap );
  466. /** @brief Get the list of the selected weak classifiers for the classification step
  467. */
  468. std::vector<int> computeSelectedWeakClassifier();
  469. /** @brief Get the list of the weak classifiers that should be replaced
  470. */
  471. std::vector<int> computeReplacedClassifier();
  472. /** @brief Get the list of the weak classifiers that replace those to be replaced
  473. */
  474. std::vector<int> computeSwappedClassifier();
  475. protected:
  476. Ptr<TrackerTargetState> estimateImpl( const std::vector<ConfidenceMap>& confidenceMaps ) CV_OVERRIDE;
  477. void updateImpl( std::vector<ConfidenceMap>& confidenceMaps ) CV_OVERRIDE;
  478. Ptr<StrongClassifierDirectSelection> boostClassifier;
  479. private:
  480. int numBaseClassifier;
  481. int iterationInit;
  482. int numFeatures;
  483. bool trained;
  484. Size initPatchSize;
  485. Rect sampleROI;
  486. std::vector<int> replacedClassifier;
  487. std::vector<int> swappedClassifier;
  488. ConfidenceMap currentConfidenceMap;
  489. };
  490. /**
  491. * \brief TrackerStateEstimator based on SVM
  492. */
  493. class CV_EXPORTS TrackerStateEstimatorSVM : public TrackerStateEstimator
  494. {
  495. public:
  496. TrackerStateEstimatorSVM();
  497. ~TrackerStateEstimatorSVM();
  498. protected:
  499. Ptr<TrackerTargetState> estimateImpl( const std::vector<ConfidenceMap>& confidenceMaps ) CV_OVERRIDE;
  500. void updateImpl( std::vector<ConfidenceMap>& confidenceMaps ) CV_OVERRIDE;
  501. };
  502. /************************************ Specific TrackerSamplerAlgorithm Classes ************************************/
  503. /** @brief TrackerSampler based on CSC (current state centered), used by MIL algorithm TrackerMIL
  504. */
  505. class CV_EXPORTS TrackerContribSamplerCSC : public TrackerContribSamplerAlgorithm
  506. {
  507. public:
  508. enum
  509. {
  510. MODE_INIT_POS = 1, //!< mode for init positive samples
  511. MODE_INIT_NEG = 2, //!< mode for init negative samples
  512. MODE_TRACK_POS = 3, //!< mode for update positive samples
  513. MODE_TRACK_NEG = 4, //!< mode for update negative samples
  514. MODE_DETECT = 5 //!< mode for detect samples
  515. };
  516. struct CV_EXPORTS Params
  517. {
  518. Params();
  519. float initInRad; //!< radius for gathering positive instances during init
  520. float trackInPosRad; //!< radius for gathering positive instances during tracking
  521. float searchWinSize; //!< size of search window
  522. int initMaxNegNum; //!< # negative samples to use during init
  523. int trackMaxPosNum; //!< # positive samples to use during training
  524. int trackMaxNegNum; //!< # negative samples to use during training
  525. };
  526. /** @brief Constructor
  527. @param parameters TrackerContribSamplerCSC parameters TrackerContribSamplerCSC::Params
  528. */
  529. TrackerContribSamplerCSC( const TrackerContribSamplerCSC::Params &parameters = TrackerContribSamplerCSC::Params() );
  530. /** @brief Set the sampling mode of TrackerContribSamplerCSC
  531. @param samplingMode The sampling mode
  532. The modes are:
  533. - "MODE_INIT_POS = 1" -- for the positive sampling in initialization step
  534. - "MODE_INIT_NEG = 2" -- for the negative sampling in initialization step
  535. - "MODE_TRACK_POS = 3" -- for the positive sampling in update step
  536. - "MODE_TRACK_NEG = 4" -- for the negative sampling in update step
  537. - "MODE_DETECT = 5" -- for the sampling in detection step
  538. */
  539. void setMode( int samplingMode );
  540. ~TrackerContribSamplerCSC();
  541. protected:
  542. bool samplingImpl(const Mat& image, Rect boundingBox, std::vector<Mat>& sample) CV_OVERRIDE;
  543. private:
  544. Params params;
  545. int mode;
  546. RNG rng;
  547. std::vector<Mat> sampleImage( const Mat& img, int x, int y, int w, int h, float inrad, float outrad = 0, int maxnum = 1000000 );
  548. };
  549. /** @brief TrackerContribSampler based on CS (current state), used by algorithm TrackerBoosting
  550. */
  551. class CV_EXPORTS TrackerSamplerCS : public TrackerContribSamplerAlgorithm
  552. {
  553. public:
  554. enum
  555. {
  556. MODE_POSITIVE = 1, //!< mode for positive samples
  557. MODE_NEGATIVE = 2, //!< mode for negative samples
  558. MODE_CLASSIFY = 3 //!< mode for classify samples
  559. };
  560. struct CV_EXPORTS Params
  561. {
  562. Params();
  563. float overlap; //!<overlapping for the search windows
  564. float searchFactor; //!<search region parameter
  565. };
  566. /** @brief Constructor
  567. @param parameters TrackerSamplerCS parameters TrackerSamplerCS::Params
  568. */
  569. TrackerSamplerCS( const TrackerSamplerCS::Params &parameters = TrackerSamplerCS::Params() );
  570. /** @brief Set the sampling mode of TrackerSamplerCS
  571. @param samplingMode The sampling mode
  572. The modes are:
  573. - "MODE_POSITIVE = 1" -- for the positive sampling
  574. - "MODE_NEGATIVE = 2" -- for the negative sampling
  575. - "MODE_CLASSIFY = 3" -- for the sampling in classification step
  576. */
  577. void setMode( int samplingMode );
  578. ~TrackerSamplerCS();
  579. bool samplingImpl( const Mat& image, Rect boundingBox, std::vector<Mat>& sample ) CV_OVERRIDE;
  580. Rect getROI() const;
  581. private:
  582. Rect getTrackingROI( float searchFactor );
  583. Rect RectMultiply( const Rect & rect, float f );
  584. std::vector<Mat> patchesRegularScan( const Mat& image, Rect trackingROI, Size patchSize );
  585. void setCheckedROI( Rect imageROI );
  586. Params params;
  587. int mode;
  588. Rect trackedPatch;
  589. Rect validROI;
  590. Rect ROI;
  591. };
  592. /** @brief This sampler is based on particle filtering.
  593. In principle, it can be thought of as performing some sort of optimization (and indeed, this
  594. tracker uses opencv's optim module), where tracker seeks to find the rectangle in given frame,
  595. which is the most *"similar"* to the initial rectangle (the one, given through the constructor).
  596. The optimization performed is stochastic and somehow resembles genetic algorithms, where on each new
  597. image received (submitted via TrackerSamplerPF::sampling()) we start with the region bounded by
  598. boundingBox, then generate several "perturbed" boxes, take the ones most similar to the original.
  599. This selection round is repeated several times. At the end, we hope that only the most promising box
  600. remaining, and these are combined to produce the subrectangle of image, which is put as a sole
  601. element in array sample.
  602. It should be noted, that the definition of "similarity" between two rectangles is based on comparing
  603. their histograms. As experiments show, tracker is *not* very succesfull if target is assumed to
  604. strongly change its dimensions.
  605. */
  606. class CV_EXPORTS TrackerSamplerPF : public TrackerContribSamplerAlgorithm
  607. {
  608. public:
  609. /** @brief This structure contains all the parameters that can be varied during the course of sampling
  610. algorithm. Below is the structure exposed, together with its members briefly explained with
  611. reference to the above discussion on algorithm's working.
  612. */
  613. struct CV_EXPORTS Params
  614. {
  615. Params();
  616. int iterationNum; //!< number of selection rounds
  617. int particlesNum; //!< number of "perturbed" boxes on each round
  618. double alpha; //!< with each new round we exponentially decrease the amount of "perturbing" we allow (like in simulated annealing)
  619. //!< and this very alpha controls how fast annealing happens, ie. how fast perturbing decreases
  620. Mat_<double> std; //!< initial values for perturbing (1-by-4 array, as each rectangle is given by 4 values -- coordinates of opposite vertices,
  621. //!< hence we have 4 values to perturb)
  622. };
  623. /** @brief Constructor
  624. @param chosenRect Initial rectangle, that is supposed to contain target we'd like to track.
  625. @param parameters
  626. */
  627. TrackerSamplerPF(const Mat& chosenRect,const TrackerSamplerPF::Params &parameters = TrackerSamplerPF::Params());
  628. protected:
  629. bool samplingImpl( const Mat& image, Rect boundingBox, std::vector<Mat>& sample ) CV_OVERRIDE;
  630. private:
  631. Params params;
  632. Ptr<MinProblemSolver> _solver;
  633. Ptr<MinProblemSolver::Function> _function;
  634. };
  635. /************************************ Specific TrackerContribFeature Classes ************************************/
  636. /**
  637. * \brief TrackerContribFeature based on Feature2D
  638. */
  639. class CV_EXPORTS TrackerFeatureFeature2d : public TrackerContribFeature
  640. {
  641. public:
  642. /**
  643. * \brief Constructor
  644. * \param detectorType string of FeatureDetector
  645. * \param descriptorType string of DescriptorExtractor
  646. */
  647. TrackerFeatureFeature2d( String detectorType, String descriptorType );
  648. ~TrackerFeatureFeature2d() CV_OVERRIDE;
  649. void selection( Mat& response, int npoints ) CV_OVERRIDE;
  650. protected:
  651. bool computeImpl( const std::vector<Mat>& images, Mat& response ) CV_OVERRIDE;
  652. private:
  653. std::vector<KeyPoint> keypoints;
  654. };
  655. /**
  656. * \brief TrackerContribFeature based on HOG
  657. */
  658. class CV_EXPORTS TrackerFeatureHOG : public TrackerContribFeature
  659. {
  660. public:
  661. TrackerFeatureHOG();
  662. ~TrackerFeatureHOG() CV_OVERRIDE;
  663. void selection( Mat& response, int npoints ) CV_OVERRIDE;
  664. protected:
  665. bool computeImpl( const std::vector<Mat>& images, Mat& response ) CV_OVERRIDE;
  666. };
  667. /** @brief TrackerContribFeature based on HAAR features, used by TrackerMIL and many others algorithms
  668. @note HAAR features implementation is copied from apps/traincascade and modified according to MIL
  669. */
  670. class CV_EXPORTS TrackerContribFeatureHAAR : public TrackerContribFeature
  671. {
  672. public:
  673. struct CV_EXPORTS Params
  674. {
  675. Params();
  676. int numFeatures; //!< # of rects
  677. Size rectSize; //!< rect size
  678. bool isIntegral; //!< true if input images are integral, false otherwise
  679. };
  680. /** @brief Constructor
  681. @param parameters TrackerContribFeatureHAAR parameters TrackerContribFeatureHAAR::Params
  682. */
  683. TrackerContribFeatureHAAR( const TrackerContribFeatureHAAR::Params &parameters = TrackerContribFeatureHAAR::Params() );
  684. ~TrackerContribFeatureHAAR() CV_OVERRIDE;
  685. /** @brief Compute the features only for the selected indices in the images collection
  686. @param selFeatures indices of selected features
  687. @param images The images
  688. @param response Collection of response for the specific TrackerContribFeature
  689. */
  690. bool extractSelected( const std::vector<int> selFeatures, const std::vector<Mat>& images, Mat& response );
  691. /** @brief Identify most effective features
  692. @param response Collection of response for the specific TrackerContribFeature
  693. @param npoints Max number of features
  694. @note This method modifies the response parameter
  695. */
  696. void selection( Mat& response, int npoints ) CV_OVERRIDE;
  697. /** @brief Swap the feature in position source with the feature in position target
  698. @param source The source position
  699. @param target The target position
  700. */
  701. bool swapFeature( int source, int target );
  702. /** @brief Swap the feature in position id with the feature input
  703. @param id The position
  704. @param feature The feature
  705. */
  706. bool swapFeature( int id, CvHaarEvaluator::FeatureHaar& feature );
  707. /** @brief Get the feature in position id
  708. @param id The position
  709. */
  710. CvHaarEvaluator::FeatureHaar& getFeatureAt( int id );
  711. protected:
  712. bool computeImpl( const std::vector<Mat>& images, Mat& response ) CV_OVERRIDE;
  713. private:
  714. Params params;
  715. Ptr<CvHaarEvaluator> featureEvaluator;
  716. };
  717. /**
  718. * \brief TrackerContribFeature based on LBP
  719. */
  720. class CV_EXPORTS TrackerFeatureLBP : public TrackerContribFeature
  721. {
  722. public:
  723. TrackerFeatureLBP();
  724. ~TrackerFeatureLBP();
  725. void selection( Mat& response, int npoints ) CV_OVERRIDE;
  726. protected:
  727. bool computeImpl( const std::vector<Mat>& images, Mat& response ) CV_OVERRIDE;
  728. };
  729. //! @}
  730. }}} // namespace
  731. #endif // OPENCV_TRACKING_DETAIL_HPP