tracking.hpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #ifndef OPENCV_TRACKING_HPP
  44. #define OPENCV_TRACKING_HPP
  45. #include "opencv2/core.hpp"
  46. #include "opencv2/imgproc.hpp"
  47. namespace cv
  48. {
  49. //! @addtogroup video_track
  50. //! @{
  51. enum { OPTFLOW_USE_INITIAL_FLOW = 4,
  52. OPTFLOW_LK_GET_MIN_EIGENVALS = 8,
  53. OPTFLOW_FARNEBACK_GAUSSIAN = 256
  54. };
  55. /** @brief Finds an object center, size, and orientation.
  56. @param probImage Back projection of the object histogram. See calcBackProject.
  57. @param window Initial search window.
  58. @param criteria Stop criteria for the underlying meanShift.
  59. returns
  60. (in old interfaces) Number of iterations CAMSHIFT took to converge
  61. The function implements the CAMSHIFT object tracking algorithm @cite Bradski98 . First, it finds an
  62. object center using meanShift and then adjusts the window size and finds the optimal rotation. The
  63. function returns the rotated rectangle structure that includes the object position, size, and
  64. orientation. The next position of the search window can be obtained with RotatedRect::boundingRect()
  65. See the OpenCV sample camshiftdemo.c that tracks colored objects.
  66. @note
  67. - (Python) A sample explaining the camshift tracking algorithm can be found at
  68. opencv_source_code/samples/python/camshift.py
  69. */
  70. CV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_IN_OUT Rect& window,
  71. TermCriteria criteria );
  72. /** @example samples/cpp/camshiftdemo.cpp
  73. An example using the mean-shift tracking algorithm
  74. */
  75. /** @brief Finds an object on a back projection image.
  76. @param probImage Back projection of the object histogram. See calcBackProject for details.
  77. @param window Initial search window.
  78. @param criteria Stop criteria for the iterative search algorithm.
  79. returns
  80. : Number of iterations CAMSHIFT took to converge.
  81. The function implements the iterative object search algorithm. It takes the input back projection of
  82. an object and the initial position. The mass center in window of the back projection image is
  83. computed and the search window center shifts to the mass center. The procedure is repeated until the
  84. specified number of iterations criteria.maxCount is done or until the window center shifts by less
  85. than criteria.epsilon. The algorithm is used inside CamShift and, unlike CamShift , the search
  86. window size or orientation do not change during the search. You can simply pass the output of
  87. calcBackProject to this function. But better results can be obtained if you pre-filter the back
  88. projection and remove the noise. For example, you can do this by retrieving connected components
  89. with findContours , throwing away contours with small area ( contourArea ), and rendering the
  90. remaining contours with drawContours.
  91. */
  92. CV_EXPORTS_W int meanShift( InputArray probImage, CV_IN_OUT Rect& window, TermCriteria criteria );
  93. /** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK.
  94. @param img 8-bit input image.
  95. @param pyramid output pyramid.
  96. @param winSize window size of optical flow algorithm. Must be not less than winSize argument of
  97. calcOpticalFlowPyrLK. It is needed to calculate required padding for pyramid levels.
  98. @param maxLevel 0-based maximal pyramid level number.
  99. @param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is
  100. constructed without the gradients then calcOpticalFlowPyrLK will calculate them internally.
  101. @param pyrBorder the border mode for pyramid layers.
  102. @param derivBorder the border mode for gradients.
  103. @param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false
  104. to force data copying.
  105. @return number of levels in constructed pyramid. Can be less than maxLevel.
  106. */
  107. CV_EXPORTS_W int buildOpticalFlowPyramid( InputArray img, OutputArrayOfArrays pyramid,
  108. Size winSize, int maxLevel, bool withDerivatives = true,
  109. int pyrBorder = BORDER_REFLECT_101,
  110. int derivBorder = BORDER_CONSTANT,
  111. bool tryReuseInputImage = true );
  112. /** @example samples/cpp/lkdemo.cpp
  113. An example using the Lucas-Kanade optical flow algorithm
  114. */
  115. /** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with
  116. pyramids.
  117. @param prevImg first 8-bit input image or pyramid constructed by buildOpticalFlowPyramid.
  118. @param nextImg second input image or pyramid of the same size and the same type as prevImg.
  119. @param prevPts vector of 2D points for which the flow needs to be found; point coordinates must be
  120. single-precision floating-point numbers.
  121. @param nextPts output vector of 2D points (with single-precision floating-point coordinates)
  122. containing the calculated new positions of input features in the second image; when
  123. OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input.
  124. @param status output status vector (of unsigned chars); each element of the vector is set to 1 if
  125. the flow for the corresponding features has been found, otherwise, it is set to 0.
  126. @param err output vector of errors; each element of the vector is set to an error for the
  127. corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't
  128. found then the error is not defined (use the status parameter to find such cases).
  129. @param winSize size of the search window at each pyramid level.
  130. @param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single
  131. level), if set to 1, two levels are used, and so on; if pyramids are passed to input then
  132. algorithm will use as many levels as pyramids have but no more than maxLevel.
  133. @param criteria parameter, specifying the termination criteria of the iterative search algorithm
  134. (after the specified maximum number of iterations criteria.maxCount or when the search window
  135. moves by less than criteria.epsilon.
  136. @param flags operation flags:
  137. - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is
  138. not set, then prevPts is copied to nextPts and is considered the initial estimate.
  139. - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see
  140. minEigThreshold description); if the flag is not set, then L1 distance between patches
  141. around the original and a moved point, divided by number of pixels in a window, is used as a
  142. error measure.
  143. @param minEigThreshold the algorithm calculates the minimum eigen value of a 2x2 normal matrix of
  144. optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided
  145. by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding
  146. feature is filtered out and its flow is not processed, so it allows to remove bad points and get a
  147. performance boost.
  148. The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See
  149. @cite Bouguet00 . The function is parallelized with the TBB library.
  150. @note
  151. - An example using the Lucas-Kanade optical flow algorithm can be found at
  152. opencv_source_code/samples/cpp/lkdemo.cpp
  153. - (Python) An example using the Lucas-Kanade optical flow algorithm can be found at
  154. opencv_source_code/samples/python/lk_track.py
  155. - (Python) An example using the Lucas-Kanade tracker for homography matching can be found at
  156. opencv_source_code/samples/python/lk_homography.py
  157. */
  158. CV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg,
  159. InputArray prevPts, InputOutputArray nextPts,
  160. OutputArray status, OutputArray err,
  161. Size winSize = Size(21,21), int maxLevel = 3,
  162. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01),
  163. int flags = 0, double minEigThreshold = 1e-4 );
  164. /** @brief Computes a dense optical flow using the Gunnar Farneback's algorithm.
  165. @param prev first 8-bit single-channel input image.
  166. @param next second input image of the same size and the same type as prev.
  167. @param flow computed flow image that has the same size as prev and type CV_32FC2.
  168. @param pyr_scale parameter, specifying the image scale (\<1) to build pyramids for each image;
  169. pyr_scale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous
  170. one.
  171. @param levels number of pyramid layers including the initial image; levels=1 means that no extra
  172. layers are created and only the original images are used.
  173. @param winsize averaging window size; larger values increase the algorithm robustness to image
  174. noise and give more chances for fast motion detection, but yield more blurred motion field.
  175. @param iterations number of iterations the algorithm does at each pyramid level.
  176. @param poly_n size of the pixel neighborhood used to find polynomial expansion in each pixel;
  177. larger values mean that the image will be approximated with smoother surfaces, yielding more
  178. robust algorithm and more blurred motion field, typically poly_n =5 or 7.
  179. @param poly_sigma standard deviation of the Gaussian that is used to smooth derivatives used as a
  180. basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a
  181. good value would be poly_sigma=1.5.
  182. @param flags operation flags that can be a combination of the following:
  183. - **OPTFLOW_USE_INITIAL_FLOW** uses the input flow as an initial flow approximation.
  184. - **OPTFLOW_FARNEBACK_GAUSSIAN** uses the Gaussian \f$\texttt{winsize}\times\texttt{winsize}\f$
  185. filter instead of a box filter of the same size for optical flow estimation; usually, this
  186. option gives z more accurate flow than with a box filter, at the cost of lower speed;
  187. normally, winsize for a Gaussian window should be set to a larger value to achieve the same
  188. level of robustness.
  189. The function finds an optical flow for each prev pixel using the @cite Farneback2003 algorithm so that
  190. \f[\texttt{prev} (y,x) \sim \texttt{next} ( y + \texttt{flow} (y,x)[1], x + \texttt{flow} (y,x)[0])\f]
  191. @note
  192. - An example using the optical flow algorithm described by Gunnar Farneback can be found at
  193. opencv_source_code/samples/cpp/fback.cpp
  194. - (Python) An example using the optical flow algorithm described by Gunnar Farneback can be
  195. found at opencv_source_code/samples/python/opt_flow.py
  196. */
  197. CV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next, InputOutputArray flow,
  198. double pyr_scale, int levels, int winsize,
  199. int iterations, int poly_n, double poly_sigma,
  200. int flags );
  201. /** @brief Computes an optimal affine transformation between two 2D point sets.
  202. @param src First input 2D point set stored in std::vector or Mat, or an image stored in Mat.
  203. @param dst Second input 2D point set of the same size and the same type as A, or another image.
  204. @param fullAffine If true, the function finds an optimal affine transformation with no additional
  205. restrictions (6 degrees of freedom). Otherwise, the class of transformations to choose from is
  206. limited to combinations of translation, rotation, and uniform scaling (4 degrees of freedom).
  207. The function finds an optimal affine transform *[A|b]* (a 2 x 3 floating-point matrix) that
  208. approximates best the affine transformation between:
  209. * Two point sets
  210. * Two raster images. In this case, the function first finds some features in the src image and
  211. finds the corresponding features in dst image. After that, the problem is reduced to the first
  212. case.
  213. In case of point sets, the problem is formulated as follows: you need to find a 2x2 matrix *A* and
  214. 2x1 vector *b* so that:
  215. \f[[A^*|b^*] = arg \min _{[A|b]} \sum _i \| \texttt{dst}[i] - A { \texttt{src}[i]}^T - b \| ^2\f]
  216. where src[i] and dst[i] are the i-th points in src and dst, respectively
  217. \f$[A|b]\f$ can be either arbitrary (when fullAffine=true ) or have a form of
  218. \f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\f]
  219. when fullAffine=false.
  220. @deprecated Use cv::estimateAffine2D, cv::estimateAffinePartial2D instead. If you are using this function
  221. with images, extract points using cv::calcOpticalFlowPyrLK and then use the estimation functions.
  222. @sa
  223. estimateAffine2D, estimateAffinePartial2D, getAffineTransform, getPerspectiveTransform, findHomography
  224. */
  225. CV_DEPRECATED CV_EXPORTS Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine );
  226. enum
  227. {
  228. MOTION_TRANSLATION = 0,
  229. MOTION_EUCLIDEAN = 1,
  230. MOTION_AFFINE = 2,
  231. MOTION_HOMOGRAPHY = 3
  232. };
  233. /** @brief Computes the Enhanced Correlation Coefficient value between two images @cite EP08 .
  234. @param templateImage single-channel template image; CV_8U or CV_32F array.
  235. @param inputImage single-channel input image to be warped to provide an image similar to
  236. templateImage, same type as templateImage.
  237. @param inputMask An optional mask to indicate valid values of inputImage.
  238. @sa
  239. findTransformECC
  240. */
  241. CV_EXPORTS_W double computeECC(InputArray templateImage, InputArray inputImage, InputArray inputMask = noArray());
  242. /** @example samples/cpp/image_alignment.cpp
  243. An example using the image alignment ECC algorithm
  244. */
  245. /** @brief Finds the geometric transform (warp) between two images in terms of the ECC criterion @cite EP08 .
  246. @param templateImage single-channel template image; CV_8U or CV_32F array.
  247. @param inputImage single-channel input image which should be warped with the final warpMatrix in
  248. order to provide an image similar to templateImage, same type as templateImage.
  249. @param warpMatrix floating-point \f$2\times 3\f$ or \f$3\times 3\f$ mapping matrix (warp).
  250. @param motionType parameter, specifying the type of motion:
  251. - **MOTION_TRANSLATION** sets a translational motion model; warpMatrix is \f$2\times 3\f$ with
  252. the first \f$2\times 2\f$ part being the unity matrix and the rest two parameters being
  253. estimated.
  254. - **MOTION_EUCLIDEAN** sets a Euclidean (rigid) transformation as motion model; three
  255. parameters are estimated; warpMatrix is \f$2\times 3\f$.
  256. - **MOTION_AFFINE** sets an affine motion model (DEFAULT); six parameters are estimated;
  257. warpMatrix is \f$2\times 3\f$.
  258. - **MOTION_HOMOGRAPHY** sets a homography as a motion model; eight parameters are
  259. estimated;\`warpMatrix\` is \f$3\times 3\f$.
  260. @param criteria parameter, specifying the termination criteria of the ECC algorithm;
  261. criteria.epsilon defines the threshold of the increment in the correlation coefficient between two
  262. iterations (a negative criteria.epsilon makes criteria.maxcount the only termination criterion).
  263. Default values are shown in the declaration above.
  264. @param inputMask An optional mask to indicate valid values of inputImage.
  265. @param gaussFiltSize An optional value indicating size of gaussian blur filter; (DEFAULT: 5)
  266. The function estimates the optimum transformation (warpMatrix) with respect to ECC criterion
  267. (@cite EP08), that is
  268. \f[\texttt{warpMatrix} = \texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f]
  269. where
  270. \f[\begin{bmatrix} x' \\ y' \end{bmatrix} = W \cdot \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}\f]
  271. (the equation holds with homogeneous coordinates for homography). It returns the final enhanced
  272. correlation coefficient, that is the correlation coefficient between the template image and the
  273. final warped input image. When a \f$3\times 3\f$ matrix is given with motionType =0, 1 or 2, the third
  274. row is ignored.
  275. Unlike findHomography and estimateRigidTransform, the function findTransformECC implements an
  276. area-based alignment that builds on intensity similarities. In essence, the function updates the
  277. initial transformation that roughly aligns the images. If this information is missing, the identity
  278. warp (unity matrix) is used as an initialization. Note that if images undergo strong
  279. displacements/rotations, an initial transformation that roughly aligns the images is necessary
  280. (e.g., a simple euclidean/similarity transform that allows for the images showing the same image
  281. content approximately). Use inverse warping in the second image to take an image close to the first
  282. one, i.e. use the flag WARP_INVERSE_MAP with warpAffine or warpPerspective. See also the OpenCV
  283. sample image_alignment.cpp that demonstrates the use of the function. Note that the function throws
  284. an exception if algorithm does not converges.
  285. @sa
  286. computeECC, estimateAffine2D, estimateAffinePartial2D, findHomography
  287. */
  288. CV_EXPORTS_W double findTransformECC( InputArray templateImage, InputArray inputImage,
  289. InputOutputArray warpMatrix, int motionType,
  290. TermCriteria criteria,
  291. InputArray inputMask, int gaussFiltSize);
  292. /** @overload */
  293. CV_EXPORTS
  294. double findTransformECC(InputArray templateImage, InputArray inputImage,
  295. InputOutputArray warpMatrix, int motionType = MOTION_AFFINE,
  296. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001),
  297. InputArray inputMask = noArray());
  298. /** @example samples/cpp/kalman.cpp
  299. An example using the standard Kalman filter
  300. */
  301. /** @brief Kalman filter class.
  302. The class implements a standard Kalman filter <http://en.wikipedia.org/wiki/Kalman_filter>,
  303. @cite Welch95 . However, you can modify transitionMatrix, controlMatrix, and measurementMatrix to get
  304. an extended Kalman filter functionality.
  305. @note In C API when CvKalman\* kalmanFilter structure is not needed anymore, it should be released
  306. with cvReleaseKalman(&kalmanFilter)
  307. */
  308. class CV_EXPORTS_W KalmanFilter
  309. {
  310. public:
  311. CV_WRAP KalmanFilter();
  312. /** @overload
  313. @param dynamParams Dimensionality of the state.
  314. @param measureParams Dimensionality of the measurement.
  315. @param controlParams Dimensionality of the control vector.
  316. @param type Type of the created matrices that should be CV_32F or CV_64F.
  317. */
  318. CV_WRAP KalmanFilter( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F );
  319. /** @brief Re-initializes Kalman filter. The previous content is destroyed.
  320. @param dynamParams Dimensionality of the state.
  321. @param measureParams Dimensionality of the measurement.
  322. @param controlParams Dimensionality of the control vector.
  323. @param type Type of the created matrices that should be CV_32F or CV_64F.
  324. */
  325. void init( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F );
  326. /** @brief Computes a predicted state.
  327. @param control The optional input control
  328. */
  329. CV_WRAP const Mat& predict( const Mat& control = Mat() );
  330. /** @brief Updates the predicted state from the measurement.
  331. @param measurement The measured system parameters
  332. */
  333. CV_WRAP const Mat& correct( const Mat& measurement );
  334. CV_PROP_RW Mat statePre; //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)
  335. CV_PROP_RW Mat statePost; //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
  336. CV_PROP_RW Mat transitionMatrix; //!< state transition matrix (A)
  337. CV_PROP_RW Mat controlMatrix; //!< control matrix (B) (not used if there is no control)
  338. CV_PROP_RW Mat measurementMatrix; //!< measurement matrix (H)
  339. CV_PROP_RW Mat processNoiseCov; //!< process noise covariance matrix (Q)
  340. CV_PROP_RW Mat measurementNoiseCov;//!< measurement noise covariance matrix (R)
  341. CV_PROP_RW Mat errorCovPre; //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/
  342. CV_PROP_RW Mat gain; //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
  343. CV_PROP_RW Mat errorCovPost; //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)
  344. // temporary matrices
  345. Mat temp1;
  346. Mat temp2;
  347. Mat temp3;
  348. Mat temp4;
  349. Mat temp5;
  350. };
  351. /** @brief Read a .flo file
  352. @param path Path to the file to be loaded
  353. The function readOpticalFlow loads a flow field from a file and returns it as a single matrix.
  354. Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the
  355. flow in the horizontal direction (u), second - vertical (v).
  356. */
  357. CV_EXPORTS_W Mat readOpticalFlow( const String& path );
  358. /** @brief Write a .flo to disk
  359. @param path Path to the file to be written
  360. @param flow Flow field to be stored
  361. The function stores a flow field in a file, returns true on success, false otherwise.
  362. The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds
  363. to the flow in the horizontal direction (u), second - vertical (v).
  364. */
  365. CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow );
  366. /**
  367. Base class for dense optical flow algorithms
  368. */
  369. class CV_EXPORTS_W DenseOpticalFlow : public Algorithm
  370. {
  371. public:
  372. /** @brief Calculates an optical flow.
  373. @param I0 first 8-bit single-channel input image.
  374. @param I1 second input image of the same size and the same type as prev.
  375. @param flow computed flow image that has the same size as prev and type CV_32FC2.
  376. */
  377. CV_WRAP virtual void calc( InputArray I0, InputArray I1, InputOutputArray flow ) = 0;
  378. /** @brief Releases all inner buffers.
  379. */
  380. CV_WRAP virtual void collectGarbage() = 0;
  381. };
  382. /** @brief Base interface for sparse optical flow algorithms.
  383. */
  384. class CV_EXPORTS_W SparseOpticalFlow : public Algorithm
  385. {
  386. public:
  387. /** @brief Calculates a sparse optical flow.
  388. @param prevImg First input image.
  389. @param nextImg Second input image of the same size and the same type as prevImg.
  390. @param prevPts Vector of 2D points for which the flow needs to be found.
  391. @param nextPts Output vector of 2D points containing the calculated new positions of input features in the second image.
  392. @param status Output status vector. Each element of the vector is set to 1 if the
  393. flow for the corresponding features has been found. Otherwise, it is set to 0.
  394. @param err Optional output vector that contains error response for each point (inverse confidence).
  395. */
  396. CV_WRAP virtual void calc(InputArray prevImg, InputArray nextImg,
  397. InputArray prevPts, InputOutputArray nextPts,
  398. OutputArray status,
  399. OutputArray err = cv::noArray()) = 0;
  400. };
  401. /** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm.
  402. */
  403. class CV_EXPORTS_W FarnebackOpticalFlow : public DenseOpticalFlow
  404. {
  405. public:
  406. CV_WRAP virtual int getNumLevels() const = 0;
  407. CV_WRAP virtual void setNumLevels(int numLevels) = 0;
  408. CV_WRAP virtual double getPyrScale() const = 0;
  409. CV_WRAP virtual void setPyrScale(double pyrScale) = 0;
  410. CV_WRAP virtual bool getFastPyramids() const = 0;
  411. CV_WRAP virtual void setFastPyramids(bool fastPyramids) = 0;
  412. CV_WRAP virtual int getWinSize() const = 0;
  413. CV_WRAP virtual void setWinSize(int winSize) = 0;
  414. CV_WRAP virtual int getNumIters() const = 0;
  415. CV_WRAP virtual void setNumIters(int numIters) = 0;
  416. CV_WRAP virtual int getPolyN() const = 0;
  417. CV_WRAP virtual void setPolyN(int polyN) = 0;
  418. CV_WRAP virtual double getPolySigma() const = 0;
  419. CV_WRAP virtual void setPolySigma(double polySigma) = 0;
  420. CV_WRAP virtual int getFlags() const = 0;
  421. CV_WRAP virtual void setFlags(int flags) = 0;
  422. CV_WRAP static Ptr<FarnebackOpticalFlow> create(
  423. int numLevels = 5,
  424. double pyrScale = 0.5,
  425. bool fastPyramids = false,
  426. int winSize = 13,
  427. int numIters = 10,
  428. int polyN = 5,
  429. double polySigma = 1.1,
  430. int flags = 0);
  431. };
  432. /** @brief Variational optical flow refinement
  433. This class implements variational refinement of the input flow field, i.e.
  434. it uses input flow to initialize the minimization of the following functional:
  435. \f$E(U) = \int_{\Omega} \delta \Psi(E_I) + \gamma \Psi(E_G) + \alpha \Psi(E_S) \f$,
  436. where \f$E_I,E_G,E_S\f$ are color constancy, gradient constancy and smoothness terms
  437. respectively. \f$\Psi(s^2)=\sqrt{s^2+\epsilon^2}\f$ is a robust penalizer to limit the
  438. influence of outliers. A complete formulation and a description of the minimization
  439. procedure can be found in @cite Brox2004
  440. */
  441. class CV_EXPORTS_W VariationalRefinement : public DenseOpticalFlow
  442. {
  443. public:
  444. /** @brief @ref calc function overload to handle separate horizontal (u) and vertical (v) flow components
  445. (to avoid extra splits/merges) */
  446. CV_WRAP virtual void calcUV(InputArray I0, InputArray I1, InputOutputArray flow_u, InputOutputArray flow_v) = 0;
  447. /** @brief Number of outer (fixed-point) iterations in the minimization procedure.
  448. @see setFixedPointIterations */
  449. CV_WRAP virtual int getFixedPointIterations() const = 0;
  450. /** @copybrief getFixedPointIterations @see getFixedPointIterations */
  451. CV_WRAP virtual void setFixedPointIterations(int val) = 0;
  452. /** @brief Number of inner successive over-relaxation (SOR) iterations
  453. in the minimization procedure to solve the respective linear system.
  454. @see setSorIterations */
  455. CV_WRAP virtual int getSorIterations() const = 0;
  456. /** @copybrief getSorIterations @see getSorIterations */
  457. CV_WRAP virtual void setSorIterations(int val) = 0;
  458. /** @brief Relaxation factor in SOR
  459. @see setOmega */
  460. CV_WRAP virtual float getOmega() const = 0;
  461. /** @copybrief getOmega @see getOmega */
  462. CV_WRAP virtual void setOmega(float val) = 0;
  463. /** @brief Weight of the smoothness term
  464. @see setAlpha */
  465. CV_WRAP virtual float getAlpha() const = 0;
  466. /** @copybrief getAlpha @see getAlpha */
  467. CV_WRAP virtual void setAlpha(float val) = 0;
  468. /** @brief Weight of the color constancy term
  469. @see setDelta */
  470. CV_WRAP virtual float getDelta() const = 0;
  471. /** @copybrief getDelta @see getDelta */
  472. CV_WRAP virtual void setDelta(float val) = 0;
  473. /** @brief Weight of the gradient constancy term
  474. @see setGamma */
  475. CV_WRAP virtual float getGamma() const = 0;
  476. /** @copybrief getGamma @see getGamma */
  477. CV_WRAP virtual void setGamma(float val) = 0;
  478. /** @brief Creates an instance of VariationalRefinement
  479. */
  480. CV_WRAP static Ptr<VariationalRefinement> create();
  481. };
  482. /** @brief DIS optical flow algorithm.
  483. This class implements the Dense Inverse Search (DIS) optical flow algorithm. More
  484. details about the algorithm can be found at @cite Kroeger2016 . Includes three presets with preselected
  485. parameters to provide reasonable trade-off between speed and quality. However, even the slowest preset is
  486. still relatively fast, use DeepFlow if you need better quality and don't care about speed.
  487. This implementation includes several additional features compared to the algorithm described in the paper,
  488. including spatial propagation of flow vectors (@ref getUseSpatialPropagation), as well as an option to
  489. utilize an initial flow approximation passed to @ref calc (which is, essentially, temporal propagation,
  490. if the previous frame's flow field is passed).
  491. */
  492. class CV_EXPORTS_W DISOpticalFlow : public DenseOpticalFlow
  493. {
  494. public:
  495. enum
  496. {
  497. PRESET_ULTRAFAST = 0,
  498. PRESET_FAST = 1,
  499. PRESET_MEDIUM = 2
  500. };
  501. /** @brief Finest level of the Gaussian pyramid on which the flow is computed (zero level
  502. corresponds to the original image resolution). The final flow is obtained by bilinear upscaling.
  503. @see setFinestScale */
  504. CV_WRAP virtual int getFinestScale() const = 0;
  505. /** @copybrief getFinestScale @see getFinestScale */
  506. CV_WRAP virtual void setFinestScale(int val) = 0;
  507. /** @brief Size of an image patch for matching (in pixels). Normally, default 8x8 patches work well
  508. enough in most cases.
  509. @see setPatchSize */
  510. CV_WRAP virtual int getPatchSize() const = 0;
  511. /** @copybrief getPatchSize @see getPatchSize */
  512. CV_WRAP virtual void setPatchSize(int val) = 0;
  513. /** @brief Stride between neighbor patches. Must be less than patch size. Lower values correspond
  514. to higher flow quality.
  515. @see setPatchStride */
  516. CV_WRAP virtual int getPatchStride() const = 0;
  517. /** @copybrief getPatchStride @see getPatchStride */
  518. CV_WRAP virtual void setPatchStride(int val) = 0;
  519. /** @brief Maximum number of gradient descent iterations in the patch inverse search stage. Higher values
  520. may improve quality in some cases.
  521. @see setGradientDescentIterations */
  522. CV_WRAP virtual int getGradientDescentIterations() const = 0;
  523. /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */
  524. CV_WRAP virtual void setGradientDescentIterations(int val) = 0;
  525. /** @brief Number of fixed point iterations of variational refinement per scale. Set to zero to
  526. disable variational refinement completely. Higher values will typically result in more smooth and
  527. high-quality flow.
  528. @see setGradientDescentIterations */
  529. CV_WRAP virtual int getVariationalRefinementIterations() const = 0;
  530. /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */
  531. CV_WRAP virtual void setVariationalRefinementIterations(int val) = 0;
  532. /** @brief Weight of the smoothness term
  533. @see setVariationalRefinementAlpha */
  534. CV_WRAP virtual float getVariationalRefinementAlpha() const = 0;
  535. /** @copybrief getVariationalRefinementAlpha @see getVariationalRefinementAlpha */
  536. CV_WRAP virtual void setVariationalRefinementAlpha(float val) = 0;
  537. /** @brief Weight of the color constancy term
  538. @see setVariationalRefinementDelta */
  539. CV_WRAP virtual float getVariationalRefinementDelta() const = 0;
  540. /** @copybrief getVariationalRefinementDelta @see getVariationalRefinementDelta */
  541. CV_WRAP virtual void setVariationalRefinementDelta(float val) = 0;
  542. /** @brief Weight of the gradient constancy term
  543. @see setVariationalRefinementGamma */
  544. CV_WRAP virtual float getVariationalRefinementGamma() const = 0;
  545. /** @copybrief getVariationalRefinementGamma @see getVariationalRefinementGamma */
  546. CV_WRAP virtual void setVariationalRefinementGamma(float val) = 0;
  547. /** @brief Whether to use mean-normalization of patches when computing patch distance. It is turned on
  548. by default as it typically provides a noticeable quality boost because of increased robustness to
  549. illumination variations. Turn it off if you are certain that your sequence doesn't contain any changes
  550. in illumination.
  551. @see setUseMeanNormalization */
  552. CV_WRAP virtual bool getUseMeanNormalization() const = 0;
  553. /** @copybrief getUseMeanNormalization @see getUseMeanNormalization */
  554. CV_WRAP virtual void setUseMeanNormalization(bool val) = 0;
  555. /** @brief Whether to use spatial propagation of good optical flow vectors. This option is turned on by
  556. default, as it tends to work better on average and can sometimes help recover from major errors
  557. introduced by the coarse-to-fine scheme employed by the DIS optical flow algorithm. Turning this
  558. option off can make the output flow field a bit smoother, however.
  559. @see setUseSpatialPropagation */
  560. CV_WRAP virtual bool getUseSpatialPropagation() const = 0;
  561. /** @copybrief getUseSpatialPropagation @see getUseSpatialPropagation */
  562. CV_WRAP virtual void setUseSpatialPropagation(bool val) = 0;
  563. /** @brief Creates an instance of DISOpticalFlow
  564. @param preset one of PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM
  565. */
  566. CV_WRAP static Ptr<DISOpticalFlow> create(int preset = DISOpticalFlow::PRESET_FAST);
  567. };
  568. /** @brief Class used for calculating a sparse optical flow.
  569. The class can calculate an optical flow for a sparse feature set using the
  570. iterative Lucas-Kanade method with pyramids.
  571. @sa calcOpticalFlowPyrLK
  572. */
  573. class CV_EXPORTS_W SparsePyrLKOpticalFlow : public SparseOpticalFlow
  574. {
  575. public:
  576. CV_WRAP virtual Size getWinSize() const = 0;
  577. CV_WRAP virtual void setWinSize(Size winSize) = 0;
  578. CV_WRAP virtual int getMaxLevel() const = 0;
  579. CV_WRAP virtual void setMaxLevel(int maxLevel) = 0;
  580. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  581. CV_WRAP virtual void setTermCriteria(TermCriteria& crit) = 0;
  582. CV_WRAP virtual int getFlags() const = 0;
  583. CV_WRAP virtual void setFlags(int flags) = 0;
  584. CV_WRAP virtual double getMinEigThreshold() const = 0;
  585. CV_WRAP virtual void setMinEigThreshold(double minEigThreshold) = 0;
  586. CV_WRAP static Ptr<SparsePyrLKOpticalFlow> create(
  587. Size winSize = Size(21, 21),
  588. int maxLevel = 3, TermCriteria crit =
  589. TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01),
  590. int flags = 0,
  591. double minEigThreshold = 1e-4);
  592. };
  593. //! @} video_track
  594. } // cv
  595. #endif