fix some bug about haar and match_template.
[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 materials 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 sdepth = 0;
758         if(gsqsum.clCxt->supportsFeature(ocl::FEATURE_CL_DOUBLE))
759             sdepth = CV_64FC1;
760         else
761             sdepth = CV_32FC1;
762         sdepth = CV_MAT_DEPTH(sdepth);
763         int type = CV_MAKE_TYPE(sdepth, 1);
764
765         cv::ocl::oclMat gsqsum_t(gsqsum.size(), type);
766         int grp_per_CU = 12;
767
768         size_t blocksize = 8;
769         size_t localThreads[3] = { blocksize, blocksize , 1 };
770         size_t globalThreads[3] = { grp_per_CU *(gsum.clCxt->getDeviceInfo().maxComputeUnits) *localThreads[0],
771                                     localThreads[1], 1
772                                   };
773         int outputsz = 256 * globalThreads[0] / localThreads[0];
774         int loopcount = sizev.size();
775         detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
776
777         for( int i = 0; i < loopcount; i++ )
778         {
779             sz = sizev[i];
780             factor = scalev[i];
781             roi = Rect(0, indexy, sz.width, sz.height);
782             roi2 = Rect(0, 0, sz.width - 1, sz.height - 1);
783             resizeroi = gimg1(roi2);
784             gimgroi = gsum(roi);
785             gimgroisq = gsqsum_t(roi);
786             int width = gimgroi.cols - 1 - cascade->orig_window_size.width;
787             int height = gimgroi.rows - 1 - cascade->orig_window_size.height;
788             scaleinfo[i].width_height = (width << 16) | height;
789
790
791             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
792             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
793
794             scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
795             scaleinfo[i].imgoff = gimgroi.offset >> 2;
796             scaleinfo[i].factor = factor;
797             cv::ocl::resize(gimg, resizeroi, Size(sz.width - 1, sz.height - 1), 0, 0, INTER_LINEAR);
798             cv::ocl::integral(resizeroi, gimgroi, gimgroisq);
799
800             indexy += sz.height;
801         }
802         gsqsum_t.convertTo(gsqsum, CV_32FC1);
803
804         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
805         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
806         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
807         node       = (GpuHidHaarTreeNode *)(classifier->node);
808
809         int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
810                        sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
811
812         candidate = (int *)malloc(4 * sizeof(int) * outputsz);
813
814         gpuSetImagesForHaarClassifierCascade( cascade, 1., gsum.step / 4 );
815
816         stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
817         openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
818
819         nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, nodenum * sizeof(GpuHidHaarTreeNode));
820
821         openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0, nodenum * sizeof(GpuHidHaarTreeNode),
822                                             node, 0, NULL, NULL));
823         candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY, 4 * sizeof(int) * outputsz);
824
825         scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
826         openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
827
828         int startstage = 0;
829         int endstage = gcascade->count;
830         int startnode = 0;
831         int pixelstep = gsum.step / 4;
832         int splitstage = 3;
833         int splitnode = stage[0].count + stage[1].count + stage[2].count;
834         cl_int4 p, pq;
835         p.s[0] = gcascade->p0;
836         p.s[1] = gcascade->p1;
837         p.s[2] = gcascade->p2;
838         p.s[3] = gcascade->p3;
839         pq.s[0] = gcascade->pq0;
840         pq.s[1] = gcascade->pq1;
841         pq.s[2] = gcascade->pq2;
842         pq.s[3] = gcascade->pq3;
843         float correction = gcascade->inv_window_area;
844
845         vector<pair<size_t, const void *> > args;
846         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
847         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
848         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
849         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
850         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
851         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
852         args.push_back ( make_pair(sizeof(cl_int) , (void *)&pixelstep ));
853         args.push_back ( make_pair(sizeof(cl_int) , (void *)&loopcount ));
854         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
855         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
856         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
857         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
858         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitnode ));
859         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&p ));
860         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&pq ));
861         args.push_back ( make_pair(sizeof(cl_float) , (void *)&correction ));
862
863         if(gcascade->is_stump_based && gsum.clCxt->supportsFeature(FEATURE_CL_INTEL_DEVICE))
864         {
865             //setup local group size
866             localThreads[0] = 8;
867             localThreads[1] = 16;
868             localThreads[2] = 1;
869
870             //init maximal number of workgroups
871             int WGNumX = 1+(sizev[0].width /(localThreads[0]));
872             int WGNumY = 1+(sizev[0].height/(localThreads[1]));
873             int WGNumZ = loopcount;
874             int WGNum = 0; //accurate number of non -empty workgroups
875             oclMat      oclWGInfo(1,sizeof(cl_int4) * WGNumX*WGNumY*WGNumZ,CV_8U);
876             {
877                 cl_int4*    pWGInfo = (cl_int4*)clEnqueueMapBuffer(getClCommandQueue(oclWGInfo.clCxt),(cl_mem)oclWGInfo.datastart,true,CL_MAP_WRITE, 0, oclWGInfo.step, 0,0,0,&status);
878                 openCLVerifyCall(status);
879                 for(int z=0;z<WGNumZ;++z)
880                 {
881                     int     Width  = (scaleinfo[z].width_height >> 16)&0xFFFF;
882                     int     Height = (scaleinfo[z].width_height >> 0 )& 0xFFFF;
883                     for(int y=0;y<WGNumY;++y)
884                     {
885                         int     gy = y*localThreads[1];
886                         if(gy>=(Height-cascade->orig_window_size.height))
887                             continue; // no data to process
888                         for(int x=0;x<WGNumX;++x)
889                         {
890                             int     gx = x*localThreads[0];
891                             if(gx>=(Width-cascade->orig_window_size.width))
892                                 continue; // no data to process
893
894                             // save no-empty workgroup info into array
895                             pWGInfo[WGNum].s[0] = scaleinfo[z].width_height;
896                             pWGInfo[WGNum].s[1] = (gx << 16) | gy;
897                             pWGInfo[WGNum].s[2] = scaleinfo[z].imgoff;
898                             memcpy(&(pWGInfo[WGNum].s[3]),&(scaleinfo[z].factor),sizeof(float));
899                             WGNum++;
900                         }
901                     }
902                 }
903                 openCLSafeCall(clEnqueueUnmapMemObject(getClCommandQueue(oclWGInfo.clCxt),(cl_mem)oclWGInfo.datastart,pWGInfo,0,0,0));
904                 pWGInfo = NULL;
905             }
906
907             // setup global sizes to have linear array of workgroups with WGNum size
908             globalThreads[0] = localThreads[0]*WGNum;
909             globalThreads[1] = localThreads[1];
910             globalThreads[2] = 1;
911
912 #define NODE_SIZE 12
913             // pack node info to have less memory loads
914             oclMat  oclNodesPK(1,sizeof(cl_int) * NODE_SIZE * nodenum,CV_8U);
915             {
916                 cl_int  status;
917                 cl_int* pNodesPK = (cl_int*)clEnqueueMapBuffer(getClCommandQueue(oclNodesPK.clCxt),(cl_mem)oclNodesPK.datastart,true,CL_MAP_WRITE, 0, oclNodesPK.step, 0,0,0,&status);
918                 openCLVerifyCall(status);
919                 //use known local data stride to precalulate indexes
920                 int DATA_SIZE_X = (localThreads[0]+cascade->orig_window_size.width);
921                 // check that maximal value is less than maximal unsigned short
922                 assert(DATA_SIZE_X*cascade->orig_window_size.height+cascade->orig_window_size.width < USHRT_MAX);
923                 for(int i = 0;i<nodenum;++i)
924                 {//process each node from classifier
925                     struct NodePK
926                     {
927                         unsigned short  slm_index[3][4];
928                         float           weight[3];
929                         float           threshold;
930                         float           alpha[2];
931                     };
932                     struct NodePK * pOut = (struct NodePK *)(pNodesPK + NODE_SIZE*i);
933                     for(int k=0;k<3;++k)
934                     {// calc 4 short indexes in shared local mem for each rectangle instead of 2 (x,y) pair.
935                         int* p = &(node[i].p[k][0]);
936                         pOut->slm_index[k][0] = (unsigned short)(p[1]*DATA_SIZE_X+p[0]);
937                         pOut->slm_index[k][1] = (unsigned short)(p[1]*DATA_SIZE_X+p[2]);
938                         pOut->slm_index[k][2] = (unsigned short)(p[3]*DATA_SIZE_X+p[0]);
939                         pOut->slm_index[k][3] = (unsigned short)(p[3]*DATA_SIZE_X+p[2]);
940                     }
941                     //store used float point values for each node
942                     pOut->weight[0] = node[i].weight[0];
943                     pOut->weight[1] = node[i].weight[1];
944                     pOut->weight[2] = node[i].weight[2];
945                     pOut->threshold = node[i].threshold;
946                     pOut->alpha[0] = node[i].alpha[0];
947                     pOut->alpha[1] = node[i].alpha[1];
948                 }
949                 openCLSafeCall(clEnqueueUnmapMemObject(getClCommandQueue(oclNodesPK.clCxt),(cl_mem)oclNodesPK.datastart,pNodesPK,0,0,0));
950                 pNodesPK = NULL;
951             }
952             // add 2 additional buffers (WGinfo and packed nodes) as 2 last args
953             args.push_back ( make_pair(sizeof(cl_mem) , (void *)&oclNodesPK.datastart ));
954             args.push_back ( make_pair(sizeof(cl_mem) , (void *)&oclWGInfo.datastart ));
955
956             //form build options for kernel
957             string  options = "-D PACKED_CLASSIFIER";
958             options += format(" -D NODE_SIZE=%d",NODE_SIZE);
959             options += format(" -D WND_SIZE_X=%d",cascade->orig_window_size.width);
960             options += format(" -D WND_SIZE_Y=%d",cascade->orig_window_size.height);
961             options += format(" -D STUMP_BASED=%d",gcascade->is_stump_based);
962             options += format(" -D LSx=%d",localThreads[0]);
963             options += format(" -D LSy=%d",localThreads[1]);
964             options += format(" -D SPLITNODE=%d",splitnode);
965             options += format(" -D SPLITSTAGE=%d",splitstage);
966             options += format(" -D OUTPUTSZ=%d",outputsz);
967
968             // init candiate global count by 0
969             int pattern = 0;
970             openCLSafeCall(clEnqueueWriteBuffer(qu, candidatebuffer, 1, 0, 1 * sizeof(pattern),&pattern, 0, NULL, NULL));
971             // execute face detector
972             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascadePacked", globalThreads, localThreads, args, -1, -1, options.c_str());
973             //read candidate buffer back and put it into host list
974             openCLReadBuffer( gsum.clCxt, candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
975             assert(candidate[0]<outputsz);
976             //printf("candidate[0]=%d\n",candidate[0]);
977             for(int i = 1; i <= candidate[0]; i++)
978             {
979                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],candidate[4 * i + 2], candidate[4 * i + 3]));
980             }
981         }
982         else
983         {
984             const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
985
986             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascade", globalThreads, localThreads, args, -1, -1, build_options);
987
988             openCLReadBuffer( gsum.clCxt, candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
989
990             for(int i = 0; i < outputsz; i++)
991                 if(candidate[4 * i + 2] != 0)
992                     allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
993                     candidate[4 * i + 2], candidate[4 * i + 3]));
994         }
995
996         free(scaleinfo);
997         free(candidate);
998         openCLSafeCall(clReleaseMemObject(stagebuffer));
999         openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
1000         openCLSafeCall(clReleaseMemObject(nodebuffer));
1001         openCLSafeCall(clReleaseMemObject(candidatebuffer));
1002
1003     }
1004     else
1005     {
1006         CvSize winsize0 = cascade->orig_window_size;
1007         int n_factors = 0;
1008         oclMat gsum;
1009         oclMat gsqsum;
1010         cv::ocl::oclMat gsqsum_t;
1011         cv::ocl::integral(gimg, gsum, gsqsum_t);
1012         gsqsum_t.convertTo(gsqsum, CV_32FC1);
1013         CvSize sz;
1014         vector<CvSize> sizev;
1015         vector<float> scalev;
1016         gpuSetHaarClassifierCascade(cascade);
1017         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1018         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1019         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1020         node       = (GpuHidHaarTreeNode *)(classifier->node);
1021         cl_mem stagebuffer;
1022         cl_mem nodebuffer;
1023         cl_mem candidatebuffer;
1024         cl_mem scaleinfobuffer;
1025         cl_mem pbuffer;
1026         cl_mem correctionbuffer;
1027         for( n_factors = 0, factor = 1;
1028                 cvRound(factor * winsize0.width) < gimg.cols - 10 &&
1029                 cvRound(factor * winsize0.height) < gimg.rows - 10;
1030                 n_factors++, factor *= scaleFactor )
1031         {
1032             CvSize winSize = { cvRound( winsize0.width * factor ),
1033                                cvRound( winsize0.height * factor )
1034                              };
1035             if( winSize.width < minSize.width || winSize.height < minSize.height )
1036             {
1037                 continue;
1038             }
1039             sizev.push_back(winSize);
1040             scalev.push_back(factor);
1041         }
1042         int loopcount = scalev.size();
1043         if(loopcount == 0)
1044         {
1045             loopcount = 1;
1046             n_factors = 1;
1047             sizev.push_back(minSize);
1048             scalev.push_back( std::min(cvRound(minSize.width / winsize0.width), cvRound(minSize.height / winsize0.height)) );
1049
1050         }
1051         detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1052         cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * loopcount);
1053         float *correction = (float *)malloc(sizeof(float) * loopcount);
1054         int grp_per_CU = 12;
1055         size_t blocksize = 8;
1056         size_t localThreads[3] = { blocksize, blocksize , 1 };
1057         size_t globalThreads[3] = { grp_per_CU *gsum.clCxt->getDeviceInfo().maxComputeUnits *localThreads[0],
1058                                     localThreads[1], 1 };
1059         int outputsz = 256 * globalThreads[0] / localThreads[0];
1060         int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
1061                        sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
1062         nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY,
1063                                         nodenum * sizeof(GpuHidHaarTreeNode));
1064         openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0,
1065                                             nodenum * sizeof(GpuHidHaarTreeNode),
1066                                             node, 0, NULL, NULL));
1067         cl_mem newnodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_WRITE,
1068                                loopcount * nodenum * sizeof(GpuHidHaarTreeNode));
1069         int startstage = 0;
1070         int endstage = gcascade->count;
1071         for(int i = 0; i < loopcount; i++)
1072         {
1073             sz = sizev[i];
1074             factor = scalev[i];
1075             double ystep = std::max(2., factor);
1076             int equRect_x = cvRound(factor * gcascade->p0);
1077             int equRect_y = cvRound(factor * gcascade->p1);
1078             int equRect_w = cvRound(factor * gcascade->p3);
1079             int equRect_h = cvRound(factor * gcascade->p2);
1080             p[i].s[0] = equRect_x;
1081             p[i].s[1] = equRect_y;
1082             p[i].s[2] = equRect_x + equRect_w;
1083             p[i].s[3] = equRect_y + equRect_h;
1084             correction[i] = 1. / (equRect_w * equRect_h);
1085             int width = (gsum.cols - 1 - sz.width  + ystep - 1) / ystep;
1086             int height = (gsum.rows - 1 - sz.height + ystep - 1) / ystep;
1087             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1088             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1089
1090             scaleinfo[i].width_height = (width << 16) | height;
1091             scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1092             scaleinfo[i].imgoff = 0;
1093             scaleinfo[i].factor = factor;
1094             int startnodenum = nodenum * i;
1095             float factor2 = (float)factor;
1096
1097             vector<pair<size_t, const void *> > args1;
1098             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
1099             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1100             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&factor2 ));
1101             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&correction[i] ));
1102             args1.push_back ( make_pair(sizeof(cl_int) , (void *)&startnodenum ));
1103
1104             size_t globalThreads2[3] = {nodenum, 1, 1};
1105             openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
1106         }
1107
1108         int step = gsum.step / 4;
1109         int startnode = 0;
1110         int splitstage = 3;
1111         stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
1112         openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
1113         candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR, 4 * sizeof(int) * outputsz);
1114         scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
1115         openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
1116         pbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_int4) * loopcount);
1117         openCLSafeCall(clEnqueueWriteBuffer(qu, pbuffer, 1, 0, sizeof(cl_int4)*loopcount, p, 0, NULL, NULL));
1118         correctionbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_float) * loopcount);
1119         openCLSafeCall(clEnqueueWriteBuffer(qu, correctionbuffer, 1, 0, sizeof(cl_float)*loopcount, correction, 0, NULL, NULL));
1120
1121         vector<pair<size_t, const void *> > args;
1122         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
1123         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
1124         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1125         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1126         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1127         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
1128         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1129         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1130         args.push_back ( make_pair(sizeof(cl_int) , (void *)&step ));
1131         args.push_back ( make_pair(sizeof(cl_int) , (void *)&loopcount ));
1132         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1133         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1134         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1135         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1136         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&pbuffer ));
1137         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&correctionbuffer ));
1138         args.push_back ( make_pair(sizeof(cl_int) , (void *)&nodenum ));
1139         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1140         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1141
1142         candidate = (int *)clEnqueueMapBuffer(qu, candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, &status);
1143
1144         for(int i = 0; i < outputsz; i++)
1145         {
1146             if(candidate[4 * i + 2] != 0)
1147                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1], candidate[4 * i + 2], candidate[4 * i + 3]));
1148         }
1149
1150         free(scaleinfo);
1151         free(p);
1152         free(correction);
1153         clEnqueueUnmapMemObject(qu, candidatebuffer, candidate, 0, 0, 0);
1154         openCLSafeCall(clReleaseMemObject(stagebuffer));
1155         openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
1156         openCLSafeCall(clReleaseMemObject(nodebuffer));
1157         openCLSafeCall(clReleaseMemObject(newnodebuffer));
1158         openCLSafeCall(clReleaseMemObject(candidatebuffer));
1159         openCLSafeCall(clReleaseMemObject(pbuffer));
1160         openCLSafeCall(clReleaseMemObject(correctionbuffer));
1161     }
1162
1163     cvFree(&cascade->hid_cascade);
1164     rectList.resize(allCandidates.size());
1165     if(!allCandidates.empty())
1166         std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1167
1168     if( minNeighbors != 0 || findBiggestObject )
1169         groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1170     else
1171         rweights.resize(rectList.size(), 0);
1172
1173     if( findBiggestObject && rectList.size() )
1174     {
1175         CvAvgComp result_comp = {{0, 0, 0, 0}, 0};
1176
1177         for( size_t i = 0; i < rectList.size(); i++ )
1178         {
1179             cv::Rect r = rectList[i];
1180             if( r.area() > cv::Rect(result_comp.rect).area() )
1181             {
1182                 result_comp.rect = r;
1183                 result_comp.neighbors = rweights[i];
1184             }
1185         }
1186         cvSeqPush( result_seq, &result_comp );
1187     }
1188     else
1189     {
1190         for( size_t i = 0; i < rectList.size(); i++ )
1191         {
1192             CvAvgComp c;
1193             c.rect = rectList[i];
1194             c.neighbors = rweights[i];
1195             cvSeqPush( result_seq, &c );
1196         }
1197     }
1198
1199     return result_seq;
1200 }
1201
1202
1203 struct getRect
1204 {
1205     Rect operator()(const CvAvgComp &e) const
1206     {
1207         return e.rect;
1208     }
1209 };
1210
1211 void cv::ocl::OclCascadeClassifier::detectMultiScale(oclMat &gimg, CV_OUT std::vector<cv::Rect>& faces,
1212                                                         double scaleFactor, int minNeighbors, int flags,
1213                                                         Size minSize, Size maxSize)
1214 {
1215     CvSeq* _objects;
1216     MemStorage storage(cvCreateMemStorage(0));
1217     _objects = oclHaarDetectObjects(gimg, storage, scaleFactor, minNeighbors, flags, minSize, maxSize);
1218     vector<CvAvgComp> vecAvgComp;
1219     Seq<CvAvgComp>(_objects).copyTo(vecAvgComp);
1220     faces.resize(vecAvgComp.size());
1221     std::transform(vecAvgComp.begin(), vecAvgComp.end(), faces.begin(), getRect());
1222 }
1223
1224 struct OclBuffers
1225 {
1226     cl_mem stagebuffer;
1227     cl_mem nodebuffer;
1228     cl_mem candidatebuffer;
1229     cl_mem scaleinfobuffer;
1230     cl_mem pbuffer;
1231     cl_mem correctionbuffer;
1232     cl_mem newnodebuffer;
1233 };
1234
1235
1236 void cv::ocl::OclCascadeClassifierBuf::detectMultiScale(oclMat &gimg, CV_OUT std::vector<cv::Rect>& faces,
1237                                                         double scaleFactor, int minNeighbors, int flags,
1238                                                         Size minSize, Size maxSize)
1239 {
1240     int blocksize = 8;
1241     int grp_per_CU = 12;
1242     size_t localThreads[3] = { blocksize, blocksize, 1 };
1243     size_t globalThreads[3] = { grp_per_CU * cv::ocl::Context::getContext()->getDeviceInfo().maxComputeUnits *localThreads[0],
1244         localThreads[1],
1245         1 };
1246     int outputsz = 256 * globalThreads[0] / localThreads[0];
1247
1248     Init(gimg.rows, gimg.cols, scaleFactor, flags, outputsz, localThreads, minSize, maxSize);
1249
1250     const double GROUP_EPS = 0.2;
1251
1252     cv::ConcurrentRectVector allCandidates;
1253     std::vector<cv::Rect> rectList;
1254     std::vector<int> rweights;
1255
1256     CvHaarClassifierCascade      *cascade = oldCascade;
1257     GpuHidHaarClassifierCascade  *gcascade;
1258     GpuHidHaarStageClassifier    *stage;
1259
1260     if( CV_MAT_DEPTH(gimg.type()) != CV_8U )
1261         CV_Error( CV_StsUnsupportedFormat, "Only 8-bit images are supported" );
1262
1263     if( CV_MAT_CN(gimg.type()) > 1 )
1264     {
1265         oclMat gtemp;
1266         cvtColor( gimg, gtemp, CV_BGR2GRAY );
1267         gimg = gtemp;
1268     }
1269
1270     int *candidate;
1271     cl_command_queue qu = getClCommandQueue(Context::getContext());
1272     if( (flags & CV_HAAR_SCALE_IMAGE) )
1273     {
1274         int indexy = 0;
1275         int sdepth = 0;
1276         CvSize sz;
1277
1278         cv::Rect roi, roi2;
1279         cv::ocl::oclMat resizeroi, gimgroi, gimgroisq;
1280         if(gsqsum.clCxt->supportsFeature(ocl::FEATURE_CL_DOUBLE))
1281             sdepth = CV_64FC1;
1282         else
1283             sdepth = CV_32FC1;
1284         sdepth = CV_MAT_DEPTH(sdepth);
1285         int type = CV_MAKE_TYPE(sdepth, 1);
1286
1287         cv::ocl::oclMat gsqsum_t(gsqsum.size(), type);
1288
1289         for( int i = 0; i < m_loopcount; i++ )
1290         {
1291             sz = sizev[i];
1292             roi = Rect(0, indexy, sz.width, sz.height);
1293             roi2 = Rect(0, 0, sz.width - 1, sz.height - 1);
1294             resizeroi = gimg1(roi2);
1295             gimgroi = gsum(roi);
1296             gimgroisq = gsqsum_t(roi);
1297
1298             cv::ocl::resize(gimg, resizeroi, Size(sz.width - 1, sz.height - 1), 0, 0, INTER_LINEAR);
1299             cv::ocl::integral(resizeroi, gimgroi, gimgroisq);
1300             indexy += sz.height;
1301         }
1302         gsqsum_t.convertTo(gsqsum, CV_32FC1);
1303         gcascade   = (GpuHidHaarClassifierCascade *)(cascade->hid_cascade);
1304         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1305
1306         int startstage = 0;
1307         int endstage = gcascade->count;
1308         int startnode = 0;
1309         int pixelstep = gsum.step / 4;
1310         int splitstage = 3;
1311         int splitnode = stage[0].count + stage[1].count + stage[2].count;
1312         cl_int4 p, pq;
1313         p.s[0] = gcascade->p0;
1314         p.s[1] = gcascade->p1;
1315         p.s[2] = gcascade->p2;
1316         p.s[3] = gcascade->p3;
1317         pq.s[0] = gcascade->pq0;
1318         pq.s[1] = gcascade->pq1;
1319         pq.s[2] = gcascade->pq2;
1320         pq.s[3] = gcascade->pq3;
1321         float correction = gcascade->inv_window_area;
1322
1323         vector<pair<size_t, const void *> > args;
1324         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->stagebuffer ));
1325         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->scaleinfobuffer ));
1326         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->nodebuffer ));
1327         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1328         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1329         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->candidatebuffer ));
1330         args.push_back ( make_pair(sizeof(cl_int) , (void *)&pixelstep ));
1331         args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_loopcount ));
1332         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1333         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1334         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1335         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1336         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitnode ));
1337         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&p ));
1338         args.push_back ( make_pair(sizeof(cl_int4) , (void *)&pq ));
1339         args.push_back ( make_pair(sizeof(cl_float) , (void *)&correction ));
1340
1341         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1342
1343         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascade", globalThreads, localThreads, args, -1, -1, build_options);
1344
1345         candidate = (int *)malloc(4 * sizeof(int) * outputsz);
1346         memset(candidate, 0, 4 * sizeof(int) * outputsz);
1347
1348         openCLReadBuffer( gsum.clCxt, ((OclBuffers *)buffers)->candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
1349
1350         for(int i = 0; i < outputsz; i++)
1351         {
1352             if(candidate[4 * i + 2] != 0)
1353             {
1354                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
1355                 candidate[4 * i + 2], candidate[4 * i + 3]));
1356             }
1357         }
1358         free((void *)candidate);
1359         candidate = NULL;
1360     }
1361     else
1362     {
1363         cv::ocl::oclMat gsqsum_t;
1364         cv::ocl::integral(gimg, gsum, gsqsum_t);
1365         gsqsum_t.convertTo(gsqsum, CV_32FC1);
1366
1367         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1368
1369         int step = gsum.step / 4;
1370         int startnode = 0;
1371         int splitstage = 3;
1372
1373         int startstage = 0;
1374         int endstage = gcascade->count;
1375
1376         vector<pair<size_t, const void *> > args;
1377         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->stagebuffer ));
1378         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->scaleinfobuffer ));
1379         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->newnodebuffer ));
1380         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1381         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1382         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->candidatebuffer ));
1383         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1384         args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1385         args.push_back ( make_pair(sizeof(cl_int) , (void *)&step ));
1386         args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_loopcount ));
1387         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1388         args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1389         args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1390         args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1391         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->pbuffer ));
1392         args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->correctionbuffer ));
1393         args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_nodenum ));
1394
1395         const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1396         openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1397
1398         candidate = (int *)clEnqueueMapBuffer(qu, ((OclBuffers *)buffers)->candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, NULL);
1399
1400         for(int i = 0; i < outputsz; i++)
1401         {
1402             if(candidate[4 * i + 2] != 0)
1403                 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
1404                 candidate[4 * i + 2], candidate[4 * i + 3]));
1405         }
1406         clEnqueueUnmapMemObject(qu, ((OclBuffers *)buffers)->candidatebuffer, candidate, 0, 0, 0);
1407     }
1408     rectList.resize(allCandidates.size());
1409     if(!allCandidates.empty())
1410         std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1411
1412     if( minNeighbors != 0 || findBiggestObject )
1413         groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1414     else
1415         rweights.resize(rectList.size(), 0);
1416
1417     GenResult(faces, rectList, rweights);
1418 }
1419
1420 void cv::ocl::OclCascadeClassifierBuf::Init(const int rows, const int cols,
1421     double scaleFactor, int flags,
1422     const int outputsz, const size_t localThreads[],
1423     CvSize minSize, CvSize maxSize)
1424 {
1425     if(initialized)
1426     {
1427         return; // we only allow one time initialization
1428     }
1429     CvHaarClassifierCascade      *cascade = oldCascade;
1430
1431     if( !CV_IS_HAAR_CLASSIFIER(cascade) )
1432         CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier cascade" );
1433
1434     if( scaleFactor <= 1 )
1435         CV_Error( CV_StsOutOfRange, "scale factor must be > 1" );
1436
1437     if( cols < minSize.width || rows < minSize.height )
1438         CV_Error(CV_StsError, "Image too small");
1439
1440     int datasize=0;
1441     int totalclassifier=0;
1442
1443     if( !cascade->hid_cascade )
1444     {
1445         gpuCreateHidHaarClassifierCascade(cascade, &datasize, &totalclassifier);
1446     }
1447
1448     if( maxSize.height == 0 || maxSize.width == 0 )
1449     {
1450         maxSize.height = rows;
1451         maxSize.width = cols;
1452     }
1453
1454     findBiggestObject = (flags & CV_HAAR_FIND_BIGGEST_OBJECT) != 0;
1455     if( findBiggestObject )
1456         flags &= ~(CV_HAAR_SCALE_IMAGE | CV_HAAR_DO_CANNY_PRUNING);
1457
1458     CreateBaseBufs(datasize, totalclassifier, flags, outputsz);
1459     CreateFactorRelatedBufs(rows, cols, flags, scaleFactor, localThreads, minSize, maxSize);
1460
1461     m_scaleFactor = scaleFactor;
1462     m_rows = rows;
1463     m_cols = cols;
1464     m_flags = flags;
1465     m_minSize = minSize;
1466     m_maxSize = maxSize;
1467
1468     // initialize nodes
1469     GpuHidHaarClassifierCascade  *gcascade;
1470     GpuHidHaarStageClassifier    *stage;
1471     GpuHidHaarClassifier         *classifier;
1472     GpuHidHaarTreeNode           *node;
1473     cl_command_queue qu = getClCommandQueue(Context::getContext());
1474     if( (flags & CV_HAAR_SCALE_IMAGE) )
1475     {
1476         gcascade   = (GpuHidHaarClassifierCascade *)(cascade->hid_cascade);
1477         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1478         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1479         node       = (GpuHidHaarTreeNode *)(classifier->node);
1480
1481         gpuSetImagesForHaarClassifierCascade( cascade, 1., gsum.step / 4 );
1482
1483         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->stagebuffer, 1, 0,
1484             sizeof(GpuHidHaarStageClassifier) * gcascade->count,
1485             stage, 0, NULL, NULL));
1486
1487         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->nodebuffer, 1, 0,
1488                                             m_nodenum * sizeof(GpuHidHaarTreeNode),
1489                                             node, 0, NULL, NULL));
1490     }
1491     else
1492     {
1493         gpuSetHaarClassifierCascade(cascade);
1494
1495         gcascade   = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1496         stage      = (GpuHidHaarStageClassifier *)(gcascade + 1);
1497         classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1498         node       = (GpuHidHaarTreeNode *)(classifier->node);
1499
1500         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->nodebuffer, 1, 0,
1501             m_nodenum * sizeof(GpuHidHaarTreeNode),
1502             node, 0, NULL, NULL));
1503
1504         cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * m_loopcount);
1505         float *correction = (float *)malloc(sizeof(float) * m_loopcount);
1506         double factor;
1507         for(int i = 0; i < m_loopcount; i++)
1508         {
1509             factor = scalev[i];
1510             int equRect_x = (int)(factor * gcascade->p0 + 0.5);
1511             int equRect_y = (int)(factor * gcascade->p1 + 0.5);
1512             int equRect_w = (int)(factor * gcascade->p3 + 0.5);
1513             int equRect_h = (int)(factor * gcascade->p2 + 0.5);
1514             p[i].s[0] = equRect_x;
1515             p[i].s[1] = equRect_y;
1516             p[i].s[2] = equRect_x + equRect_w;
1517             p[i].s[3] = equRect_y + equRect_h;
1518             correction[i] = 1. / (equRect_w * equRect_h);
1519             int startnodenum = m_nodenum * i;
1520             float factor2 = (float)factor;
1521
1522             vector<pair<size_t, const void *> > args1;
1523             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->nodebuffer ));
1524             args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->newnodebuffer ));
1525             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&factor2 ));
1526             args1.push_back ( make_pair(sizeof(cl_float) , (void *)&correction[i] ));
1527             args1.push_back ( make_pair(sizeof(cl_int) , (void *)&startnodenum ));
1528
1529             size_t globalThreads2[3] = {m_nodenum, 1, 1};
1530
1531             openCLExecuteKernel(Context::getContext(), &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
1532         }
1533         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
1534         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->pbuffer, 1, 0, sizeof(cl_int4)*m_loopcount, p, 0, NULL, NULL));
1535         openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->correctionbuffer, 1, 0, sizeof(cl_float)*m_loopcount, correction, 0, NULL, NULL));
1536
1537         free(p);
1538         free(correction);
1539     }
1540     initialized = true;
1541 }
1542
1543 void cv::ocl::OclCascadeClassifierBuf::CreateBaseBufs(const int datasize, const int totalclassifier,
1544                                                       const int flags, const int outputsz)
1545 {
1546     if (!initialized)
1547     {
1548         buffers = malloc(sizeof(OclBuffers));
1549
1550         size_t tempSize =
1551             sizeof(GpuHidHaarStageClassifier) * ((GpuHidHaarClassifierCascade *)oldCascade->hid_cascade)->count;
1552         m_nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) - tempSize - sizeof(GpuHidHaarClassifier) * totalclassifier)
1553             / sizeof(GpuHidHaarTreeNode);
1554
1555         ((OclBuffers *)buffers)->stagebuffer     = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,  tempSize);
1556         ((OclBuffers *)buffers)->nodebuffer      = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,  m_nodenum * sizeof(GpuHidHaarTreeNode));
1557     }
1558
1559     if (initialized
1560         && ((m_flags & CV_HAAR_SCALE_IMAGE) ^ (flags & CV_HAAR_SCALE_IMAGE)))
1561     {
1562         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->candidatebuffer));
1563     }
1564
1565     if (flags & CV_HAAR_SCALE_IMAGE)
1566     {
1567         ((OclBuffers *)buffers)->candidatebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(),
1568                                                         CL_MEM_WRITE_ONLY,
1569                                                         4 * sizeof(int) * outputsz);
1570     }
1571     else
1572     {
1573         ((OclBuffers *)buffers)->candidatebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(),
1574                                                         CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR,
1575                                                         4 * sizeof(int) * outputsz);
1576     }
1577 }
1578
1579 void cv::ocl::OclCascadeClassifierBuf::CreateFactorRelatedBufs(
1580     const int rows, const int cols, const int flags,
1581     const double scaleFactor, const size_t localThreads[],
1582     CvSize minSize, CvSize maxSize)
1583 {
1584     if (initialized)
1585     {
1586         if ((m_flags & CV_HAAR_SCALE_IMAGE) && !(flags & CV_HAAR_SCALE_IMAGE))
1587         {
1588             gimg1.release();
1589             gsum.release();
1590             gsqsum.release();
1591         }
1592         else if (!(m_flags & CV_HAAR_SCALE_IMAGE) && (flags & CV_HAAR_SCALE_IMAGE))
1593         {
1594             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1595             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1596             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1597         }
1598         else if ((m_flags & CV_HAAR_SCALE_IMAGE) && (flags & CV_HAAR_SCALE_IMAGE))
1599         {
1600             if (fabs(m_scaleFactor - scaleFactor) < 1e-6
1601                 && (rows == m_rows && cols == m_cols)
1602                 && (minSize.width == m_minSize.width)
1603                 && (minSize.height == m_minSize.height)
1604                 && (maxSize.width == m_maxSize.width)
1605                 && (maxSize.height == m_maxSize.height))
1606             {
1607                 return;
1608             }
1609         }
1610         else
1611         {
1612             if (fabs(m_scaleFactor - scaleFactor) < 1e-6
1613                 && (rows == m_rows && cols == m_cols)
1614                 && (minSize.width == m_minSize.width)
1615                 && (minSize.height == m_minSize.height)
1616                 && (maxSize.width == m_maxSize.width)
1617                 && (maxSize.height == m_maxSize.height))
1618             {
1619                 return;
1620             }
1621             else
1622             {
1623                 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1624                 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1625                 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1626             }
1627         }
1628     }
1629
1630     int loopcount;
1631     int indexy = 0;
1632     int totalheight = 0;
1633     double factor;
1634     Rect roi;
1635     CvSize sz;
1636     CvSize winSize0 = oldCascade->orig_window_size;
1637     detect_piramid_info *scaleinfo;
1638     cl_command_queue qu = getClCommandQueue(Context::getContext());
1639     if (flags & CV_HAAR_SCALE_IMAGE)
1640     {
1641         for(factor = 1.f;; factor *= scaleFactor)
1642         {
1643             CvSize winSize = { cvRound(winSize0.width * factor), cvRound(winSize0.height * factor) };
1644             sz.width     = cvRound( cols / factor ) + 1;
1645             sz.height    = cvRound( rows / factor ) + 1;
1646             CvSize sz1     = { sz.width - winSize0.width - 1,      sz.height - winSize0.height - 1 };
1647
1648             if( sz1.width <= 0 || sz1.height <= 0 )
1649                 break;
1650             if( winSize.width > maxSize.width || winSize.height > maxSize.height )
1651                 break;
1652             if( winSize.width < minSize.width || winSize.height < minSize.height )
1653                 continue;
1654
1655             totalheight += sz.height;
1656             sizev.push_back(sz);
1657             scalev.push_back(static_cast<float>(factor));
1658         }
1659
1660         loopcount = sizev.size();
1661         gimg1.create(rows, cols, CV_8UC1);
1662         gsum.create(totalheight + 4, cols + 1, CV_32SC1);
1663         gsqsum.create(totalheight + 4, cols + 1, CV_32FC1);
1664
1665         scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1666         for( int i = 0; i < loopcount; i++ )
1667         {
1668             sz = sizev[i];
1669             roi = Rect(0, indexy, sz.width, sz.height);
1670             int width = sz.width - 1 - oldCascade->orig_window_size.width;
1671             int height = sz.height - 1 - oldCascade->orig_window_size.height;
1672             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1673             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1674
1675             ((detect_piramid_info *)scaleinfo)[i].width_height = (width << 16) | height;
1676             ((detect_piramid_info *)scaleinfo)[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1677             ((detect_piramid_info *)scaleinfo)[i].imgoff = gsum(roi).offset >> 2;
1678             ((detect_piramid_info *)scaleinfo)[i].factor = scalev[i];
1679
1680             indexy += sz.height;
1681         }
1682     }
1683     else
1684     {
1685         for(factor = 1;
1686             cvRound(factor * winSize0.width) < cols - 10 && cvRound(factor * winSize0.height) < rows - 10;
1687             factor *= scaleFactor)
1688         {
1689             CvSize winSize = { cvRound( winSize0.width * factor ), cvRound( winSize0.height * factor ) };
1690             if( winSize.width < minSize.width || winSize.height < minSize.height )
1691             {
1692                 continue;
1693             }
1694             sizev.push_back(winSize);
1695             scalev.push_back(factor);
1696         }
1697
1698         loopcount = scalev.size();
1699         if(loopcount == 0)
1700         {
1701             loopcount = 1;
1702             sizev.push_back(minSize);
1703             scalev.push_back( std::min(cvRound(minSize.width / winSize0.width), cvRound(minSize.height / winSize0.height)) );
1704         }
1705
1706         ((OclBuffers *)buffers)->pbuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,
1707             sizeof(cl_int4) * loopcount);
1708         ((OclBuffers *)buffers)->correctionbuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,
1709             sizeof(cl_float) * loopcount);
1710         ((OclBuffers *)buffers)->newnodebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_WRITE,
1711             loopcount * m_nodenum * sizeof(GpuHidHaarTreeNode));
1712
1713         scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1714         for( int i = 0; i < loopcount; i++ )
1715         {
1716             sz = sizev[i];
1717             factor = scalev[i];
1718             double ystep = cv::max(2.,factor);
1719             int width = cvRound((cols - 1 - sz.width  + ystep - 1) / ystep);
1720             int height = cvRound((rows - 1 - sz.height + ystep - 1) / ystep);
1721             int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1722             int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1723
1724             ((detect_piramid_info *)scaleinfo)[i].width_height = (width << 16) | height;
1725             ((detect_piramid_info *)scaleinfo)[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1726             ((detect_piramid_info *)scaleinfo)[i].imgoff = 0;
1727             ((detect_piramid_info *)scaleinfo)[i].factor = factor;
1728         }
1729     }
1730
1731     if (loopcount != m_loopcount)
1732     {
1733         if (initialized)
1734         {
1735             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->scaleinfobuffer));
1736         }
1737         ((OclBuffers *)buffers)->scaleinfobuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
1738     }
1739
1740     openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->scaleinfobuffer, 1, 0,
1741         sizeof(detect_piramid_info)*loopcount,
1742         scaleinfo, 0, NULL, NULL));
1743     free(scaleinfo);
1744
1745     m_loopcount = loopcount;
1746 }
1747
1748 void cv::ocl::OclCascadeClassifierBuf::GenResult(CV_OUT std::vector<cv::Rect>& faces,
1749                                                  const std::vector<cv::Rect> &rectList,
1750                                                  const std::vector<int> &rweights)
1751 {
1752     MemStorage tempStorage(cvCreateMemStorage(0));
1753     CvSeq *result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), tempStorage );
1754
1755     if( findBiggestObject && rectList.size() )
1756     {
1757         CvAvgComp result_comp = {{0, 0, 0, 0}, 0};
1758
1759         for( size_t i = 0; i < rectList.size(); i++ )
1760         {
1761             cv::Rect r = rectList[i];
1762             if( r.area() > cv::Rect(result_comp.rect).area() )
1763             {
1764                 result_comp.rect = r;
1765                 result_comp.neighbors = rweights[i];
1766             }
1767         }
1768         cvSeqPush( result_seq, &result_comp );
1769     }
1770     else
1771     {
1772         for( size_t i = 0; i < rectList.size(); i++ )
1773         {
1774             CvAvgComp c;
1775             c.rect = rectList[i];
1776             c.neighbors = rweights[i];
1777             cvSeqPush( result_seq, &c );
1778         }
1779     }
1780
1781     vector<CvAvgComp> vecAvgComp;
1782     Seq<CvAvgComp>(result_seq).copyTo(vecAvgComp);
1783     faces.resize(vecAvgComp.size());
1784     std::transform(vecAvgComp.begin(), vecAvgComp.end(), faces.begin(), getRect());
1785 }
1786
1787 void cv::ocl::OclCascadeClassifierBuf::release()
1788 {
1789     if(initialized)
1790     {
1791         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->stagebuffer));
1792         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->scaleinfobuffer));
1793         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->nodebuffer));
1794         openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->candidatebuffer));
1795
1796         if( (m_flags & CV_HAAR_SCALE_IMAGE) )
1797         {
1798             cvFree(&oldCascade->hid_cascade);
1799         }
1800         else
1801         {
1802             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1803             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1804             openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1805         }
1806
1807         free(buffers);
1808         buffers = NULL;
1809         initialized = false;
1810     }
1811 }
1812
1813 #ifndef _MAX_PATH
1814 #define _MAX_PATH 1024
1815 #endif