Merge pull request #1804 from alekcac:youtube_link_fix
[profile/ivi/opencv.git] / modules / ocl / src / haar.cpp
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) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
14 // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // @Authors
18 //    Niko Li, newlife20080214@gmail.com
19 //    Wang Weiyan, wangweiyanster@gmail.com
20 //    Jia Haipeng, jiahaipeng95@gmail.com
21 //    Wu Xinglong, wxl370@126.com
22 //    Wang Yao, bitwangyaoyao@gmail.com
23 //
24 // Redistribution and use in source and binary forms, with or without modification,
25 // are permitted provided that the following conditions are met:
26 //
27 //   * Redistribution's of source code must retain the above copyright notice,
28 //     this list of conditions and the following disclaimer.
29 //
30 //   * Redistribution's in binary form must reproduce the above copyright notice,
31 //     this list of conditions and the following disclaimer in the documentation
32 //     and/or other materials provided with the distribution.
33 //
34 //   * The name of the copyright holders may not be used to endorse or promote products
35 //     derived from this software without specific prior written permission.
36 //
37 // This software is provided by the copyright holders and contributors "as is" and
38 // any express or implied warranties, including, but not limited to, the implied
39 // warranties of merchantability and fitness for a particular purpose are disclaimed.
40 // In no event shall the Intel Corporation or contributors be liable for any direct,
41 // indirect, incidental, special, exemplary, or consequential damages
42 // (including, but not limited to, procurement of substitute goods or services;
43 // loss of use, data, or profits; or business interruption) however caused
44 // and on any theory of liability, whether in contract, strict liability,
45 // or tort (including negligence or otherwise) arising in any way out of
46 // the use of this software, even if advised of the possibility of such damage.
47 //
48 //M*/
49
50 #include "precomp.hpp"
51 #include "opencl_kernels.hpp"
52
53 using namespace cv;
54 using namespace cv::ocl;
55
56 /* these settings affect the quality of detection: change with care */
57 #define CV_ADJUST_FEATURES  1
58 #define CV_ADJUST_WEIGHTS   0
59 #define CV_HAAR_FEATURE_MAX 3
60 typedef int sumtype;
61 typedef double sqsumtype;
62
63 typedef struct CvHidHaarFeature
64 {
65     struct
66     {
67         sumtype *p0, *p1, *p2, *p3;
68         float weight;
69     }
70     rect[CV_HAAR_FEATURE_MAX];
71 }
72 CvHidHaarFeature;
73
74
75 typedef struct CvHidHaarTreeNode
76 {
77     CvHidHaarFeature feature;
78     float threshold;
79     int left;
80     int right;
81 }
82 CvHidHaarTreeNode;
83
84
85 typedef struct CvHidHaarClassifier
86 {
87     int count;
88     //CvHaarFeature* orig_feature;
89     CvHidHaarTreeNode *node;
90     float *alpha;
91 }
92 CvHidHaarClassifier;
93
94
95 typedef struct CvHidHaarStageClassifier
96 {
97     int  count;
98     float threshold;
99     CvHidHaarClassifier *classifier;
100     int two_rects;
101
102     struct CvHidHaarStageClassifier *next;
103     struct CvHidHaarStageClassifier *child;
104     struct CvHidHaarStageClassifier *parent;
105 }
106 CvHidHaarStageClassifier;
107
108
109 struct CvHidHaarClassifierCascade
110 {
111     int  count;
112     int  is_stump_based;
113     int  has_tilted_features;
114     int  is_tree;
115     double inv_window_area;
116     CvMat sum, sqsum, tilted;
117     CvHidHaarStageClassifier *stage_classifier;
118     sqsumtype *pq0, *pq1, *pq2, *pq3;
119     sumtype *p0, *p1, *p2, *p3;
120
121     void **ipp_stages;
122 };
123 typedef struct
124 {
125     int width_height;
126     int grpnumperline_totalgrp;
127     int imgoff;
128     float factor;
129 } detect_piramid_info;
130 #ifdef _MSC_VER
131 #define _ALIGNED_ON(_ALIGNMENT) __declspec(align(_ALIGNMENT))
132
133 typedef _ALIGNED_ON(128) struct  GpuHidHaarTreeNode
134 {
135     _ALIGNED_ON(64) int p[CV_HAAR_FEATURE_MAX][4];
136     float weight[CV_HAAR_FEATURE_MAX] ;
137     float threshold ;
138     _ALIGNED_ON(16) float alpha[3] ;
139     _ALIGNED_ON(4) int left ;
140     _ALIGNED_ON(4) int right ;
141 }
142 GpuHidHaarTreeNode;
143
144
145 typedef  _ALIGNED_ON(32) struct  GpuHidHaarClassifier
146 {
147     _ALIGNED_ON(4) int count;
148     _ALIGNED_ON(8) GpuHidHaarTreeNode *node ;
149     _ALIGNED_ON(8) float *alpha ;
150 }
151 GpuHidHaarClassifier;
152
153
154 typedef _ALIGNED_ON(64) struct   GpuHidHaarStageClassifier
155 {
156     _ALIGNED_ON(4) int  count ;
157     _ALIGNED_ON(4) float threshold ;
158     _ALIGNED_ON(4) int two_rects ;
159     _ALIGNED_ON(8) GpuHidHaarClassifier *classifier ;
160     _ALIGNED_ON(8) struct GpuHidHaarStageClassifier *next;
161     _ALIGNED_ON(8) struct GpuHidHaarStageClassifier *child ;
162     _ALIGNED_ON(8) struct GpuHidHaarStageClassifier *parent ;
163 }
164 GpuHidHaarStageClassifier;
165
166
167 typedef _ALIGNED_ON(64) struct  GpuHidHaarClassifierCascade
168 {
169     _ALIGNED_ON(4) int  count ;
170     _ALIGNED_ON(4) int  is_stump_based ;
171     _ALIGNED_ON(4) int  has_tilted_features ;
172     _ALIGNED_ON(4) int  is_tree ;
173     _ALIGNED_ON(4) int pq0 ;
174     _ALIGNED_ON(4) int pq1 ;
175     _ALIGNED_ON(4) int pq2 ;
176     _ALIGNED_ON(4) int pq3 ;
177     _ALIGNED_ON(4) int p0 ;
178     _ALIGNED_ON(4) int p1 ;
179     _ALIGNED_ON(4) int p2 ;
180     _ALIGNED_ON(4) int p3 ;
181     _ALIGNED_ON(4) float inv_window_area ;
182 } GpuHidHaarClassifierCascade;
183 #else
184 #define _ALIGNED_ON(_ALIGNMENT) __attribute__((aligned(_ALIGNMENT) ))
185
186 typedef struct _ALIGNED_ON(128) GpuHidHaarTreeNode
187 {
188     int p[CV_HAAR_FEATURE_MAX][4] _ALIGNED_ON(64);
189     float weight[CV_HAAR_FEATURE_MAX];// _ALIGNED_ON(16);
190     float threshold;// _ALIGNED_ON(4);
191     float alpha[3] _ALIGNED_ON(16);
192     int left _ALIGNED_ON(4);
193     int right _ALIGNED_ON(4);
194 }
195 GpuHidHaarTreeNode;
196
197 typedef struct _ALIGNED_ON(32) GpuHidHaarClassifier
198 {
199     int count _ALIGNED_ON(4);
200     GpuHidHaarTreeNode *node _ALIGNED_ON(8);
201     float *alpha _ALIGNED_ON(8);
202 }
203 GpuHidHaarClassifier;
204
205
206 typedef struct _ALIGNED_ON(64) GpuHidHaarStageClassifier
207 {
208     int  count _ALIGNED_ON(4);
209     float threshold _ALIGNED_ON(4);
210     int two_rects _ALIGNED_ON(4);
211     GpuHidHaarClassifier *classifier _ALIGNED_ON(8);
212     struct GpuHidHaarStageClassifier *next _ALIGNED_ON(8);
213     struct GpuHidHaarStageClassifier *child _ALIGNED_ON(8);
214     struct GpuHidHaarStageClassifier *parent _ALIGNED_ON(8);
215 }
216 GpuHidHaarStageClassifier;
217
218
219 typedef struct _ALIGNED_ON(64) GpuHidHaarClassifierCascade
220 {
221     int  count _ALIGNED_ON(4);
222     int  is_stump_based _ALIGNED_ON(4);
223     int  has_tilted_features _ALIGNED_ON(4);
224     int  is_tree _ALIGNED_ON(4);
225     int pq0 _ALIGNED_ON(4);
226     int pq1 _ALIGNED_ON(4);
227     int pq2 _ALIGNED_ON(4);
228     int pq3 _ALIGNED_ON(4);
229     int p0 _ALIGNED_ON(4);
230     int p1 _ALIGNED_ON(4);
231     int p2 _ALIGNED_ON(4);
232     int p3 _ALIGNED_ON(4);
233     float inv_window_area _ALIGNED_ON(4);
234 } GpuHidHaarClassifierCascade;
235 #endif
236
237 const int icv_object_win_border = 1;
238 const float icv_stage_threshold_bias = 0.0001f;
239 double globaltime = 0;
240
241 /* create more efficient internal representation of haar classifier cascade */
242 static GpuHidHaarClassifierCascade * gpuCreateHidHaarClassifierCascade( CvHaarClassifierCascade *cascade, int *size, int *totalclassifier)
243 {
244     GpuHidHaarClassifierCascade *out = 0;
245
246     int i, j, k, l;
247     int datasize;
248     int total_classifiers = 0;
249     int total_nodes = 0;
250     char errorstr[256];
251
252     GpuHidHaarStageClassifier *stage_classifier_ptr;
253     GpuHidHaarClassifier *haar_classifier_ptr;
254     GpuHidHaarTreeNode *haar_node_ptr;
255
256     CvSize orig_window_size;
257     int has_tilted_features = 0;
258
259     if( !CV_IS_HAAR_CLASSIFIER(cascade) )
260         CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
261
262     if( cascade->hid_cascade )
263         CV_Error( CV_StsError, "hid_cascade has been already created" );
264
265     if( !cascade->stage_classifier )
266         CV_Error( CV_StsNullPtr, "" );
267
268     if( cascade->count <= 0 )
269         CV_Error( CV_StsOutOfRange, "Negative number of cascade stages" );
270
271     orig_window_size = cascade->orig_window_size;
272
273     /* check input structure correctness and calculate total memory size needed for
274     internal representation of the classifier cascade */
275     for( i = 0; i < cascade->count; i++ )
276     {
277         CvHaarStageClassifier *stage_classifier = cascade->stage_classifier + i;
278
279         if( !stage_classifier->classifier ||
280                 stage_classifier->count <= 0 )
281         {
282             sprintf( errorstr, "header of the stage classifier #%d is invalid "
283                      "(has null pointers or non-positive classfier count)", i );
284             CV_Error( CV_StsError, errorstr );
285         }
286
287         total_classifiers += stage_classifier->count;
288
289         for( j = 0; j < stage_classifier->count; j++ )
290         {
291             CvHaarClassifier *classifier = stage_classifier->classifier + j;
292
293             total_nodes += classifier->count;
294             for( l = 0; l < classifier->count; l++ )
295             {
296                 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
297                 {
298                     if( classifier->haar_feature[l].rect[k].r.width )
299                     {
300                         CvRect r = classifier->haar_feature[l].rect[k].r;
301                         int tilted = classifier->haar_feature[l].tilted;
302                         has_tilted_features |= tilted != 0;
303                         if( r.width < 0 || r.height < 0 || r.y < 0 ||
304                                 r.x + r.width > orig_window_size.width
305                                 ||
306                                 (!tilted &&
307                                  (r.x < 0 || r.y + r.height > orig_window_size.height))
308                                 ||
309                                 (tilted && (r.x - r.height < 0 ||
310                                             r.y + r.width + r.height > orig_window_size.height)))
311                         {
312                             sprintf( errorstr, "rectangle #%d of the classifier #%d of "
313                                      "the stage classifier #%d is not inside "
314                                      "the reference (original) cascade window", k, j, i );
315                             CV_Error( CV_StsNullPtr, errorstr );
316                         }
317                     }
318                 }
319             }
320         }
321     }
322
323     // this is an upper boundary for the whole hidden cascade size
324     datasize = sizeof(GpuHidHaarClassifierCascade)                   +
325                sizeof(GpuHidHaarStageClassifier) * cascade->count    +
326                sizeof(GpuHidHaarClassifier)      * total_classifiers +
327                sizeof(GpuHidHaarTreeNode)        * total_nodes;
328
329     *totalclassifier = total_classifiers;
330     *size = datasize;
331     out = (GpuHidHaarClassifierCascade *)cvAlloc( datasize );
332     memset( out, 0, sizeof(*out) );
333
334     /* init header */
335     out->count = cascade->count;
336     stage_classifier_ptr = (GpuHidHaarStageClassifier *)(out + 1);
337     haar_classifier_ptr = (GpuHidHaarClassifier *)(stage_classifier_ptr + cascade->count);
338     haar_node_ptr = (GpuHidHaarTreeNode *)(haar_classifier_ptr + total_classifiers);
339
340     out->is_stump_based = 1;
341     out->has_tilted_features = has_tilted_features;
342     out->is_tree = 0;
343
344     /* initialize internal representation */
345     for( i = 0; i < cascade->count; i++ )
346     {
347         CvHaarStageClassifier *stage_classifier = cascade->stage_classifier + i;
348         GpuHidHaarStageClassifier *hid_stage_classifier = stage_classifier_ptr + i;
349
350         hid_stage_classifier->count = stage_classifier->count;
351         hid_stage_classifier->threshold = stage_classifier->threshold - icv_stage_threshold_bias;
352         hid_stage_classifier->classifier = haar_classifier_ptr;
353         hid_stage_classifier->two_rects = 1;
354         haar_classifier_ptr += stage_classifier->count;
355
356         for( j = 0; j < stage_classifier->count; j++ )
357         {
358             CvHaarClassifier *classifier         = stage_classifier->classifier + j;
359             GpuHidHaarClassifier *hid_classifier = hid_stage_classifier->classifier + j;
360             int node_count = classifier->count;
361
362             float *alpha_ptr = &haar_node_ptr->alpha[0];
363
364             hid_classifier->count = node_count;
365             hid_classifier->node = haar_node_ptr;
366             hid_classifier->alpha = alpha_ptr;
367
368             for( l = 0; l < node_count; l++ )
369             {
370                 GpuHidHaarTreeNode *node     = hid_classifier->node + l;
371                 CvHaarFeature      *feature = classifier->haar_feature + l;
372
373                 memset( node, -1, sizeof(*node) );
374                 node->threshold = classifier->threshold[l];
375                 node->left      = classifier->left[l];
376                 node->right     = classifier->right[l];
377
378                 if( fabs(feature->rect[2].weight) < DBL_EPSILON ||
379                         feature->rect[2].r.width == 0 ||
380                         feature->rect[2].r.height == 0 )
381                 {
382                     node->p[2][0] = 0;
383                     node->p[2][1] = 0;
384                     node->p[2][2] = 0;
385                     node->p[2][3] = 0;
386                     node->weight[2] = 0;
387                 }
388                 else
389                     hid_stage_classifier->two_rects = 0;
390
391                 memcpy( node->alpha, classifier->alpha, (node_count + 1)*sizeof(alpha_ptr[0]));
392                 haar_node_ptr = haar_node_ptr + 1;
393             }
394             out->is_stump_based &= node_count == 1;
395         }
396     }
397
398     cascade->hid_cascade = (CvHidHaarClassifierCascade *)out;
399     assert( (char *)haar_node_ptr - (char *)out <= datasize );
400
401     return out;
402 }
403
404
405 #define sum_elem_ptr(sum,row,col)  \
406     ((sumtype*)CV_MAT_ELEM_PTR_FAST((sum),(row),(col),sizeof(sumtype)))
407
408 #define sqsum_elem_ptr(sqsum,row,col)  \
409     ((sqsumtype*)CV_MAT_ELEM_PTR_FAST((sqsum),(row),(col),sizeof(sqsumtype)))
410
411 #define calc_sum(rect,offset) \
412     ((rect).p0[offset] - (rect).p1[offset] - (rect).p2[offset] + (rect).p3[offset])
413
414
415 static void gpuSetImagesForHaarClassifierCascade( CvHaarClassifierCascade *_cascade,
416                                       double scale,
417                                       int step)
418 {
419     GpuHidHaarClassifierCascade *cascade;
420     int coi0 = 0, coi1 = 0;
421     int i;
422     int datasize;
423     int total;
424     CvRect equRect;
425     double weight_scale;
426     GpuHidHaarStageClassifier *stage_classifier;
427
428     if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
429         CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
430
431     if( scale <= 0 )
432         CV_Error( CV_StsOutOfRange, "Scale must be positive" );
433
434     if( coi0 || coi1 )
435         CV_Error( CV_BadCOI, "COI is not supported" );
436
437     if( !_cascade->hid_cascade )
438         gpuCreateHidHaarClassifierCascade(_cascade, &datasize, &total);
439
440     cascade = (GpuHidHaarClassifierCascade *) _cascade->hid_cascade;
441     stage_classifier = (GpuHidHaarStageClassifier *) (cascade + 1);
442
443     _cascade->scale = scale;
444     _cascade->real_window_size.width = cvRound( _cascade->orig_window_size.width * scale );
445     _cascade->real_window_size.height = cvRound( _cascade->orig_window_size.height * scale );
446
447     equRect.x = equRect.y = cvRound(scale);
448     equRect.width = cvRound((_cascade->orig_window_size.width - 2) * scale);
449     equRect.height = cvRound((_cascade->orig_window_size.height - 2) * scale);
450     weight_scale = 1. / (equRect.width * equRect.height);
451     cascade->inv_window_area = weight_scale;
452
453     cascade->pq0 = equRect.x;
454     cascade->pq1 = equRect.y;
455     cascade->pq2 = equRect.x + equRect.width;
456     cascade->pq3 = equRect.y + equRect.height;
457
458     cascade->p0 = equRect.x;
459     cascade->p1 = equRect.y;
460     cascade->p2 = equRect.x + equRect.width;
461     cascade->p3 = equRect.y + equRect.height;
462
463
464     /* init pointers in haar features according to real window size and
465     given image pointers */
466     for( i = 0; i < _cascade->count; i++ )
467     {
468         int j, k, l;
469         for( j = 0; j < stage_classifier[i].count; j++ )
470         {
471             for( l = 0; l < stage_classifier[i].classifier[j].count; l++ )
472             {
473                 CvHaarFeature *feature =
474                     &_cascade->stage_classifier[i].classifier[j].haar_feature[l];
475                 GpuHidHaarTreeNode *hidnode = &stage_classifier[i].classifier[j].node[l];
476                 double sum0 = 0, area0 = 0;
477                 CvRect r[3];
478
479                 int base_w = -1, base_h = -1;
480                 int new_base_w = 0, new_base_h = 0;
481                 int kx, ky;
482                 int flagx = 0, flagy = 0;
483                 int x0 = 0, y0 = 0;
484                 int nr;
485
486                 /* align blocks */
487                 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
488                 {
489                     if(!hidnode->p[k][0])
490                         break;
491                     r[k] = feature->rect[k].r;
492                     base_w = (int)CV_IMIN( (unsigned)base_w, (unsigned)(r[k].width - 1) );
493                     base_w = (int)CV_IMIN( (unsigned)base_w, (unsigned)(r[k].x - r[0].x - 1) );
494                     base_h = (int)CV_IMIN( (unsigned)base_h, (unsigned)(r[k].height - 1) );
495                     base_h = (int)CV_IMIN( (unsigned)base_h, (unsigned)(r[k].y - r[0].y - 1) );
496                 }
497
498                 nr = k;
499                 base_w += 1;
500                 base_h += 1;
501                 if(base_w == 0)
502                     base_w = 1;
503                 kx = r[0].width / base_w;
504                 if(base_h == 0)
505                     base_h = 1;
506                 ky = r[0].height / base_h;
507
508                 if( kx <= 0 )
509                 {
510                     flagx = 1;
511                     new_base_w = cvRound( r[0].width * scale ) / kx;
512                     x0 = cvRound( r[0].x * scale );
513                 }
514
515                 if( ky <= 0 )
516                 {
517                     flagy = 1;
518                     new_base_h = cvRound( r[0].height * scale ) / ky;
519                     y0 = cvRound( r[0].y * scale );
520                 }
521
522                 for( k = 0; k < nr; k++ )
523                 {
524                     CvRect tr;
525                     double correction_ratio;
526
527                     if( flagx )
528                     {
529                         tr.x = (r[k].x - r[0].x) * new_base_w / base_w + x0;
530                         tr.width = r[k].width * new_base_w / base_w;
531                     }
532                     else
533                     {
534                         tr.x = cvRound( r[k].x * scale );
535                         tr.width = cvRound( r[k].width * scale );
536                     }
537
538                     if( flagy )
539                     {
540                         tr.y = (r[k].y - r[0].y) * new_base_h / base_h + y0;
541                         tr.height = r[k].height * new_base_h / base_h;
542                     }
543                     else
544                     {
545                         tr.y = cvRound( r[k].y * scale );
546                         tr.height = cvRound( r[k].height * scale );
547                     }
548
549 #if CV_ADJUST_WEIGHTS
550                     {
551                         // RAINER START
552                         const float orig_feature_size =  (float)(feature->rect[k].r.width) * feature->rect[k].r.height;
553                         const float orig_norm_size = (float)(_cascade->orig_window_size.width) * (_cascade->orig_window_size.height);
554                         const float feature_size = float(tr.width * tr.height);
555                         //const float normSize    = float(equRect.width*equRect.height);
556                         float target_ratio = orig_feature_size / orig_norm_size;
557                         //float isRatio = featureSize / normSize;
558                         //correctionRatio = targetRatio / isRatio / normSize;
559                         correction_ratio = target_ratio / feature_size;
560                         // RAINER END
561                     }
562 #else
563                     correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
564 #endif
565
566                     if( !feature->tilted )
567                     {
568                         hidnode->p[k][0] = tr.x;
569                         hidnode->p[k][1] = tr.y;
570                         hidnode->p[k][2] = tr.x + tr.width;
571                         hidnode->p[k][3] = tr.y + tr.height;
572                     }
573                     else
574                     {
575                         hidnode->p[k][2] = (tr.y + tr.width) * step + tr.x + tr.width;
576                         hidnode->p[k][3] = (tr.y + tr.width + tr.height) * step + tr.x + tr.width - tr.height;
577                         hidnode->p[k][0] = tr.y * step + tr.x;
578                         hidnode->p[k][1] = (tr.y + tr.height) * step + tr.x - tr.height;
579                     }
580                     hidnode->weight[k] = (float)(feature->rect[k].weight * correction_ratio);
581                     if( k == 0 )
582                         area0 = tr.width * tr.height;
583                     else
584                         sum0 += hidnode->weight[k] * tr.width * tr.height;
585                 }
586                 hidnode->weight[0] = (float)(-sum0 / area0);
587             } /* l */
588         } /* j */
589     }
590 }
591
592 static void gpuSetHaarClassifierCascade( CvHaarClassifierCascade *_cascade)
593 {
594     GpuHidHaarClassifierCascade *cascade;
595     int i;
596     int datasize;
597     int total;
598     CvRect equRect;
599     double weight_scale;
600     GpuHidHaarStageClassifier *stage_classifier;
601
602     if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
603         CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
604
605     if( !_cascade->hid_cascade )
606         gpuCreateHidHaarClassifierCascade(_cascade, &datasize, &total);
607
608     cascade = (GpuHidHaarClassifierCascade *) _cascade->hid_cascade;
609     stage_classifier = (GpuHidHaarStageClassifier *) cascade + 1;
610
611     _cascade->scale = 1.0;
612     _cascade->real_window_size.width =  _cascade->orig_window_size.width ;
613     _cascade->real_window_size.height = _cascade->orig_window_size.height;
614
615     equRect.x = equRect.y = 1;
616     equRect.width = _cascade->orig_window_size.width - 2;
617     equRect.height = _cascade->orig_window_size.height - 2;
618     weight_scale = 1;
619     cascade->inv_window_area = weight_scale;
620
621     cascade->p0 = equRect.x;
622     cascade->p1 = equRect.y;
623     cascade->p2 = equRect.height;
624     cascade->p3 = equRect.width ;
625     for( i = 0; i < _cascade->count; i++ )
626     {
627         int j, l;
628         for( j = 0; j < stage_classifier[i].count; j++ )
629         {
630             for( l = 0; l < stage_classifier[i].classifier[j].count; l++ )
631             {
632                 const CvHaarFeature *feature =
633                     &_cascade->stage_classifier[i].classifier[j].haar_feature[l];
634                 GpuHidHaarTreeNode *hidnode = &stage_classifier[i].classifier[j].node[l];
635
636                 for( int k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
637                 {
638                     const CvRect tr = feature->rect[k].r;
639                     if (tr.width == 0)
640                         break;
641                     double correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
642                     hidnode->p[k][0] = tr.x;
643                     hidnode->p[k][1] = tr.y;
644                     hidnode->p[k][2] = tr.width;
645                     hidnode->p[k][3] = tr.height;
646                     hidnode->weight[k] = (float)(feature->rect[k].weight * correction_ratio);
647                 }
648             } /* l */
649         } /* j */
650     }
651 }
652 void OclCascadeClassifier::detectMultiScale(oclMat &gimg, CV_OUT std::vector<cv::Rect>& faces,
653                                             double scaleFactor, int minNeighbors, int flags,
654                                             Size minSize, Size maxSize)
655 //CvSeq *cv::ocl::OclCascadeClassifier::oclHaarDetectObjects( oclMat &gimg, CvMemStorage *storage, double scaleFactor,
656 //        int minNeighbors, int flags, CvSize minSize, CvSize maxSize)
657 {
658     CvHaarClassifierCascade *cascade = oldCascade;
659
660     const double GROUP_EPS = 0.2;
661
662     cv::ConcurrentRectVector allCandidates;
663     std::vector<cv::Rect> rectList;
664     std::vector<int> rweights;
665     double factor;
666     int datasize=0;
667     int totalclassifier=0;
668
669     GpuHidHaarClassifierCascade *gcascade;
670     GpuHidHaarStageClassifier    *stage;
671     GpuHidHaarClassifier         *classifier;
672     GpuHidHaarTreeNode           *node;
673
674     int *candidate;
675     cl_int status;
676
677     bool findBiggestObject = (flags & CV_HAAR_FIND_BIGGEST_OBJECT) != 0;
678
679     if( maxSize.height == 0 || maxSize.width == 0 )
680     {
681         maxSize.height = gimg.rows;
682         maxSize.width = gimg.cols;
683     }
684
685     if( !CV_IS_HAAR_CLASSIFIER(cascade) )
686         CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier cascade" );
687
688     //if( !storage )
689     //    CV_Error( CV_StsNullPtr, "Null storage pointer" );
690
691     if( CV_MAT_DEPTH(gimg.type()) != CV_8U )
692         CV_Error( CV_StsUnsupportedFormat, "Only 8-bit images are supported" );
693
694     if( scaleFactor <= 1 )
695         CV_Error( CV_StsOutOfRange, "scale factor must be > 1" );
696
697     if( findBiggestObject )
698         flags &= ~CV_HAAR_SCALE_IMAGE;
699
700     if( !cascade->hid_cascade )
701         gpuCreateHidHaarClassifierCascade(cascade, &datasize, &totalclassifier);
702
703     //result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), storage );
704
705     if( CV_MAT_CN(gimg.type()) > 1 )
706     {
707         oclMat gtemp;
708         cvtColor( gimg, gtemp, COLOR_BGR2GRAY );
709         gimg = gtemp;
710     }
711
712     if( findBiggestObject )
713         flags &= ~(CV_HAAR_SCALE_IMAGE | CV_HAAR_DO_CANNY_PRUNING);
714
715     if( gimg.cols < minSize.width || gimg.rows < minSize.height )
716         CV_Error(CV_StsError, "Image too small");
717
718     cl_command_queue qu = getClCommandQueue(Context::getContext());
719     if( (flags & CV_HAAR_SCALE_IMAGE) )
720     {
721         CvSize winSize0 = cascade->orig_window_size;
722         int totalheight = 0;
723         int indexy = 0;
724         CvSize sz;
725         std::vector<CvSize> sizev;
726         std::vector<float> scalev;
727         for(factor = 1.f;; factor *= scaleFactor)
728         {
729             CvSize winSize( cvRound(winSize0.width * factor), cvRound(winSize0.height * factor) );
730             sz.width     = cvRound( gimg.cols / factor ) + 1;
731             sz.height    = cvRound( gimg.rows / factor ) + 1;
732             CvSize sz1( sz.width - winSize0.width - 1,      sz.height - winSize0.height - 1 );
733
734             if( sz1.width <= 0 || sz1.height <= 0 )
735                 break;
736             if( winSize.width > maxSize.width || winSize.height > maxSize.height )
737                 break;
738             if( winSize.width < minSize.width || winSize.height < minSize.height )
739                 continue;
740
741             totalheight += sz.height;
742             sizev.push_back(sz);
743             scalev.push_back(factor);
744         }
745
746         oclMat gimg1(gimg.rows, gimg.cols, CV_8UC1);
747         oclMat gsum(totalheight + 4, gimg.cols + 1, CV_32SC1);
748         oclMat gsqsum(totalheight + 4, gimg.cols + 1, CV_32FC1);
749
750         cl_mem stagebuffer;
751         cl_mem nodebuffer;
752         cl_mem candidatebuffer;
753         cl_mem scaleinfobuffer;
754         cv::Rect roi, roi2;
755         cv::Mat imgroi, imgroisq;
756         cv::ocl::oclMat resizeroi, gimgroi, gimgroisq;
757         int grp_per_CU = 12;
758
759         size_t blocksize = 8;
760         size_t localThreads[3] = { blocksize, blocksize , 1 };
761         size_t globalThreads[3] = { grp_per_CU *(gsum.clCxt->getDeviceInfo().maxComputeUnits) *localThreads[0],
762                                     localThreads[1], 1
763                                   };
764         int outputsz = 256 * globalThreads[0] / localThreads[0];
765         int loopcount = sizev.size();
766         detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
767
768         for( int i = 0; i < loopcount; i++ )
769         {
770             sz = sizev[i];
771             factor = scalev[i];
772             roi = Rect(0, indexy, sz.width, sz.height);
773             roi2 = Rect(0, 0, sz.width - 1, sz.height - 1);
774             resizeroi = gimg1(roi2);
775             gimgroi = gsum(roi);
776             gimgroisq = gsqsum(roi);
777             int width = gimgroi.cols - 1 - cascade->orig_window_size.width;
778             int height = gimgroi.rows - 1 - cascade->orig_window_size.height;
779             scaleinfo[i].width_height = (width << 16) | height;
780
781
782             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
783             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
784
785             scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
786             scaleinfo[i].imgoff = gimgroi.offset >> 2;
787             scaleinfo[i].factor = factor;
788             cv::ocl::resize(gimg, resizeroi, Size(sz.width - 1, sz.height - 1), 0, 0, INTER_LINEAR);
789             cv::ocl::integral(resizeroi, gimgroi, gimgroisq);
790             indexy += sz.height;
791         }
792
793         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
794         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
795         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
796         node       = (GpuHidHaarTreeNode *)(classifier->node);
797
798         int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
799                        sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
800
801         candidate = (int *)malloc(4 * sizeof(int) * outputsz);
802
803         gpuSetImagesForHaarClassifierCascade( cascade, 1., gsum.step / 4 );
804
805         stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
806         openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
807
808         nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, nodenum * sizeof(GpuHidHaarTreeNode));
809
810         openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0, nodenum * sizeof(GpuHidHaarTreeNode),
811                                             node, 0, NULL, NULL));
812         candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY, 4 * sizeof(int) * outputsz);
813
814         scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
815         openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
816
817         int startstage = 0;
818         int endstage = gcascade->count;
819         int startnode = 0;
820         int pixelstep = gsum.step / 4;
821         int splitstage = 3;
822         int splitnode = stage[0].count + stage[1].count + stage[2].count;
823         cl_int4 p, pq;
824         p.s[0] = gcascade->p0;
825         p.s[1] = gcascade->p1;
826         p.s[2] = gcascade->p2;
827         p.s[3] = gcascade->p3;
828         pq.s[0] = gcascade->pq0;
829         pq.s[1] = gcascade->pq1;
830         pq.s[2] = gcascade->pq2;
831         pq.s[3] = gcascade->pq3;
832         float correction = gcascade->inv_window_area;
833
834         std::vector<std::pair<size_t, const void *> > args;
835         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
836         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
837         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
838         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
839         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
840         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
841         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&pixelstep ));
842         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&loopcount ));
843         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&startstage ));
844         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&splitstage ));
845         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&endstage ));
846         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&startnode ));
847         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&splitnode ));
848         args.push_back ( std::make_pair(sizeof(cl_int4) , (void *)&p ));
849         args.push_back ( std::make_pair(sizeof(cl_int4) , (void *)&pq ));
850         args.push_back ( std::make_pair(sizeof(cl_float) , (void *)&correction ));
851
852         if(gcascade->is_stump_based && gsum.clCxt->supportsFeature(FEATURE_CL_INTEL_DEVICE))
853         {
854             //setup local group size
855             localThreads[0] = 8;
856             localThreads[1] = 16;
857             localThreads[2] = 1;
858
859             //init maximal number of workgroups
860             int WGNumX = 1+(sizev[0].width /(localThreads[0]));
861             int WGNumY = 1+(sizev[0].height/(localThreads[1]));
862             int WGNumZ = loopcount;
863             int WGNum = 0; //accurate number of non -empty workgroups
864             oclMat      oclWGInfo(1,sizeof(cl_int4) * WGNumX*WGNumY*WGNumZ,CV_8U);
865             {
866                 cl_int4*    pWGInfo = (cl_int4*)clEnqueueMapBuffer(getClCommandQueue(oclWGInfo.clCxt),(cl_mem)oclWGInfo.datastart,true,CL_MAP_WRITE, 0, oclWGInfo.step, 0,0,0,&status);
867                 openCLVerifyCall(status);
868                 for(int z=0;z<WGNumZ;++z)
869                 {
870                     int     Width  = (scaleinfo[z].width_height >> 16)&0xFFFF;
871                     int     Height = (scaleinfo[z].width_height >> 0 )& 0xFFFF;
872                     for(int y=0;y<WGNumY;++y)
873                     {
874                         int     gy = y*localThreads[1];
875                         if(gy>=(Height-cascade->orig_window_size.height))
876                             continue; // no data to process
877                         for(int x=0;x<WGNumX;++x)
878                         {
879                             int     gx = x*localThreads[0];
880                             if(gx>=(Width-cascade->orig_window_size.width))
881                                 continue; // no data to process
882
883                             // save no-empty workgroup info into array
884                             pWGInfo[WGNum].s[0] = scaleinfo[z].width_height;
885                             pWGInfo[WGNum].s[1] = (gx << 16) | gy;
886                             pWGInfo[WGNum].s[2] = scaleinfo[z].imgoff;
887                             memcpy(&(pWGInfo[WGNum].s[3]),&(scaleinfo[z].factor),sizeof(float));
888                             WGNum++;
889                         }
890                     }
891                 }
892                 openCLSafeCall(clEnqueueUnmapMemObject(getClCommandQueue(oclWGInfo.clCxt),(cl_mem)oclWGInfo.datastart,pWGInfo,0,0,0));
893                 pWGInfo = NULL;
894             }
895
896             // setup global sizes to have linear array of workgroups with WGNum size
897             globalThreads[0] = localThreads[0]*WGNum;
898             globalThreads[1] = localThreads[1];
899             globalThreads[2] = 1;
900
901 #define NODE_SIZE 12
902             // pack node info to have less memory loads
903             oclMat  oclNodesPK(1,sizeof(cl_int) * NODE_SIZE * nodenum,CV_8U);
904             {
905                 cl_int  status;
906                 cl_int* pNodesPK = (cl_int*)clEnqueueMapBuffer(getClCommandQueue(oclNodesPK.clCxt),(cl_mem)oclNodesPK.datastart,true,CL_MAP_WRITE, 0, oclNodesPK.step, 0,0,0,&status);
907                 openCLVerifyCall(status);
908                 //use known local data stride to precalulate indexes
909                 int DATA_SIZE_X = (localThreads[0]+cascade->orig_window_size.width);
910                 // check that maximal value is less than maximal unsigned short
911                 assert(DATA_SIZE_X*cascade->orig_window_size.height+cascade->orig_window_size.width < USHRT_MAX);
912                 for(int i = 0;i<nodenum;++i)
913                 {//process each node from classifier
914                     struct NodePK
915                     {
916                         unsigned short  slm_index[3][4];
917                         float           weight[3];
918                         float           threshold;
919                         float           alpha[2];
920                     };
921                     struct NodePK * pOut = (struct NodePK *)(pNodesPK + NODE_SIZE*i);
922                     for(int k=0;k<3;++k)
923                     {// calc 4 short indexes in shared local mem for each rectangle instead of 2 (x,y) pair.
924                         int* p = &(node[i].p[k][0]);
925                         pOut->slm_index[k][0] = (unsigned short)(p[1]*DATA_SIZE_X+p[0]);
926                         pOut->slm_index[k][1] = (unsigned short)(p[1]*DATA_SIZE_X+p[2]);
927                         pOut->slm_index[k][2] = (unsigned short)(p[3]*DATA_SIZE_X+p[0]);
928                         pOut->slm_index[k][3] = (unsigned short)(p[3]*DATA_SIZE_X+p[2]);
929                     }
930                     //store used float point values for each node
931                     pOut->weight[0] = node[i].weight[0];
932                     pOut->weight[1] = node[i].weight[1];
933                     pOut->weight[2] = node[i].weight[2];
934                     pOut->threshold = node[i].threshold;
935                     pOut->alpha[0] = node[i].alpha[0];
936                    pOut->alpha[1] = node[i].alpha[1];
937                 }
938                 openCLSafeCall(clEnqueueUnmapMemObject(getClCommandQueue(oclNodesPK.clCxt),(cl_mem)oclNodesPK.datastart,pNodesPK,0,0,0));
939                 pNodesPK = NULL;
940             }
941             // add 2 additional buffers (WGinfo and packed nodes) as 2 last args
942             args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&oclNodesPK.datastart ));
943             args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&oclWGInfo.datastart ));
944
945             //form build options for kernel
946             String  options = "-D PACKED_CLASSIFIER";
947             options = options + format(" -D NODE_SIZE=%d",NODE_SIZE);
948             options = options + format(" -D WND_SIZE_X=%d",cascade->orig_window_size.width);
949             options = options + format(" -D WND_SIZE_Y=%d",cascade->orig_window_size.height);
950             options = options + format(" -D STUMP_BASED=%d",gcascade->is_stump_based);
951             options = options + format(" -D LSx=%d",localThreads[0]);
952             options = options + format(" -D LSy=%d",localThreads[1]);
953             options = options + format(" -D SPLITNODE=%d",splitnode);
954             options = options + format(" -D SPLITSTAGE=%d",splitstage);
955             options = options + format(" -D OUTPUTSZ=%d",outputsz);
956
957             // init candiate global count by 0
958             int pattern = 0;
959             openCLSafeCall(clEnqueueWriteBuffer(qu, candidatebuffer, 1, 0, 1 * sizeof(pattern),&pattern, 0, NULL, NULL));
960             // execute face detector
961             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascadePacked", globalThreads, localThreads, args, -1, -1, options.c_str());
962             //read candidate buffer back and put it into host list
963             openCLReadBuffer( gsum.clCxt, candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
964             assert(candidate[0]<outputsz);
965             //printf("candidate[0]=%d\n",candidate[0]);
966             for(int i = 1; i <= candidate[0]; i++)
967             {
968                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],candidate[4 * i + 2], candidate[4 * i + 3]));
969             }
970         }
971         else
972         {
973             const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
974
975             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascade", globalThreads, localThreads, args, -1, -1, build_options);
976
977             openCLReadBuffer( gsum.clCxt, candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
978
979             for(int i = 0; i < outputsz; i++)
980                 if(candidate[4 * i + 2] != 0)
981                     allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
982                     candidate[4 * i + 2], candidate[4 * i + 3]));
983         }
984
985         free(scaleinfo);
986         free(candidate);
987         openCLSafeCall(clReleaseMemObject(stagebuffer));
988         openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
989         openCLSafeCall(clReleaseMemObject(nodebuffer));
990         openCLSafeCall(clReleaseMemObject(candidatebuffer));
991
992     }
993     else
994     {
995         CvSize winsize0 = cascade->orig_window_size;
996         int n_factors = 0;
997         oclMat gsum;
998         oclMat gsqsum;
999         cv::ocl::integral(gimg, gsum, gsqsum);
1000         CvSize sz;
1001         std::vector<CvSize> sizev;
1002         std::vector<float> scalev;
1003         gpuSetHaarClassifierCascade(cascade);
1004         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1005         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1006         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1007         node       = (GpuHidHaarTreeNode *)(classifier->node);
1008         cl_mem stagebuffer;
1009         cl_mem nodebuffer;
1010         cl_mem candidatebuffer;
1011         cl_mem scaleinfobuffer;
1012         cl_mem pbuffer;
1013         cl_mem correctionbuffer;
1014         for( n_factors = 0, factor = 1;
1015                 cvRound(factor * winsize0.width) < gimg.cols - 10 &&
1016                 cvRound(factor * winsize0.height) < gimg.rows - 10;
1017                 n_factors++, factor *= scaleFactor )
1018         {
1019             CvSize winSize( cvRound( winsize0.width * factor ), cvRound( winsize0.height * factor ) );
1020             if( winSize.width < minSize.width || winSize.height < minSize.height )
1021             {
1022                 continue;
1023             }
1024             sizev.push_back(winSize);
1025             scalev.push_back(factor);
1026         }
1027         int loopcount = scalev.size();
1028         if(loopcount == 0)
1029         {
1030             loopcount = 1;
1031             n_factors = 1;
1032             sizev.push_back(minSize);
1033             scalev.push_back( std::min(cvRound(minSize.width / winsize0.width), cvRound(minSize.height / winsize0.height)) );
1034         }
1035         detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1036         cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * loopcount);
1037         float *correction = (float *)malloc(sizeof(float) * loopcount);
1038         int grp_per_CU = 12;
1039         size_t blocksize = 8;
1040         size_t localThreads[3] = { blocksize, blocksize , 1 };
1041         size_t globalThreads[3] = { grp_per_CU *gsum.clCxt->getDeviceInfo().maxComputeUnits *localThreads[0],
1042                                     localThreads[1], 1 };
1043         int outputsz = 256 * globalThreads[0] / localThreads[0];
1044         int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
1045                        sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
1046         nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY,
1047                                         nodenum * sizeof(GpuHidHaarTreeNode));
1048         openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0,
1049                                             nodenum * sizeof(GpuHidHaarTreeNode),
1050                                             node, 0, NULL, NULL));
1051         cl_mem newnodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_WRITE,
1052                                loopcount * nodenum * sizeof(GpuHidHaarTreeNode));
1053         int startstage = 0;
1054         int endstage = gcascade->count;
1055         for(int i = 0; i < loopcount; i++)
1056         {
1057             sz = sizev[i];
1058             factor = scalev[i];
1059             double ystep = std::max(2., factor);
1060             int equRect_x = cvRound(factor * gcascade->p0);
1061             int equRect_y = cvRound(factor * gcascade->p1);
1062             int equRect_w = cvRound(factor * gcascade->p3);
1063             int equRect_h = cvRound(factor * gcascade->p2);
1064             p[i].s[0] = equRect_x;
1065             p[i].s[1] = equRect_y;
1066             p[i].s[2] = equRect_x + equRect_w;
1067             p[i].s[3] = equRect_y + equRect_h;
1068             correction[i] = 1. / (equRect_w * equRect_h);
1069             int width = (gsum.cols - 1 - sz.width  + ystep - 1) / ystep;
1070             int height = (gsum.rows - 1 - sz.height + ystep - 1) / ystep;
1071             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1072             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1073
1074             scaleinfo[i].width_height = (width << 16) | height;
1075             scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1076             scaleinfo[i].imgoff = 0;
1077             scaleinfo[i].factor = factor;
1078             int startnodenum = nodenum * i;
1079             float factor2 = (float)factor;
1080
1081             std::vector<std::pair<size_t, const void *> > args1;
1082             args1.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
1083             args1.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1084             args1.push_back ( std::make_pair(sizeof(cl_float) , (void *)&factor2 ));
1085             args1.push_back ( std::make_pair(sizeof(cl_float) , (void *)&correction[i] ));
1086             args1.push_back ( std::make_pair(sizeof(cl_int) , (void *)&startnodenum ));
1087
1088             size_t globalThreads2[3] = {nodenum, 1, 1};
1089             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
1090         }
1091
1092         int step = gsum.step / 4;
1093         int startnode = 0;
1094         int splitstage = 3;
1095         stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
1096         openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
1097         candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR, 4 * sizeof(int) * outputsz);
1098         scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
1099         openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
1100         pbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_int4) * loopcount);
1101         openCLSafeCall(clEnqueueWriteBuffer(qu, pbuffer, 1, 0, sizeof(cl_int4)*loopcount, p, 0, NULL, NULL));
1102         correctionbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_float) * loopcount);
1103         openCLSafeCall(clEnqueueWriteBuffer(qu, correctionbuffer, 1, 0, sizeof(cl_float)*loopcount, correction, 0, NULL, NULL));
1104
1105         std::vector<std::pair<size_t, const void *> > args;
1106         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
1107         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
1108         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1109         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1110         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1111         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
1112         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1113         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1114         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&step ));
1115         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&loopcount ));
1116         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&startstage ));
1117         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&splitstage ));
1118         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&endstage ));
1119         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&startnode ));
1120         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&pbuffer ));
1121         args.push_back ( std::make_pair(sizeof(cl_mem) , (void *)&correctionbuffer ));
1122         args.push_back ( std::make_pair(sizeof(cl_int) , (void *)&nodenum ));
1123         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1124         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1125
1126         candidate = (int *)clEnqueueMapBuffer(qu, candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, &status);
1127
1128         for(int i = 0; i < outputsz; i++)
1129         {
1130             if(candidate[4 * i + 2] != 0)
1131                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1], candidate[4 * i + 2], candidate[4 * i + 3]));
1132         }
1133
1134         free(scaleinfo);
1135         free(p);
1136         free(correction);
1137         clEnqueueUnmapMemObject(qu, candidatebuffer, candidate, 0, 0, 0);
1138         openCLSafeCall(clReleaseMemObject(stagebuffer));
1139         openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
1140         openCLSafeCall(clReleaseMemObject(nodebuffer));
1141         openCLSafeCall(clReleaseMemObject(newnodebuffer));
1142         openCLSafeCall(clReleaseMemObject(candidatebuffer));
1143         openCLSafeCall(clReleaseMemObject(pbuffer));
1144         openCLSafeCall(clReleaseMemObject(correctionbuffer));
1145     }
1146
1147     cvFree(&cascade->hid_cascade);
1148     rectList.resize(allCandidates.size());
1149     if(!allCandidates.empty())
1150         std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1151
1152     if( minNeighbors != 0 || findBiggestObject )
1153         groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1154     else
1155         rweights.resize(rectList.size(), 0);
1156
1157     faces.clear();
1158     if( findBiggestObject && rectList.size() )
1159     {
1160         Rect result_comp(0, 0, 0, 0);
1161         for( size_t i = 0; i < rectList.size(); i++ )
1162         {
1163             cv::Rect r = rectList[i];
1164             if( r.area() > result_comp.area() )
1165             {
1166                 result_comp = r;
1167             }
1168         }
1169         faces.push_back(result_comp);
1170     }
1171     else
1172     {
1173         faces = rectList;
1174     }
1175 }