Added few opencl optimizations (as Intel platform codepath):
[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 //    Sen Liu, swjtuls1987@126.com
24 //
25 // Redistribution and use in source and binary forms, with or without modification,
26 // are permitted provided that the following conditions are met:
27 //
28 //   * Redistribution's of source code must retain the above copyright notice,
29 //     this list of conditions and the following disclaimer.
30 //
31 //   * Redistribution's in binary form must reproduce the above copyright notice,
32 //     this list of conditions and the following disclaimer in the documentation
33 //     and/or other oclMaterials provided with the distribution.
34 //
35 //   * The name of the copyright holders may not be used to endorse or promote products
36 //     derived from this software without specific prior written permission.
37 //
38 // This software is provided by the copyright holders and contributors "as is" and
39 // any express or implied warranties, including, but not limited to, the implied
40 // warranties of merchantability and fitness for a particular purpose are disclaimed.
41 // In no event shall the Intel Corporation or contributors be liable for any direct,
42 // indirect, incidental, special, exemplary, or consequential damages
43 // (including, but not limited to, procurement of substitute goods or services;
44 // loss of use, data, or profits; or business interruption) however caused
45 // and on any theory of liability, whether in contract, strict liability,
46 // or tort (including negligence or otherwise) arising in any way out of
47 // the use of this software, even if advised of the possibility of such damage.
48 //
49 //M*/
50
51 #include "precomp.hpp"
52 #include "opencl_kernels.hpp"
53
54 using namespace cv;
55 using namespace cv::ocl;
56
57 /* these settings affect the quality of detection: change with care */
58 #define CV_ADJUST_FEATURES 1
59 #define CV_ADJUST_WEIGHTS  0
60
61 typedef int sumtype;
62 typedef double sqsumtype;
63
64 typedef struct CvHidHaarFeature
65 {
66     struct
67     {
68         sumtype *p0, *p1, *p2, *p3;
69         float weight;
70     }
71     rect[CV_HAAR_FEATURE_MAX];
72 }
73 CvHidHaarFeature;
74
75
76 typedef struct CvHidHaarTreeNode
77 {
78     CvHidHaarFeature feature;
79     float threshold;
80     int left;
81     int right;
82 }
83 CvHidHaarTreeNode;
84
85
86 typedef struct CvHidHaarClassifier
87 {
88     int count;
89     //CvHaarFeature* orig_feature;
90     CvHidHaarTreeNode *node;
91     float *alpha;
92 }
93 CvHidHaarClassifier;
94
95
96 typedef struct CvHidHaarStageClassifier
97 {
98     int  count;
99     float threshold;
100     CvHidHaarClassifier *classifier;
101     int two_rects;
102
103     struct CvHidHaarStageClassifier *next;
104     struct CvHidHaarStageClassifier *child;
105     struct CvHidHaarStageClassifier *parent;
106 }
107 CvHidHaarStageClassifier;
108
109
110 struct CvHidHaarClassifierCascade
111 {
112     int  count;
113     int  is_stump_based;
114     int  has_tilted_features;
115     int  is_tree;
116     double inv_window_area;
117     CvMat sum, sqsum, tilted;
118     CvHidHaarStageClassifier *stage_classifier;
119     sqsumtype *pq0, *pq1, *pq2, *pq3;
120     sumtype *p0, *p1, *p2, *p3;
121
122     void **ipp_stages;
123 };
124 typedef struct
125 {
126     int width_height;
127     int grpnumperline_totalgrp;
128     int imgoff;
129     float factor;
130 } detect_piramid_info;
131 #ifdef _MSC_VER
132 #define _ALIGNED_ON(_ALIGNMENT) __declspec(align(_ALIGNMENT))
133
134 typedef _ALIGNED_ON(128) struct  GpuHidHaarTreeNode
135 {
136     _ALIGNED_ON(64) int p[CV_HAAR_FEATURE_MAX][4];
137     float weight[CV_HAAR_FEATURE_MAX] ;
138     float threshold ;
139     _ALIGNED_ON(16) float alpha[3] ;
140     _ALIGNED_ON(4) int left ;
141     _ALIGNED_ON(4) int right ;
142 }
143 GpuHidHaarTreeNode;
144
145
146 typedef  _ALIGNED_ON(32) struct  GpuHidHaarClassifier
147 {
148     _ALIGNED_ON(4) int count;
149     _ALIGNED_ON(8) GpuHidHaarTreeNode *node ;
150     _ALIGNED_ON(8) float *alpha ;
151 }
152 GpuHidHaarClassifier;
153
154
155 typedef _ALIGNED_ON(64) struct   GpuHidHaarStageClassifier
156 {
157     _ALIGNED_ON(4) int  count ;
158     _ALIGNED_ON(4) float threshold ;
159     _ALIGNED_ON(4) int two_rects ;
160     _ALIGNED_ON(8) GpuHidHaarClassifier *classifier ;
161     _ALIGNED_ON(8) struct GpuHidHaarStageClassifier *next;
162     _ALIGNED_ON(8) struct GpuHidHaarStageClassifier *child ;
163     _ALIGNED_ON(8) struct GpuHidHaarStageClassifier *parent ;
164 }
165 GpuHidHaarStageClassifier;
166
167
168 typedef _ALIGNED_ON(64) struct  GpuHidHaarClassifierCascade
169 {
170     _ALIGNED_ON(4) int  count ;
171     _ALIGNED_ON(4) int  is_stump_based ;
172     _ALIGNED_ON(4) int  has_tilted_features ;
173     _ALIGNED_ON(4) int  is_tree ;
174     _ALIGNED_ON(4) int pq0 ;
175     _ALIGNED_ON(4) int pq1 ;
176     _ALIGNED_ON(4) int pq2 ;
177     _ALIGNED_ON(4) int pq3 ;
178     _ALIGNED_ON(4) int p0 ;
179     _ALIGNED_ON(4) int p1 ;
180     _ALIGNED_ON(4) int p2 ;
181     _ALIGNED_ON(4) int p3 ;
182     _ALIGNED_ON(4) float inv_window_area ;
183 } GpuHidHaarClassifierCascade;
184 #else
185 #define _ALIGNED_ON(_ALIGNMENT) __attribute__((aligned(_ALIGNMENT) ))
186
187 typedef struct _ALIGNED_ON(128) GpuHidHaarTreeNode
188 {
189     int p[CV_HAAR_FEATURE_MAX][4] _ALIGNED_ON(64);
190     float weight[CV_HAAR_FEATURE_MAX];// _ALIGNED_ON(16);
191     float threshold;// _ALIGNED_ON(4);
192     float alpha[3] _ALIGNED_ON(16);
193     int left _ALIGNED_ON(4);
194     int right _ALIGNED_ON(4);
195 }
196 GpuHidHaarTreeNode;
197
198 typedef struct _ALIGNED_ON(32) GpuHidHaarClassifier
199 {
200     int count _ALIGNED_ON(4);
201     GpuHidHaarTreeNode *node _ALIGNED_ON(8);
202     float *alpha _ALIGNED_ON(8);
203 }
204 GpuHidHaarClassifier;
205
206
207 typedef struct _ALIGNED_ON(64) GpuHidHaarStageClassifier
208 {
209     int  count _ALIGNED_ON(4);
210     float threshold _ALIGNED_ON(4);
211     int two_rects _ALIGNED_ON(4);
212     GpuHidHaarClassifier *classifier _ALIGNED_ON(8);
213     struct GpuHidHaarStageClassifier *next _ALIGNED_ON(8);
214     struct GpuHidHaarStageClassifier *child _ALIGNED_ON(8);
215     struct GpuHidHaarStageClassifier *parent _ALIGNED_ON(8);
216 }
217 GpuHidHaarStageClassifier;
218
219
220 typedef struct _ALIGNED_ON(64) GpuHidHaarClassifierCascade
221 {
222     int  count _ALIGNED_ON(4);
223     int  is_stump_based _ALIGNED_ON(4);
224     int  has_tilted_features _ALIGNED_ON(4);
225     int  is_tree _ALIGNED_ON(4);
226     int pq0 _ALIGNED_ON(4);
227     int pq1 _ALIGNED_ON(4);
228     int pq2 _ALIGNED_ON(4);
229     int pq3 _ALIGNED_ON(4);
230     int p0 _ALIGNED_ON(4);
231     int p1 _ALIGNED_ON(4);
232     int p2 _ALIGNED_ON(4);
233     int p3 _ALIGNED_ON(4);
234     float inv_window_area _ALIGNED_ON(4);
235 } GpuHidHaarClassifierCascade;
236 #endif
237
238 const int icv_object_win_border = 1;
239 const float icv_stage_threshold_bias = 0.0001f;
240 double globaltime = 0;
241
242 /* create more efficient internal representation of haar classifier cascade */
243 static GpuHidHaarClassifierCascade * gpuCreateHidHaarClassifierCascade( CvHaarClassifierCascade *cascade, int *size, int *totalclassifier)
244 {
245     GpuHidHaarClassifierCascade *out = 0;
246
247     int i, j, k, l;
248     int datasize;
249     int total_classifiers = 0;
250     int total_nodes = 0;
251     char errorstr[256];
252
253     GpuHidHaarStageClassifier *stage_classifier_ptr;
254     GpuHidHaarClassifier *haar_classifier_ptr;
255     GpuHidHaarTreeNode *haar_node_ptr;
256
257     CvSize orig_window_size;
258     int has_tilted_features = 0;
259
260     if( !CV_IS_HAAR_CLASSIFIER(cascade) )
261         CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
262
263     if( cascade->hid_cascade )
264         CV_Error( CV_StsError, "hid_cascade has been already created" );
265
266     if( !cascade->stage_classifier )
267         CV_Error( CV_StsNullPtr, "" );
268
269     if( cascade->count <= 0 )
270         CV_Error( CV_StsOutOfRange, "Negative number of cascade stages" );
271
272     orig_window_size = cascade->orig_window_size;
273
274     /* check input structure correctness and calculate total memory size needed for
275     internal representation of the classifier cascade */
276     for( i = 0; i < cascade->count; i++ )
277     {
278         CvHaarStageClassifier *stage_classifier = cascade->stage_classifier + i;
279
280         if( !stage_classifier->classifier ||
281                 stage_classifier->count <= 0 )
282         {
283             sprintf( errorstr, "header of the stage classifier #%d is invalid "
284                      "(has null pointers or non-positive classfier count)", i );
285             CV_Error( CV_StsError, errorstr );
286         }
287
288         total_classifiers += stage_classifier->count;
289
290         for( j = 0; j < stage_classifier->count; j++ )
291         {
292             CvHaarClassifier *classifier = stage_classifier->classifier + j;
293
294             total_nodes += classifier->count;
295             for( l = 0; l < classifier->count; l++ )
296             {
297                 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
298                 {
299                     if( classifier->haar_feature[l].rect[k].r.width )
300                     {
301                         CvRect r = classifier->haar_feature[l].rect[k].r;
302                         int tilted = classifier->haar_feature[l].tilted;
303                         has_tilted_features |= tilted != 0;
304                         if( r.width < 0 || r.height < 0 || r.y < 0 ||
305                                 r.x + r.width > orig_window_size.width
306                                 ||
307                                 (!tilted &&
308                                  (r.x < 0 || r.y + r.height > orig_window_size.height))
309                                 ||
310                                 (tilted && (r.x - r.height < 0 ||
311                                             r.y + r.width + r.height > orig_window_size.height)))
312                         {
313                             sprintf( errorstr, "rectangle #%d of the classifier #%d of "
314                                      "the stage classifier #%d is not inside "
315                                      "the reference (original) cascade window", k, j, i );
316                             CV_Error( CV_StsNullPtr, errorstr );
317                         }
318                     }
319                 }
320             }
321         }
322     }
323
324     // this is an upper boundary for the whole hidden cascade size
325     datasize = sizeof(GpuHidHaarClassifierCascade)                   +
326                sizeof(GpuHidHaarStageClassifier) * cascade->count    +
327                sizeof(GpuHidHaarClassifier)      * total_classifiers +
328                sizeof(GpuHidHaarTreeNode)        * total_nodes;
329
330     *totalclassifier = total_classifiers;
331     *size = datasize;
332     out = (GpuHidHaarClassifierCascade *)cvAlloc( datasize );
333     memset( out, 0, sizeof(*out) );
334
335     /* init header */
336     out->count = cascade->count;
337     stage_classifier_ptr = (GpuHidHaarStageClassifier *)(out + 1);
338     haar_classifier_ptr = (GpuHidHaarClassifier *)(stage_classifier_ptr + cascade->count);
339     haar_node_ptr = (GpuHidHaarTreeNode *)(haar_classifier_ptr + total_classifiers);
340
341     out->is_stump_based = 1;
342     out->has_tilted_features = has_tilted_features;
343     out->is_tree = 0;
344
345     /* initialize internal representation */
346     for( i = 0; i < cascade->count; i++ )
347     {
348         CvHaarStageClassifier *stage_classifier = cascade->stage_classifier + i;
349         GpuHidHaarStageClassifier *hid_stage_classifier = stage_classifier_ptr + i;
350
351         hid_stage_classifier->count = stage_classifier->count;
352         hid_stage_classifier->threshold = stage_classifier->threshold - icv_stage_threshold_bias;
353         hid_stage_classifier->classifier = haar_classifier_ptr;
354         hid_stage_classifier->two_rects = 1;
355         haar_classifier_ptr += stage_classifier->count;
356
357         for( j = 0; j < stage_classifier->count; j++ )
358         {
359             CvHaarClassifier *classifier         = stage_classifier->classifier + j;
360             GpuHidHaarClassifier *hid_classifier = hid_stage_classifier->classifier + j;
361             int node_count = classifier->count;
362
363             float *alpha_ptr = &haar_node_ptr->alpha[0];
364
365             hid_classifier->count = node_count;
366             hid_classifier->node = haar_node_ptr;
367             hid_classifier->alpha = alpha_ptr;
368
369             for( l = 0; l < node_count; l++ )
370             {
371                 GpuHidHaarTreeNode *node     = hid_classifier->node + l;
372                 CvHaarFeature      *feature = classifier->haar_feature + l;
373
374                 memset( node, -1, sizeof(*node) );
375                 node->threshold = classifier->threshold[l];
376                 node->left      = classifier->left[l];
377                 node->right     = classifier->right[l];
378
379                 if( fabs(feature->rect[2].weight) < DBL_EPSILON ||
380                         feature->rect[2].r.width == 0 ||
381                         feature->rect[2].r.height == 0 )
382                 {
383                     node->p[2][0] = 0;
384                     node->p[2][1] = 0;
385                     node->p[2][2] = 0;
386                     node->p[2][3] = 0;
387                     node->weight[2] = 0;
388                 }
389                 else
390                     hid_stage_classifier->two_rects = 0;
391
392                 memcpy( node->alpha, classifier->alpha, (node_count + 1)*sizeof(alpha_ptr[0]));
393                 haar_node_ptr = haar_node_ptr + 1;
394             }
395             out->is_stump_based &= node_count == 1;
396         }
397     }
398
399     cascade->hid_cascade = (CvHidHaarClassifierCascade *)out;
400     assert( (char *)haar_node_ptr - (char *)out <= datasize );
401
402     return out;
403 }
404
405
406 #define sum_elem_ptr(sum,row,col)  \
407     ((sumtype*)CV_MAT_ELEM_PTR_FAST((sum),(row),(col),sizeof(sumtype)))
408
409 #define sqsum_elem_ptr(sqsum,row,col)  \
410     ((sqsumtype*)CV_MAT_ELEM_PTR_FAST((sqsum),(row),(col),sizeof(sqsumtype)))
411
412 #define calc_sum(rect,offset) \
413     ((rect).p0[offset] - (rect).p1[offset] - (rect).p2[offset] + (rect).p3[offset])
414
415
416 static void gpuSetImagesForHaarClassifierCascade( CvHaarClassifierCascade *_cascade,
417                                       double scale,
418                                       int step)
419 {
420     GpuHidHaarClassifierCascade *cascade;
421     int coi0 = 0, coi1 = 0;
422     int i;
423     int datasize;
424     int total;
425     CvRect equRect;
426     double weight_scale;
427     GpuHidHaarStageClassifier *stage_classifier;
428
429     if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
430         CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
431
432     if( scale <= 0 )
433         CV_Error( CV_StsOutOfRange, "Scale must be positive" );
434
435     if( coi0 || coi1 )
436         CV_Error( CV_BadCOI, "COI is not supported" );
437
438     if( !_cascade->hid_cascade )
439         gpuCreateHidHaarClassifierCascade(_cascade, &datasize, &total);
440
441     cascade = (GpuHidHaarClassifierCascade *) _cascade->hid_cascade;
442     stage_classifier = (GpuHidHaarStageClassifier *) (cascade + 1);
443
444     _cascade->scale = scale;
445     _cascade->real_window_size.width = cvRound( _cascade->orig_window_size.width * scale );
446     _cascade->real_window_size.height = cvRound( _cascade->orig_window_size.height * scale );
447
448     equRect.x = equRect.y = cvRound(scale);
449     equRect.width = cvRound((_cascade->orig_window_size.width - 2) * scale);
450     equRect.height = cvRound((_cascade->orig_window_size.height - 2) * scale);
451     weight_scale = 1. / (equRect.width * equRect.height);
452     cascade->inv_window_area = weight_scale;
453
454     cascade->pq0 = equRect.x;
455     cascade->pq1 = equRect.y;
456     cascade->pq2 = equRect.x + equRect.width;
457     cascade->pq3 = equRect.y + equRect.height;
458
459     cascade->p0 = equRect.x;
460     cascade->p1 = equRect.y;
461     cascade->p2 = equRect.x + equRect.width;
462     cascade->p3 = equRect.y + equRect.height;
463
464
465     /* init pointers in haar features according to real window size and
466     given image pointers */
467     for( i = 0; i < _cascade->count; i++ )
468     {
469         int j, k, l;
470         for( j = 0; j < stage_classifier[i].count; j++ )
471         {
472             for( l = 0; l < stage_classifier[i].classifier[j].count; l++ )
473             {
474                 CvHaarFeature *feature =
475                     &_cascade->stage_classifier[i].classifier[j].haar_feature[l];
476                 GpuHidHaarTreeNode *hidnode = &stage_classifier[i].classifier[j].node[l];
477                 double sum0 = 0, area0 = 0;
478                 CvRect r[3];
479
480                 int base_w = -1, base_h = -1;
481                 int new_base_w = 0, new_base_h = 0;
482                 int kx, ky;
483                 int flagx = 0, flagy = 0;
484                 int x0 = 0, y0 = 0;
485                 int nr;
486
487                 /* align blocks */
488                 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
489                 {
490                     if(!hidnode->p[k][0])
491                         break;
492                     r[k] = feature->rect[k].r;
493                     base_w = (int)CV_IMIN( (unsigned)base_w, (unsigned)(r[k].width - 1) );
494                     base_w = (int)CV_IMIN( (unsigned)base_w, (unsigned)(r[k].x - r[0].x - 1) );
495                     base_h = (int)CV_IMIN( (unsigned)base_h, (unsigned)(r[k].height - 1) );
496                     base_h = (int)CV_IMIN( (unsigned)base_h, (unsigned)(r[k].y - r[0].y - 1) );
497                 }
498
499                 nr = k;
500                 base_w += 1;
501                 base_h += 1;
502                 if(base_w == 0)
503                     base_w = 1;
504                 kx = r[0].width / base_w;
505                 if(base_h == 0)
506                     base_h = 1;
507                 ky = r[0].height / base_h;
508
509                 if( kx <= 0 )
510                 {
511                     flagx = 1;
512                     new_base_w = cvRound( r[0].width * scale ) / kx;
513                     x0 = cvRound( r[0].x * scale );
514                 }
515
516                 if( ky <= 0 )
517                 {
518                     flagy = 1;
519                     new_base_h = cvRound( r[0].height * scale ) / ky;
520                     y0 = cvRound( r[0].y * scale );
521                 }
522
523                 for( k = 0; k < nr; k++ )
524                 {
525                     CvRect tr;
526                     double correction_ratio;
527
528                     if( flagx )
529                     {
530                         tr.x = (r[k].x - r[0].x) * new_base_w / base_w + x0;
531                         tr.width = r[k].width * new_base_w / base_w;
532                     }
533                     else
534                     {
535                         tr.x = cvRound( r[k].x * scale );
536                         tr.width = cvRound( r[k].width * scale );
537                     }
538
539                     if( flagy )
540                     {
541                         tr.y = (r[k].y - r[0].y) * new_base_h / base_h + y0;
542                         tr.height = r[k].height * new_base_h / base_h;
543                     }
544                     else
545                     {
546                         tr.y = cvRound( r[k].y * scale );
547                         tr.height = cvRound( r[k].height * scale );
548                     }
549
550 #if CV_ADJUST_WEIGHTS
551                     {
552                         // RAINER START
553                         const float orig_feature_size =  (float)(feature->rect[k].r.width) * feature->rect[k].r.height;
554                         const float orig_norm_size = (float)(_cascade->orig_window_size.width) * (_cascade->orig_window_size.height);
555                         const float feature_size = float(tr.width * tr.height);
556                         //const float normSize    = float(equRect.width*equRect.height);
557                         float target_ratio = orig_feature_size / orig_norm_size;
558                         //float isRatio = featureSize / normSize;
559                         //correctionRatio = targetRatio / isRatio / normSize;
560                         correction_ratio = target_ratio / feature_size;
561                         // RAINER END
562                     }
563 #else
564                     correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
565 #endif
566
567                     if( !feature->tilted )
568                     {
569                         hidnode->p[k][0] = tr.x;
570                         hidnode->p[k][1] = tr.y;
571                         hidnode->p[k][2] = tr.x + tr.width;
572                         hidnode->p[k][3] = tr.y + tr.height;
573                     }
574                     else
575                     {
576                         hidnode->p[k][2] = (tr.y + tr.width) * step + tr.x + tr.width;
577                         hidnode->p[k][3] = (tr.y + tr.width + tr.height) * step + tr.x + tr.width - tr.height;
578                         hidnode->p[k][0] = tr.y * step + tr.x;
579                         hidnode->p[k][1] = (tr.y + tr.height) * step + tr.x - tr.height;
580                     }
581                     hidnode->weight[k] = (float)(feature->rect[k].weight * correction_ratio);
582                     if( k == 0 )
583                         area0 = tr.width * tr.height;
584                     else
585                         sum0 += hidnode->weight[k] * tr.width * tr.height;
586                 }
587                 hidnode->weight[0] = (float)(-sum0 / area0);
588             } /* l */
589         } /* j */
590     }
591 }
592
593 static void gpuSetHaarClassifierCascade( CvHaarClassifierCascade *_cascade)
594 {
595     GpuHidHaarClassifierCascade *cascade;
596     int i;
597     int datasize;
598     int total;
599     CvRect equRect;
600     double weight_scale;
601     GpuHidHaarStageClassifier *stage_classifier;
602
603     if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
604         CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
605
606     if( !_cascade->hid_cascade )
607         gpuCreateHidHaarClassifierCascade(_cascade, &datasize, &total);
608
609     cascade = (GpuHidHaarClassifierCascade *) _cascade->hid_cascade;
610     stage_classifier = (GpuHidHaarStageClassifier *) cascade + 1;
611
612     _cascade->scale = 1.0;
613     _cascade->real_window_size.width =  _cascade->orig_window_size.width ;
614     _cascade->real_window_size.height = _cascade->orig_window_size.height;
615
616     equRect.x = equRect.y = 1;
617     equRect.width = _cascade->orig_window_size.width - 2;
618     equRect.height = _cascade->orig_window_size.height - 2;
619     weight_scale = 1;
620     cascade->inv_window_area = weight_scale;
621
622     cascade->p0 = equRect.x;
623     cascade->p1 = equRect.y;
624     cascade->p2 = equRect.height;
625     cascade->p3 = equRect.width ;
626     for( i = 0; i < _cascade->count; i++ )
627     {
628         int j, l;
629         for( j = 0; j < stage_classifier[i].count; j++ )
630         {
631             for( l = 0; l < stage_classifier[i].classifier[j].count; l++ )
632             {
633                 const CvHaarFeature *feature =
634                     &_cascade->stage_classifier[i].classifier[j].haar_feature[l];
635                 GpuHidHaarTreeNode *hidnode = &stage_classifier[i].classifier[j].node[l];
636
637                 for( int k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
638                 {
639                     const CvRect tr = feature->rect[k].r;
640                     if (tr.width == 0)
641                         break;
642                     double correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
643                     hidnode->p[k][0] = tr.x;
644                     hidnode->p[k][1] = tr.y;
645                     hidnode->p[k][2] = tr.width;
646                     hidnode->p[k][3] = tr.height;
647                     hidnode->weight[k] = (float)(feature->rect[k].weight * correction_ratio);
648                 }
649             } /* l */
650         } /* j */
651     }
652 }
653
654 CvSeq *cv::ocl::OclCascadeClassifier::oclHaarDetectObjects( oclMat &gimg, CvMemStorage *storage, double scaleFactor,
655         int minNeighbors, int flags, CvSize minSize, CvSize maxSize)
656 {
657     CvHaarClassifierCascade *cascade = oldCascade;
658
659     const double GROUP_EPS = 0.2;
660     CvSeq *result_seq = 0;
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, CV_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         vector<CvSize> sizev;
726         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         vector<pair<size_t, const void *> > args;
835         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
836         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
837         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
838         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
839         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
840         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
841         args.push_back ( make_pair(sizeof(cl_int) , (void *)&pixelstep ));
842         args.push_back ( make_pair(sizeof(cl_int) , (void *)&loopcount ));
843         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
844         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
845         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
846         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
847         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitnode ));
848         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&p ));
849         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&pq ));
850         args.push_back ( 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_INVALIDATE_REGION, 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                             pWGInfo[WGNum].s[3] = *(int*)&scaleinfo[z].factor;
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_INVALIDATE_REGION, 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 ( make_pair(sizeof(cl_mem) , (void *)&oclNodesPK.datastart ));
943             args.push_back ( make_pair(sizeof(cl_mem) , (void *)&oclWGInfo.datastart ));
944
945             //form build options for kernel
946             string  options = "-D PACKED_CLASSIFIER";
947             options += format(" -D NODE_SIZE=%d",NODE_SIZE);
948             options += format(" -D WND_SIZE_X=%d",cascade->orig_window_size.width);
949             options += format(" -D WND_SIZE_Y=%d",cascade->orig_window_size.height);
950             options += format(" -D STUMP_BASED=%d",gcascade->is_stump_based);
951             options += format(" -D LSx=%d",localThreads[0]);
952             options += format(" -D LSy=%d",localThreads[1]);
953             options += format(" -D SPLITNODE=%d",splitnode);
954             options += format(" -D SPLITSTAGE=%d",splitstage);
955             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         vector<CvSize> sizev;
1002         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 ),
1020                                cvRound( winsize0.height * factor )
1021                              };
1022             if( winSize.width < minSize.width || winSize.height < minSize.height )
1023             {
1024                 continue;
1025             }
1026             sizev.push_back(winSize);
1027             scalev.push_back(factor);
1028         }
1029         int loopcount = scalev.size();
1030         if(loopcount == 0)
1031         {
1032             loopcount = 1;
1033             n_factors = 1;
1034             sizev.push_back(minSize);
1035             scalev.push_back( std::min(cvRound(minSize.width / winsize0.width), cvRound(minSize.height / winsize0.height)) );
1036
1037         }
1038         detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1039         cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * loopcount);
1040         float *correction = (float *)malloc(sizeof(float) * loopcount);
1041         int grp_per_CU = 12;
1042         size_t blocksize = 8;
1043         size_t localThreads[3] = { blocksize, blocksize , 1 };
1044         size_t globalThreads[3] = { grp_per_CU *gsum.clCxt->getDeviceInfo().maxComputeUnits *localThreads[0],
1045                                     localThreads[1], 1 };
1046         int outputsz = 256 * globalThreads[0] / localThreads[0];
1047         int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
1048                        sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
1049         nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY,
1050                                         nodenum * sizeof(GpuHidHaarTreeNode));
1051         openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0,
1052                                             nodenum * sizeof(GpuHidHaarTreeNode),
1053                                             node, 0, NULL, NULL));
1054         cl_mem newnodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_WRITE,
1055                                loopcount * nodenum * sizeof(GpuHidHaarTreeNode));
1056         int startstage = 0;
1057         int endstage = gcascade->count;
1058         for(int i = 0; i < loopcount; i++)
1059         {
1060             sz = sizev[i];
1061             factor = scalev[i];
1062             int ystep = cvRound(std::max(2., factor));
1063             int equRect_x = (int)(factor * gcascade->p0 + 0.5);
1064             int equRect_y = (int)(factor * gcascade->p1 + 0.5);
1065             int equRect_w = (int)(factor * gcascade->p3 + 0.5);
1066             int equRect_h = (int)(factor * gcascade->p2 + 0.5);
1067             p[i].s[0] = equRect_x;
1068             p[i].s[1] = equRect_y;
1069             p[i].s[2] = equRect_x + equRect_w;
1070             p[i].s[3] = equRect_y + equRect_h;
1071             correction[i] = 1. / (equRect_w * equRect_h);
1072             int width = (gsum.cols - 1 - sz.width  + ystep - 1) / ystep;
1073             int height = (gsum.rows - 1 - sz.height + ystep - 1) / ystep;
1074             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1075             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1076
1077             scaleinfo[i].width_height = (width << 16) | height;
1078             scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1079             scaleinfo[i].imgoff = 0;
1080             scaleinfo[i].factor = factor;
1081             int startnodenum = nodenum * i;
1082             float factor2 = (float)factor;
1083
1084             vector<pair<size_t, const void *> > args1;
1085             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
1086             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1087             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&factor2 ));
1088             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&correction[i] ));
1089             args1.push_back ( make_pair(sizeof(cl_int) , (void *)&startnodenum ));
1090
1091             size_t globalThreads2[3] = {nodenum, 1, 1};
1092             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
1093         }
1094
1095         int step = gsum.step / 4;
1096         int startnode = 0;
1097         int splitstage = 3;
1098         stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
1099         openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
1100         candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR, 4 * sizeof(int) * outputsz);
1101         scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
1102         openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
1103         pbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_int4) * loopcount);
1104         openCLSafeCall(clEnqueueWriteBuffer(qu, pbuffer, 1, 0, sizeof(cl_int4)*loopcount, p, 0, NULL, NULL));
1105         correctionbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_float) * loopcount);
1106         openCLSafeCall(clEnqueueWriteBuffer(qu, correctionbuffer, 1, 0, sizeof(cl_float)*loopcount, correction, 0, NULL, NULL));
1107
1108         vector<pair<size_t, const void *> > args;
1109         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
1110         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
1111         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1112         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1113         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1114         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
1115         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1116         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1117         args.push_back ( make_pair(sizeof(cl_int) , (void *)&step ));
1118         args.push_back ( make_pair(sizeof(cl_int) , (void *)&loopcount ));
1119         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1120         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1121         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1122         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1123         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&pbuffer ));
1124         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&correctionbuffer ));
1125         args.push_back ( make_pair(sizeof(cl_int) , (void *)&nodenum ));
1126         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1127         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1128
1129         candidate = (int *)clEnqueueMapBuffer(qu, candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, &status);
1130
1131         for(int i = 0; i < outputsz; i++)
1132         {
1133             if(candidate[4 * i + 2] != 0)
1134                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1], candidate[4 * i + 2], candidate[4 * i + 3]));
1135         }
1136
1137         free(scaleinfo);
1138         free(p);
1139         free(correction);
1140         clEnqueueUnmapMemObject(qu, candidatebuffer, candidate, 0, 0, 0);
1141         openCLSafeCall(clReleaseMemObject(stagebuffer));
1142         openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
1143         openCLSafeCall(clReleaseMemObject(nodebuffer));
1144         openCLSafeCall(clReleaseMemObject(newnodebuffer));
1145         openCLSafeCall(clReleaseMemObject(candidatebuffer));
1146         openCLSafeCall(clReleaseMemObject(pbuffer));
1147         openCLSafeCall(clReleaseMemObject(correctionbuffer));
1148     }
1149
1150     cvFree(&cascade->hid_cascade);
1151     rectList.resize(allCandidates.size());
1152     if(!allCandidates.empty())
1153         std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1154
1155     if( minNeighbors != 0 || findBiggestObject )
1156         groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1157     else
1158         rweights.resize(rectList.size(), 0);
1159
1160     if( findBiggestObject && rectList.size() )
1161     {
1162         CvAvgComp result_comp = {{0, 0, 0, 0}, 0};
1163
1164         for( size_t i = 0; i < rectList.size(); i++ )
1165         {
1166             cv::Rect r = rectList[i];
1167             if( r.area() > cv::Rect(result_comp.rect).area() )
1168             {
1169                 result_comp.rect = r;
1170                 result_comp.neighbors = rweights[i];
1171             }
1172         }
1173         cvSeqPush( result_seq, &result_comp );
1174     }
1175     else
1176     {
1177         for( size_t i = 0; i < rectList.size(); i++ )
1178         {
1179             CvAvgComp c;
1180             c.rect = rectList[i];
1181             c.neighbors = rweights[i];
1182             cvSeqPush( result_seq, &c );
1183         }
1184     }
1185
1186     return result_seq;
1187 }
1188
1189 struct OclBuffers
1190 {
1191     cl_mem stagebuffer;
1192     cl_mem nodebuffer;
1193     cl_mem candidatebuffer;
1194     cl_mem scaleinfobuffer;
1195     cl_mem pbuffer;
1196     cl_mem correctionbuffer;
1197     cl_mem newnodebuffer;
1198 };
1199
1200 struct getRect
1201 {
1202     Rect operator()(const CvAvgComp &e) const
1203     {
1204         return e.rect;
1205     }
1206 };
1207
1208 void cv::ocl::OclCascadeClassifierBuf::detectMultiScale(oclMat &gimg, CV_OUT std::vector<cv::Rect>& faces,
1209                                                         double scaleFactor, int minNeighbors, int flags,
1210                                                         Size minSize, Size maxSize)
1211 {
1212     int blocksize = 8;
1213     int grp_per_CU = 12;
1214     size_t localThreads[3] = { blocksize, blocksize, 1 };
1215     size_t globalThreads[3] = { grp_per_CU * cv::ocl::Context::getContext()->getDeviceInfo().maxComputeUnits *localThreads[0],
1216         localThreads[1],
1217         1 };
1218     int outputsz = 256 * globalThreads[0] / localThreads[0];
1219
1220     Init(gimg.rows, gimg.cols, scaleFactor, flags, outputsz, localThreads, minSize, maxSize);
1221
1222     const double GROUP_EPS = 0.2;
1223
1224     cv::ConcurrentRectVector allCandidates;
1225     std::vector<cv::Rect> rectList;
1226     std::vector<int> rweights;
1227
1228     CvHaarClassifierCascade      *cascade = oldCascade;
1229     GpuHidHaarClassifierCascade  *gcascade;
1230     GpuHidHaarStageClassifier    *stage;
1231
1232     if( CV_MAT_DEPTH(gimg.type()) != CV_8U )
1233         CV_Error( CV_StsUnsupportedFormat, "Only 8-bit images are supported" );
1234
1235     if( CV_MAT_CN(gimg.type()) > 1 )
1236     {
1237         oclMat gtemp;
1238         cvtColor( gimg, gtemp, CV_BGR2GRAY );
1239         gimg = gtemp;
1240     }
1241
1242     int *candidate;
1243     cl_command_queue qu = getClCommandQueue(Context::getContext());
1244     if( (flags & CV_HAAR_SCALE_IMAGE) )
1245     {
1246         int indexy = 0;
1247         CvSize sz;
1248
1249         cv::Rect roi, roi2;
1250         cv::ocl::oclMat resizeroi, gimgroi, gimgroisq;
1251
1252         for( int i = 0; i < m_loopcount; i++ )
1253         {
1254             sz = sizev[i];
1255             roi = Rect(0, indexy, sz.width, sz.height);
1256             roi2 = Rect(0, 0, sz.width - 1, sz.height - 1);
1257             resizeroi = gimg1(roi2);
1258             gimgroi = gsum(roi);
1259             gimgroisq = gsqsum(roi);
1260
1261             cv::ocl::resize(gimg, resizeroi, Size(sz.width - 1, sz.height - 1), 0, 0, INTER_LINEAR);
1262             cv::ocl::integral(resizeroi, gimgroi, gimgroisq);
1263             indexy += sz.height;
1264         }
1265
1266         gcascade   = (GpuHidHaarClassifierCascade *)(cascade->hid_cascade);
1267         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1268
1269         int startstage = 0;
1270         int endstage = gcascade->count;
1271         int startnode = 0;
1272         int pixelstep = gsum.step / 4;
1273         int splitstage = 3;
1274         int splitnode = stage[0].count + stage[1].count + stage[2].count;
1275         cl_int4 p, pq;
1276         p.s[0] = gcascade->p0;
1277         p.s[1] = gcascade->p1;
1278         p.s[2] = gcascade->p2;
1279         p.s[3] = gcascade->p3;
1280         pq.s[0] = gcascade->pq0;
1281         pq.s[1] = gcascade->pq1;
1282         pq.s[2] = gcascade->pq2;
1283         pq.s[3] = gcascade->pq3;
1284         float correction = gcascade->inv_window_area;
1285
1286         vector<pair<size_t, const void *> > args;
1287         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->stagebuffer ));
1288         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->scaleinfobuffer ));
1289         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->nodebuffer ));
1290         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1291         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1292         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->candidatebuffer ));
1293         args.push_back ( make_pair(sizeof(cl_int) , (void *)&pixelstep ));
1294         args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_loopcount ));
1295         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1296         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1297         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1298         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1299         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitnode ));
1300         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&p ));
1301         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&pq ));
1302         args.push_back ( make_pair(sizeof(cl_float) , (void *)&correction ));
1303
1304         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1305
1306         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascade", globalThreads, localThreads, args, -1, -1, build_options);
1307
1308         candidate = (int *)malloc(4 * sizeof(int) * outputsz);
1309         memset(candidate, 0, 4 * sizeof(int) * outputsz);
1310
1311         openCLReadBuffer( gsum.clCxt, ((OclBuffers *)buffers)->candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
1312
1313         for(int i = 0; i < outputsz; i++)
1314         {
1315             if(candidate[4 * i + 2] != 0)
1316             {
1317                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
1318                 candidate[4 * i + 2], candidate[4 * i + 3]));
1319             }
1320         }
1321         free((void *)candidate);
1322         candidate = NULL;
1323     }
1324     else
1325     {
1326         cv::ocl::integral(gimg, gsum, gsqsum);
1327
1328         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1329
1330         int step = gsum.step / 4;
1331         int startnode = 0;
1332         int splitstage = 3;
1333
1334         int startstage = 0;
1335         int endstage = gcascade->count;
1336
1337         vector<pair<size_t, const void *> > args;
1338         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->stagebuffer ));
1339         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->scaleinfobuffer ));
1340         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->newnodebuffer ));
1341         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1342         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1343         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->candidatebuffer ));
1344         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1345         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1346         args.push_back ( make_pair(sizeof(cl_int) , (void *)&step ));
1347         args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_loopcount ));
1348         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1349         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1350         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1351         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1352         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->pbuffer ));
1353         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->correctionbuffer ));
1354         args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_nodenum ));
1355
1356         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1357         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1358
1359         candidate = (int *)clEnqueueMapBuffer(qu, ((OclBuffers *)buffers)->candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, NULL);
1360
1361         for(int i = 0; i < outputsz; i++)
1362         {
1363             if(candidate[4 * i + 2] != 0)
1364                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
1365                 candidate[4 * i + 2], candidate[4 * i + 3]));
1366         }
1367         clEnqueueUnmapMemObject(qu, ((OclBuffers *)buffers)->candidatebuffer, candidate, 0, 0, 0);
1368     }
1369     rectList.resize(allCandidates.size());
1370     if(!allCandidates.empty())
1371         std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1372
1373     if( minNeighbors != 0 || findBiggestObject )
1374         groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1375     else
1376         rweights.resize(rectList.size(), 0);
1377
1378     GenResult(faces, rectList, rweights);
1379 }
1380
1381 void cv::ocl::OclCascadeClassifierBuf::Init(const int rows, const int cols,
1382     double scaleFactor, int flags,
1383     const int outputsz, const size_t localThreads[],
1384     CvSize minSize, CvSize maxSize)
1385 {
1386     if(initialized)
1387     {
1388         return; // we only allow one time initialization
1389     }
1390     CvHaarClassifierCascade      *cascade = oldCascade;
1391
1392     if( !CV_IS_HAAR_CLASSIFIER(cascade) )
1393         CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier cascade" );
1394
1395     if( scaleFactor <= 1 )
1396         CV_Error( CV_StsOutOfRange, "scale factor must be > 1" );
1397
1398     if( cols < minSize.width || rows < minSize.height )
1399         CV_Error(CV_StsError, "Image too small");
1400
1401     int datasize=0;
1402     int totalclassifier=0;
1403
1404     if( !cascade->hid_cascade )
1405     {
1406         gpuCreateHidHaarClassifierCascade(cascade, &datasize, &totalclassifier);
1407     }
1408
1409     if( maxSize.height == 0 || maxSize.width == 0 )
1410     {
1411         maxSize.height = rows;
1412         maxSize.width = cols;
1413     }
1414
1415     findBiggestObject = (flags & CV_HAAR_FIND_BIGGEST_OBJECT) != 0;
1416     if( findBiggestObject )
1417         flags &= ~(CV_HAAR_SCALE_IMAGE | CV_HAAR_DO_CANNY_PRUNING);
1418
1419     CreateBaseBufs(datasize, totalclassifier, flags, outputsz);
1420     CreateFactorRelatedBufs(rows, cols, flags, scaleFactor, localThreads, minSize, maxSize);
1421
1422     m_scaleFactor = scaleFactor;
1423     m_rows = rows;
1424     m_cols = cols;
1425     m_flags = flags;
1426     m_minSize = minSize;
1427     m_maxSize = maxSize;
1428
1429     // initialize nodes
1430     GpuHidHaarClassifierCascade  *gcascade;
1431     GpuHidHaarStageClassifier    *stage;
1432     GpuHidHaarClassifier         *classifier;
1433     GpuHidHaarTreeNode           *node;
1434     cl_command_queue qu = getClCommandQueue(Context::getContext());
1435     if( (flags & CV_HAAR_SCALE_IMAGE) )
1436     {
1437         gcascade   = (GpuHidHaarClassifierCascade *)(cascade->hid_cascade);
1438         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1439         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1440         node       = (GpuHidHaarTreeNode *)(classifier->node);
1441
1442         gpuSetImagesForHaarClassifierCascade( cascade, 1., gsum.step / 4 );
1443
1444         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->stagebuffer, 1, 0,
1445             sizeof(GpuHidHaarStageClassifier) * gcascade->count,
1446             stage, 0, NULL, NULL));
1447
1448         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->nodebuffer, 1, 0,
1449                                             m_nodenum * sizeof(GpuHidHaarTreeNode),
1450                                             node, 0, NULL, NULL));
1451     }
1452     else
1453     {
1454         gpuSetHaarClassifierCascade(cascade);
1455
1456         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1457         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1458         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1459         node       = (GpuHidHaarTreeNode *)(classifier->node);
1460
1461         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->nodebuffer, 1, 0,
1462             m_nodenum * sizeof(GpuHidHaarTreeNode),
1463             node, 0, NULL, NULL));
1464
1465         cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * m_loopcount);
1466         float *correction = (float *)malloc(sizeof(float) * m_loopcount);
1467         double factor;
1468         for(int i = 0; i < m_loopcount; i++)
1469         {
1470             factor = scalev[i];
1471             int equRect_x = (int)(factor * gcascade->p0 + 0.5);
1472             int equRect_y = (int)(factor * gcascade->p1 + 0.5);
1473             int equRect_w = (int)(factor * gcascade->p3 + 0.5);
1474             int equRect_h = (int)(factor * gcascade->p2 + 0.5);
1475             p[i].s[0] = equRect_x;
1476             p[i].s[1] = equRect_y;
1477             p[i].s[2] = equRect_x + equRect_w;
1478             p[i].s[3] = equRect_y + equRect_h;
1479             correction[i] = 1. / (equRect_w * equRect_h);
1480             int startnodenum = m_nodenum * i;
1481             float factor2 = (float)factor;
1482
1483             vector<pair<size_t, const void *> > args1;
1484             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->nodebuffer ));
1485             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->newnodebuffer ));
1486             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&factor2 ));
1487             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&correction[i] ));
1488             args1.push_back ( make_pair(sizeof(cl_int) , (void *)&startnodenum ));
1489
1490             size_t globalThreads2[3] = {m_nodenum, 1, 1};
1491
1492             openCLExecuteKernel(Context::getContext(), &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
1493         }
1494         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
1495         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->pbuffer, 1, 0, sizeof(cl_int4)*m_loopcount, p, 0, NULL, NULL));
1496         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->correctionbuffer, 1, 0, sizeof(cl_float)*m_loopcount, correction, 0, NULL, NULL));
1497
1498         free(p);
1499         free(correction);
1500     }
1501     initialized = true;
1502 }
1503
1504 void cv::ocl::OclCascadeClassifierBuf::CreateBaseBufs(const int datasize, const int totalclassifier,
1505                                                       const int flags, const int outputsz)
1506 {
1507     if (!initialized)
1508     {
1509         buffers = malloc(sizeof(OclBuffers));
1510
1511         size_t tempSize =
1512             sizeof(GpuHidHaarStageClassifier) * ((GpuHidHaarClassifierCascade *)oldCascade->hid_cascade)->count;
1513         m_nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) - tempSize - sizeof(GpuHidHaarClassifier) * totalclassifier)
1514             / sizeof(GpuHidHaarTreeNode);
1515
1516         ((OclBuffers *)buffers)->stagebuffer     = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,  tempSize);
1517         ((OclBuffers *)buffers)->nodebuffer      = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,  m_nodenum * sizeof(GpuHidHaarTreeNode));
1518     }
1519
1520     if (initialized
1521         && ((m_flags & CV_HAAR_SCALE_IMAGE) ^ (flags & CV_HAAR_SCALE_IMAGE)))
1522     {
1523         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->candidatebuffer));
1524     }
1525
1526     if (flags & CV_HAAR_SCALE_IMAGE)
1527     {
1528         ((OclBuffers *)buffers)->candidatebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(),
1529                                                         CL_MEM_WRITE_ONLY,
1530                                                         4 * sizeof(int) * outputsz);
1531     }
1532     else
1533     {
1534         ((OclBuffers *)buffers)->candidatebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(),
1535                                                         CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR,
1536                                                         4 * sizeof(int) * outputsz);
1537     }
1538 }
1539
1540 void cv::ocl::OclCascadeClassifierBuf::CreateFactorRelatedBufs(
1541     const int rows, const int cols, const int flags,
1542     const double scaleFactor, const size_t localThreads[],
1543     CvSize minSize, CvSize maxSize)
1544 {
1545     if (initialized)
1546     {
1547         if ((m_flags & CV_HAAR_SCALE_IMAGE) && !(flags & CV_HAAR_SCALE_IMAGE))
1548         {
1549             gimg1.release();
1550             gsum.release();
1551             gsqsum.release();
1552         }
1553         else if (!(m_flags & CV_HAAR_SCALE_IMAGE) && (flags & CV_HAAR_SCALE_IMAGE))
1554         {
1555             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1556             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1557             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1558         }
1559         else if ((m_flags & CV_HAAR_SCALE_IMAGE) && (flags & CV_HAAR_SCALE_IMAGE))
1560         {
1561             if (fabs(m_scaleFactor - scaleFactor) < 1e-6
1562                 && (rows == m_rows && cols == m_cols)
1563                 && (minSize.width == m_minSize.width)
1564                 && (minSize.height == m_minSize.height)
1565                 && (maxSize.width == m_maxSize.width)
1566                 && (maxSize.height == m_maxSize.height))
1567             {
1568                 return;
1569             }
1570         }
1571         else
1572         {
1573             if (fabs(m_scaleFactor - scaleFactor) < 1e-6
1574                 && (rows == m_rows && cols == m_cols)
1575                 && (minSize.width == m_minSize.width)
1576                 && (minSize.height == m_minSize.height)
1577                 && (maxSize.width == m_maxSize.width)
1578                 && (maxSize.height == m_maxSize.height))
1579             {
1580                 return;
1581             }
1582             else
1583             {
1584                 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1585                 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1586                 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1587             }
1588         }
1589     }
1590
1591     int loopcount;
1592     int indexy = 0;
1593     int totalheight = 0;
1594     double factor;
1595     Rect roi;
1596     CvSize sz;
1597     CvSize winSize0 = oldCascade->orig_window_size;
1598     detect_piramid_info *scaleinfo;
1599     cl_command_queue qu = getClCommandQueue(Context::getContext());
1600     if (flags & CV_HAAR_SCALE_IMAGE)
1601     {
1602         for(factor = 1.f;; factor *= scaleFactor)
1603         {
1604             CvSize winSize = { cvRound(winSize0.width * factor), cvRound(winSize0.height * factor) };
1605             sz.width     = cvRound( cols / factor ) + 1;
1606             sz.height    = cvRound( rows / factor ) + 1;
1607             CvSize sz1     = { sz.width - winSize0.width - 1,      sz.height - winSize0.height - 1 };
1608
1609             if( sz1.width <= 0 || sz1.height <= 0 )
1610                 break;
1611             if( winSize.width > maxSize.width || winSize.height > maxSize.height )
1612                 break;
1613             if( winSize.width < minSize.width || winSize.height < minSize.height )
1614                 continue;
1615
1616             totalheight += sz.height;
1617             sizev.push_back(sz);
1618             scalev.push_back(static_cast<float>(factor));
1619         }
1620
1621         loopcount = sizev.size();
1622         gimg1.create(rows, cols, CV_8UC1);
1623         gsum.create(totalheight + 4, cols + 1, CV_32SC1);
1624         gsqsum.create(totalheight + 4, cols + 1, CV_32FC1);
1625
1626         scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1627         for( int i = 0; i < loopcount; i++ )
1628         {
1629             sz = sizev[i];
1630             roi = Rect(0, indexy, sz.width, sz.height);
1631             int width = sz.width - 1 - oldCascade->orig_window_size.width;
1632             int height = sz.height - 1 - oldCascade->orig_window_size.height;
1633             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1634             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1635
1636             ((detect_piramid_info *)scaleinfo)[i].width_height = (width << 16) | height;
1637             ((detect_piramid_info *)scaleinfo)[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1638             ((detect_piramid_info *)scaleinfo)[i].imgoff = gsum(roi).offset >> 2;
1639             ((detect_piramid_info *)scaleinfo)[i].factor = scalev[i];
1640
1641             indexy += sz.height;
1642         }
1643     }
1644     else
1645     {
1646         for(factor = 1;
1647             cvRound(factor * winSize0.width) < cols - 10 && cvRound(factor * winSize0.height) < rows - 10;
1648             factor *= scaleFactor)
1649         {
1650             CvSize winSize = { cvRound( winSize0.width * factor ), cvRound( winSize0.height * factor ) };
1651             if( winSize.width < minSize.width || winSize.height < minSize.height )
1652             {
1653                 continue;
1654             }
1655             sizev.push_back(winSize);
1656             scalev.push_back(factor);
1657         }
1658
1659         loopcount = scalev.size();
1660         if(loopcount == 0)
1661         {
1662             loopcount = 1;
1663             sizev.push_back(minSize);
1664             scalev.push_back( std::min(cvRound(minSize.width / winSize0.width), cvRound(minSize.height / winSize0.height)) );
1665         }
1666
1667         ((OclBuffers *)buffers)->pbuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,
1668             sizeof(cl_int4) * loopcount);
1669         ((OclBuffers *)buffers)->correctionbuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,
1670             sizeof(cl_float) * loopcount);
1671         ((OclBuffers *)buffers)->newnodebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_WRITE,
1672             loopcount * m_nodenum * sizeof(GpuHidHaarTreeNode));
1673
1674         scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1675         for( int i = 0; i < loopcount; i++ )
1676         {
1677             sz = sizev[i];
1678             factor = scalev[i];
1679             int ystep = cvRound(std::max(2., factor));
1680             int width = (cols - 1 - sz.width  + ystep - 1) / ystep;
1681             int height = (rows - 1 - sz.height + ystep - 1) / ystep;
1682             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1683             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1684
1685             ((detect_piramid_info *)scaleinfo)[i].width_height = (width << 16) | height;
1686             ((detect_piramid_info *)scaleinfo)[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1687             ((detect_piramid_info *)scaleinfo)[i].imgoff = 0;
1688             ((detect_piramid_info *)scaleinfo)[i].factor = factor;
1689         }
1690     }
1691
1692     if (loopcount != m_loopcount)
1693     {
1694         if (initialized)
1695         {
1696             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->scaleinfobuffer));
1697         }
1698         ((OclBuffers *)buffers)->scaleinfobuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
1699     }
1700
1701     openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->scaleinfobuffer, 1, 0,
1702         sizeof(detect_piramid_info)*loopcount,
1703         scaleinfo, 0, NULL, NULL));
1704     free(scaleinfo);
1705
1706     m_loopcount = loopcount;
1707 }
1708
1709 void cv::ocl::OclCascadeClassifierBuf::GenResult(CV_OUT std::vector<cv::Rect>& faces,
1710                                                  const std::vector<cv::Rect> &rectList,
1711                                                  const std::vector<int> &rweights)
1712 {
1713     MemStorage tempStorage(cvCreateMemStorage(0));
1714     CvSeq *result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), tempStorage );
1715
1716     if( findBiggestObject && rectList.size() )
1717     {
1718         CvAvgComp result_comp = {{0, 0, 0, 0}, 0};
1719
1720         for( size_t i = 0; i < rectList.size(); i++ )
1721         {
1722             cv::Rect r = rectList[i];
1723             if( r.area() > cv::Rect(result_comp.rect).area() )
1724             {
1725                 result_comp.rect = r;
1726                 result_comp.neighbors = rweights[i];
1727             }
1728         }
1729         cvSeqPush( result_seq, &result_comp );
1730     }
1731     else
1732     {
1733         for( size_t i = 0; i < rectList.size(); i++ )
1734         {
1735             CvAvgComp c;
1736             c.rect = rectList[i];
1737             c.neighbors = rweights[i];
1738             cvSeqPush( result_seq, &c );
1739         }
1740     }
1741
1742     vector<CvAvgComp> vecAvgComp;
1743     Seq<CvAvgComp>(result_seq).copyTo(vecAvgComp);
1744     faces.resize(vecAvgComp.size());
1745     std::transform(vecAvgComp.begin(), vecAvgComp.end(), faces.begin(), getRect());
1746 }
1747
1748 void cv::ocl::OclCascadeClassifierBuf::release()
1749 {
1750     if(initialized)
1751     {
1752         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->stagebuffer));
1753         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->scaleinfobuffer));
1754         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->nodebuffer));
1755         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->candidatebuffer));
1756
1757         if( (m_flags & CV_HAAR_SCALE_IMAGE) )
1758         {
1759             cvFree(&oldCascade->hid_cascade);
1760         }
1761         else
1762         {
1763             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1764             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1765             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1766         }
1767
1768         free(buffers);
1769         buffers = NULL;
1770         initialized = false;
1771     }
1772 }
1773
1774 #ifndef _MAX_PATH
1775 #define _MAX_PATH 1024
1776 #endif