ba758c235f2ecba6b8661a2584a5a5d763dc4eca
[platform/upstream/opencv.git] / modules / contrib / include / opencv2 / contrib / compat.hpp
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-2011, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42
43 #ifndef __OPENCV_CONTRIB_COMPAT_HPP__
44 #define __OPENCV_CONTRIB_COMPAT_HPP__
45
46 #include "opencv2/core/core_c.h"
47
48 #ifdef __cplusplus
49
50 /****************************************************************************************\
51 *                                   Adaptive Skin Detector                               *
52 \****************************************************************************************/
53
54 class CV_EXPORTS CvAdaptiveSkinDetector
55 {
56 private:
57     enum {
58         GSD_HUE_LT = 3,
59         GSD_HUE_UT = 33,
60         GSD_INTENSITY_LT = 15,
61         GSD_INTENSITY_UT = 250
62     };
63
64     class CV_EXPORTS Histogram
65     {
66     private:
67         enum {
68             HistogramSize = (GSD_HUE_UT - GSD_HUE_LT + 1)
69         };
70
71     protected:
72         int findCoverageIndex(double surfaceToCover, int defaultValue = 0);
73
74     public:
75         CvHistogram *fHistogram;
76         Histogram();
77         virtual ~Histogram();
78
79         void findCurveThresholds(int &x1, int &x2, double percent = 0.05);
80         void mergeWith(Histogram *source, double weight);
81     };
82
83     int nStartCounter, nFrameCount, nSkinHueLowerBound, nSkinHueUpperBound, nMorphingMethod, nSamplingDivider;
84     double fHistogramMergeFactor, fHuePercentCovered;
85     Histogram histogramHueMotion, skinHueHistogram;
86     IplImage *imgHueFrame, *imgSaturationFrame, *imgLastGrayFrame, *imgMotionFrame, *imgFilteredFrame;
87     IplImage *imgShrinked, *imgTemp, *imgGrayFrame, *imgHSVFrame;
88
89 protected:
90     void initData(IplImage *src, int widthDivider, int heightDivider);
91     void adaptiveFilter();
92
93 public:
94
95     enum {
96         MORPHING_METHOD_NONE = 0,
97         MORPHING_METHOD_ERODE = 1,
98         MORPHING_METHOD_ERODE_ERODE = 2,
99         MORPHING_METHOD_ERODE_DILATE = 3
100     };
101
102     CvAdaptiveSkinDetector(int samplingDivider = 1, int morphingMethod = MORPHING_METHOD_NONE);
103     virtual ~CvAdaptiveSkinDetector();
104
105     virtual void process(IplImage *inputBGRImage, IplImage *outputHueMask);
106 };
107
108
109 /****************************************************************************************\
110  *                                  Fuzzy MeanShift Tracker                               *
111  \****************************************************************************************/
112
113 class CV_EXPORTS CvFuzzyPoint {
114 public:
115     double x, y, value;
116
117     CvFuzzyPoint(double _x, double _y);
118 };
119
120 class CV_EXPORTS CvFuzzyCurve {
121 private:
122     std::vector<CvFuzzyPoint> points;
123     double value, centre;
124
125     bool between(double x, double x1, double x2);
126
127 public:
128     CvFuzzyCurve();
129     ~CvFuzzyCurve();
130
131     void setCentre(double _centre);
132     double getCentre();
133     void clear();
134     void addPoint(double x, double y);
135     double calcValue(double param);
136     double getValue();
137     void setValue(double _value);
138 };
139
140 class CV_EXPORTS CvFuzzyFunction {
141 public:
142     std::vector<CvFuzzyCurve> curves;
143
144     CvFuzzyFunction();
145     ~CvFuzzyFunction();
146     void addCurve(CvFuzzyCurve *curve, double value = 0);
147     void resetValues();
148     double calcValue();
149     CvFuzzyCurve *newCurve();
150 };
151
152 class CV_EXPORTS CvFuzzyRule {
153 private:
154     CvFuzzyCurve *fuzzyInput1, *fuzzyInput2;
155     CvFuzzyCurve *fuzzyOutput;
156 public:
157     CvFuzzyRule();
158     ~CvFuzzyRule();
159     void setRule(CvFuzzyCurve *c1, CvFuzzyCurve *c2, CvFuzzyCurve *o1);
160     double calcValue(double param1, double param2);
161     CvFuzzyCurve *getOutputCurve();
162 };
163
164 class CV_EXPORTS CvFuzzyController {
165 private:
166     std::vector<CvFuzzyRule*> rules;
167 public:
168     CvFuzzyController();
169     ~CvFuzzyController();
170     void addRule(CvFuzzyCurve *c1, CvFuzzyCurve *c2, CvFuzzyCurve *o1);
171     double calcOutput(double param1, double param2);
172 };
173
174 class CV_EXPORTS CvFuzzyMeanShiftTracker
175 {
176 private:
177     class FuzzyResizer
178     {
179     private:
180         CvFuzzyFunction iInput, iOutput;
181         CvFuzzyController fuzzyController;
182     public:
183         FuzzyResizer();
184         int calcOutput(double edgeDensity, double density);
185     };
186
187     class SearchWindow
188     {
189     public:
190         FuzzyResizer *fuzzyResizer;
191         int x, y;
192         int width, height, maxWidth, maxHeight, ellipseHeight, ellipseWidth;
193         int ldx, ldy, ldw, ldh, numShifts, numIters;
194         int xGc, yGc;
195         long m00, m01, m10, m11, m02, m20;
196         double ellipseAngle;
197         double density;
198         unsigned int depthLow, depthHigh;
199         int verticalEdgeLeft, verticalEdgeRight, horizontalEdgeTop, horizontalEdgeBottom;
200
201         SearchWindow();
202         ~SearchWindow();
203         void setSize(int _x, int _y, int _width, int _height);
204         void initDepthValues(IplImage *maskImage, IplImage *depthMap);
205         bool shift();
206         void extractInfo(IplImage *maskImage, IplImage *depthMap, bool initDepth);
207         void getResizeAttribsEdgeDensityLinear(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh);
208         void getResizeAttribsInnerDensity(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh);
209         void getResizeAttribsEdgeDensityFuzzy(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh);
210         bool meanShift(IplImage *maskImage, IplImage *depthMap, int maxIteration, bool initDepth);
211     };
212
213 public:
214     enum TrackingState
215     {
216         tsNone          = 0,
217         tsSearching     = 1,
218         tsTracking      = 2,
219         tsSetWindow     = 3,
220         tsDisabled      = 10
221     };
222
223     enum ResizeMethod {
224         rmEdgeDensityLinear     = 0,
225         rmEdgeDensityFuzzy      = 1,
226         rmInnerDensity          = 2
227     };
228
229     enum {
230         MinKernelMass           = 1000
231     };
232
233     SearchWindow kernel;
234     int searchMode;
235
236 private:
237     enum
238     {
239         MaxMeanShiftIteration   = 5,
240         MaxSetSizeIteration     = 5
241     };
242
243     void findOptimumSearchWindow(SearchWindow &searchWindow, IplImage *maskImage, IplImage *depthMap, int maxIteration, int resizeMethod, bool initDepth);
244
245 public:
246     CvFuzzyMeanShiftTracker();
247     ~CvFuzzyMeanShiftTracker();
248
249     void track(IplImage *maskImage, IplImage *depthMap, int resizeMethod, bool resetSearch, int minKernelMass = MinKernelMass);
250 };
251
252
253 namespace cv
254 {
255
256 typedef bool (*BundleAdjustCallback)(int iteration, double norm_error, void* user_data);
257
258 class CV_EXPORTS LevMarqSparse {
259 public:
260     LevMarqSparse();
261     LevMarqSparse(int npoints, // number of points
262                   int ncameras, // number of cameras
263                   int nPointParams, // number of params per one point  (3 in case of 3D points)
264                   int nCameraParams, // number of parameters per one camera
265                   int nErrParams, // number of parameters in measurement vector
266                   // for 1 point at one camera (2 in case of 2D projections)
267                   Mat& visibility, // visibility matrix. rows correspond to points, columns correspond to cameras
268                   // 1 - point is visible for the camera, 0 - invisible
269                   Mat& P0, // starting vector of parameters, first cameras then points
270                   Mat& X, // measurements, in order of visibility. non visible cases are skipped
271                   TermCriteria criteria, // termination criteria
272
273                   // callback for estimation of Jacobian matrices
274                   void (*fjac)(int i, int j, Mat& point_params,
275                                          Mat& cam_params, Mat& A, Mat& B, void* data),
276                   // callback for estimation of backprojection errors
277                   void (*func)(int i, int j, Mat& point_params,
278                                          Mat& cam_params, Mat& estim, void* data),
279                   void* data, // user-specific data passed to the callbacks
280                   BundleAdjustCallback cb, void* user_data
281                   );
282
283     virtual ~LevMarqSparse();
284
285     virtual void run( int npoints, // number of points
286                      int ncameras, // number of cameras
287                      int nPointParams, // number of params per one point  (3 in case of 3D points)
288                      int nCameraParams, // number of parameters per one camera
289                      int nErrParams, // number of parameters in measurement vector
290                      // for 1 point at one camera (2 in case of 2D projections)
291                      Mat& visibility, // visibility matrix. rows correspond to points, columns correspond to cameras
292                      // 1 - point is visible for the camera, 0 - invisible
293                      Mat& P0, // starting vector of parameters, first cameras then points
294                      Mat& X, // measurements, in order of visibility. non visible cases are skipped
295                      TermCriteria criteria, // termination criteria
296
297                      // callback for estimation of Jacobian matrices
298                      void (CV_CDECL * fjac)(int i, int j, Mat& point_params,
299                                             Mat& cam_params, Mat& A, Mat& B, void* data),
300                      // callback for estimation of backprojection errors
301                      void (CV_CDECL * func)(int i, int j, Mat& point_params,
302                                             Mat& cam_params, Mat& estim, void* data),
303                      void* data // user-specific data passed to the callbacks
304                      );
305
306     virtual void clear();
307
308     // useful function to do simple bundle adjustment tasks
309     static void bundleAdjust(std::vector<Point3d>& points, // positions of points in global coordinate system (input and output)
310                              const std::vector<std::vector<Point2d> >& imagePoints, // projections of 3d points for every camera
311                              const std::vector<std::vector<int> >& visibility, // visibility of 3d points for every camera
312                              std::vector<Mat>& cameraMatrix, // intrinsic matrices of all cameras (input and output)
313                              std::vector<Mat>& R, // rotation matrices of all cameras (input and output)
314                              std::vector<Mat>& T, // translation vector of all cameras (input and output)
315                              std::vector<Mat>& distCoeffs, // distortion coefficients of all cameras (input and output)
316                              const TermCriteria& criteria=
317                              TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON),
318                              BundleAdjustCallback cb = 0, void* user_data = 0);
319
320 public:
321     virtual void optimize(CvMat &_vis); //main function that runs minimization
322
323     //iteratively asks for measurement for visible camera-point pairs
324     void ask_for_proj(CvMat &_vis,bool once=false);
325     //iteratively asks for Jacobians for every camera_point pair
326     void ask_for_projac(CvMat &_vis);
327
328     CvMat* err; //error X-hX
329     double prevErrNorm, errNorm;
330     double lambda;
331     CvTermCriteria criteria;
332     int iters;
333
334     CvMat** U; //size of array is equal to number of cameras
335     CvMat** V; //size of array is equal to number of points
336     CvMat** inv_V_star; //inverse of V*
337
338     CvMat** A;
339     CvMat** B;
340     CvMat** W;
341
342     CvMat* X; //measurement
343     CvMat* hX; //current measurement extimation given new parameter vector
344
345     CvMat* prevP; //current already accepted parameter.
346     CvMat* P; // parameters used to evaluate function with new params
347     // this parameters may be rejected
348
349     CvMat* deltaP; //computed increase of parameters (result of normal system solution )
350
351     CvMat** ea; // sum_i  AijT * e_ij , used as right part of normal equation
352     // length of array is j = number of cameras
353     CvMat** eb; // sum_j  BijT * e_ij , used as right part of normal equation
354     // length of array is i = number of points
355
356     CvMat** Yj; //length of array is i = num_points
357
358     CvMat* S; //big matrix of block Sjk  , each block has size num_cam_params x num_cam_params
359
360     CvMat* JtJ_diag; //diagonal of JtJ,  used to backup diagonal elements before augmentation
361
362     CvMat* Vis_index; // matrix which element is index of measurement for point i and camera j
363
364     int num_cams;
365     int num_points;
366     int num_err_param;
367     int num_cam_param;
368     int num_point_param;
369
370     //target function and jacobian pointers, which needs to be initialized
371     void (*fjac)(int i, int j, Mat& point_params, Mat& cam_params, Mat& A, Mat& B, void* data);
372     void (*func)(int i, int j, Mat& point_params, Mat& cam_params, Mat& estim, void* data);
373
374     void* data;
375
376     BundleAdjustCallback cb;
377     void* user_data;
378 };
379
380 } // cv
381
382 #endif /* __cplusplus */
383
384 #endif /* __OPENCV_CONTRIB_COMPAT_HPP__ */