1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
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.
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
25 // Redistribution and use in source and binary forms, with or without modification,
26 // are permitted provided that the following conditions are met:
28 // * Redistribution's of source code must retain the above copyright notice,
29 // this list of conditions and the following disclaimer.
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.
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.
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.
51 #include "precomp.hpp"
52 #include "opencl_kernels.hpp"
55 using namespace cv::ocl;
57 /* these settings affect the quality of detection: change with care */
58 #define CV_ADJUST_FEATURES 1
59 #define CV_ADJUST_WEIGHTS 0
62 typedef double sqsumtype;
64 typedef struct CvHidHaarFeature
68 sumtype *p0, *p1, *p2, *p3;
71 rect[CV_HAAR_FEATURE_MAX];
76 typedef struct CvHidHaarTreeNode
78 CvHidHaarFeature feature;
86 typedef struct CvHidHaarClassifier
89 //CvHaarFeature* orig_feature;
90 CvHidHaarTreeNode *node;
96 typedef struct CvHidHaarStageClassifier
100 CvHidHaarClassifier *classifier;
103 struct CvHidHaarStageClassifier *next;
104 struct CvHidHaarStageClassifier *child;
105 struct CvHidHaarStageClassifier *parent;
107 CvHidHaarStageClassifier;
110 struct CvHidHaarClassifierCascade
114 int has_tilted_features;
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;
127 int grpnumperline_totalgrp;
130 } detect_piramid_info;
132 #define _ALIGNED_ON(_ALIGNMENT) __declspec(align(_ALIGNMENT))
134 typedef _ALIGNED_ON(128) struct GpuHidHaarTreeNode
136 _ALIGNED_ON(64) int p[CV_HAAR_FEATURE_MAX][4];
137 float weight[CV_HAAR_FEATURE_MAX] ;
139 _ALIGNED_ON(16) float alpha[3] ;
140 _ALIGNED_ON(4) int left ;
141 _ALIGNED_ON(4) int right ;
146 typedef _ALIGNED_ON(32) struct GpuHidHaarClassifier
148 _ALIGNED_ON(4) int count;
149 _ALIGNED_ON(8) GpuHidHaarTreeNode *node ;
150 _ALIGNED_ON(8) float *alpha ;
152 GpuHidHaarClassifier;
155 typedef _ALIGNED_ON(64) struct GpuHidHaarStageClassifier
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 ;
165 GpuHidHaarStageClassifier;
168 typedef _ALIGNED_ON(64) struct GpuHidHaarClassifierCascade
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;
185 #define _ALIGNED_ON(_ALIGNMENT) __attribute__((aligned(_ALIGNMENT) ))
187 typedef struct _ALIGNED_ON(128) GpuHidHaarTreeNode
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);
198 typedef struct _ALIGNED_ON(32) GpuHidHaarClassifier
200 int count _ALIGNED_ON(4);
201 GpuHidHaarTreeNode *node _ALIGNED_ON(8);
202 float *alpha _ALIGNED_ON(8);
204 GpuHidHaarClassifier;
207 typedef struct _ALIGNED_ON(64) GpuHidHaarStageClassifier
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);
217 GpuHidHaarStageClassifier;
220 typedef struct _ALIGNED_ON(64) GpuHidHaarClassifierCascade
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;
238 const int icv_object_win_border = 1;
239 const float icv_stage_threshold_bias = 0.0001f;
240 double globaltime = 0;
242 /* create more efficient internal representation of haar classifier cascade */
243 static GpuHidHaarClassifierCascade * gpuCreateHidHaarClassifierCascade( CvHaarClassifierCascade *cascade, int *size, int *totalclassifier)
245 GpuHidHaarClassifierCascade *out = 0;
249 int total_classifiers = 0;
253 GpuHidHaarStageClassifier *stage_classifier_ptr;
254 GpuHidHaarClassifier *haar_classifier_ptr;
255 GpuHidHaarTreeNode *haar_node_ptr;
257 CvSize orig_window_size;
258 int has_tilted_features = 0;
260 if( !CV_IS_HAAR_CLASSIFIER(cascade) )
261 CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
263 if( cascade->hid_cascade )
264 CV_Error( CV_StsError, "hid_cascade has been already created" );
266 if( !cascade->stage_classifier )
267 CV_Error( CV_StsNullPtr, "" );
269 if( cascade->count <= 0 )
270 CV_Error( CV_StsOutOfRange, "Negative number of cascade stages" );
272 orig_window_size = cascade->orig_window_size;
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++ )
278 CvHaarStageClassifier *stage_classifier = cascade->stage_classifier + i;
280 if( !stage_classifier->classifier ||
281 stage_classifier->count <= 0 )
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 );
288 total_classifiers += stage_classifier->count;
290 for( j = 0; j < stage_classifier->count; j++ )
292 CvHaarClassifier *classifier = stage_classifier->classifier + j;
294 total_nodes += classifier->count;
295 for( l = 0; l < classifier->count; l++ )
297 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
299 if( classifier->haar_feature[l].rect[k].r.width )
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
308 (r.x < 0 || r.y + r.height > orig_window_size.height))
310 (tilted && (r.x - r.height < 0 ||
311 r.y + r.width + r.height > orig_window_size.height)))
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 );
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;
330 *totalclassifier = total_classifiers;
332 out = (GpuHidHaarClassifierCascade *)cvAlloc( datasize );
333 memset( out, 0, sizeof(*out) );
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);
341 out->is_stump_based = 1;
342 out->has_tilted_features = has_tilted_features;
345 /* initialize internal representation */
346 for( i = 0; i < cascade->count; i++ )
348 CvHaarStageClassifier *stage_classifier = cascade->stage_classifier + i;
349 GpuHidHaarStageClassifier *hid_stage_classifier = stage_classifier_ptr + i;
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;
357 for( j = 0; j < stage_classifier->count; j++ )
359 CvHaarClassifier *classifier = stage_classifier->classifier + j;
360 GpuHidHaarClassifier *hid_classifier = hid_stage_classifier->classifier + j;
361 int node_count = classifier->count;
363 float *alpha_ptr = &haar_node_ptr->alpha[0];
365 hid_classifier->count = node_count;
366 hid_classifier->node = haar_node_ptr;
367 hid_classifier->alpha = alpha_ptr;
369 for( l = 0; l < node_count; l++ )
371 GpuHidHaarTreeNode *node = hid_classifier->node + l;
372 CvHaarFeature *feature = classifier->haar_feature + l;
374 memset( node, -1, sizeof(*node) );
375 node->threshold = classifier->threshold[l];
376 node->left = classifier->left[l];
377 node->right = classifier->right[l];
379 if( fabs(feature->rect[2].weight) < DBL_EPSILON ||
380 feature->rect[2].r.width == 0 ||
381 feature->rect[2].r.height == 0 )
390 hid_stage_classifier->two_rects = 0;
392 memcpy( node->alpha, classifier->alpha, (node_count + 1)*sizeof(alpha_ptr[0]));
393 haar_node_ptr = haar_node_ptr + 1;
395 out->is_stump_based &= node_count == 1;
399 cascade->hid_cascade = (CvHidHaarClassifierCascade *)out;
400 assert( (char *)haar_node_ptr - (char *)out <= datasize );
406 #define sum_elem_ptr(sum,row,col) \
407 ((sumtype*)CV_MAT_ELEM_PTR_FAST((sum),(row),(col),sizeof(sumtype)))
409 #define sqsum_elem_ptr(sqsum,row,col) \
410 ((sqsumtype*)CV_MAT_ELEM_PTR_FAST((sqsum),(row),(col),sizeof(sqsumtype)))
412 #define calc_sum(rect,offset) \
413 ((rect).p0[offset] - (rect).p1[offset] - (rect).p2[offset] + (rect).p3[offset])
416 static void gpuSetImagesForHaarClassifierCascade( CvHaarClassifierCascade *_cascade,
420 GpuHidHaarClassifierCascade *cascade;
421 int coi0 = 0, coi1 = 0;
427 GpuHidHaarStageClassifier *stage_classifier;
429 if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
430 CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
433 CV_Error( CV_StsOutOfRange, "Scale must be positive" );
436 CV_Error( CV_BadCOI, "COI is not supported" );
438 if( !_cascade->hid_cascade )
439 gpuCreateHidHaarClassifierCascade(_cascade, &datasize, &total);
441 cascade = (GpuHidHaarClassifierCascade *) _cascade->hid_cascade;
442 stage_classifier = (GpuHidHaarStageClassifier *) (cascade + 1);
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 );
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;
454 cascade->pq0 = equRect.x;
455 cascade->pq1 = equRect.y;
456 cascade->pq2 = equRect.x + equRect.width;
457 cascade->pq3 = equRect.y + equRect.height;
459 cascade->p0 = equRect.x;
460 cascade->p1 = equRect.y;
461 cascade->p2 = equRect.x + equRect.width;
462 cascade->p3 = equRect.y + equRect.height;
465 /* init pointers in haar features according to real window size and
466 given image pointers */
467 for( i = 0; i < _cascade->count; i++ )
470 for( j = 0; j < stage_classifier[i].count; j++ )
472 for( l = 0; l < stage_classifier[i].classifier[j].count; l++ )
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;
480 int base_w = -1, base_h = -1;
481 int new_base_w = 0, new_base_h = 0;
483 int flagx = 0, flagy = 0;
488 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
490 if(!hidnode->p[k][0])
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) );
504 kx = r[0].width / base_w;
507 ky = r[0].height / base_h;
512 new_base_w = cvRound( r[0].width * scale ) / kx;
513 x0 = cvRound( r[0].x * scale );
519 new_base_h = cvRound( r[0].height * scale ) / ky;
520 y0 = cvRound( r[0].y * scale );
523 for( k = 0; k < nr; k++ )
526 double correction_ratio;
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;
535 tr.x = cvRound( r[k].x * scale );
536 tr.width = cvRound( r[k].width * scale );
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;
546 tr.y = cvRound( r[k].y * scale );
547 tr.height = cvRound( r[k].height * scale );
550 #if CV_ADJUST_WEIGHTS
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;
564 correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
567 if( !feature->tilted )
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;
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;
581 hidnode->weight[k] = (float)(feature->rect[k].weight * correction_ratio);
583 area0 = tr.width * tr.height;
585 sum0 += hidnode->weight[k] * tr.width * tr.height;
587 hidnode->weight[0] = (float)(-sum0 / area0);
593 static void gpuSetHaarClassifierCascade( CvHaarClassifierCascade *_cascade)
595 GpuHidHaarClassifierCascade *cascade;
601 GpuHidHaarStageClassifier *stage_classifier;
603 if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
604 CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
606 if( !_cascade->hid_cascade )
607 gpuCreateHidHaarClassifierCascade(_cascade, &datasize, &total);
609 cascade = (GpuHidHaarClassifierCascade *) _cascade->hid_cascade;
610 stage_classifier = (GpuHidHaarStageClassifier *) cascade + 1;
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;
616 equRect.x = equRect.y = 1;
617 equRect.width = _cascade->orig_window_size.width - 2;
618 equRect.height = _cascade->orig_window_size.height - 2;
620 cascade->inv_window_area = weight_scale;
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++ )
629 for( j = 0; j < stage_classifier[i].count; j++ )
631 for( l = 0; l < stage_classifier[i].classifier[j].count; l++ )
633 CvHaarFeature *feature =
634 &_cascade->stage_classifier[i].classifier[j].haar_feature[l];
635 GpuHidHaarTreeNode *hidnode = &stage_classifier[i].classifier[j].node[l];
642 for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
644 if(!hidnode->p[k][0])
646 r[k] = feature->rect[k].r;
650 for( k = 0; k < nr; k++ )
653 double correction_ratio;
655 tr.width = r[k].width;
657 tr.height = r[k].height;
658 correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
659 hidnode->p[k][0] = tr.x;
660 hidnode->p[k][1] = tr.y;
661 hidnode->p[k][2] = tr.width;
662 hidnode->p[k][3] = tr.height;
663 hidnode->weight[k] = (float)(feature->rect[k].weight * correction_ratio);
670 CvSeq *cv::ocl::OclCascadeClassifier::oclHaarDetectObjects( oclMat &gimg, CvMemStorage *storage, double scaleFactor,
671 int minNeighbors, int flags, CvSize minSize, CvSize maxSize)
673 CvHaarClassifierCascade *cascade = oldCascade;
675 const double GROUP_EPS = 0.2;
676 CvSeq *result_seq = 0;
678 cv::ConcurrentRectVector allCandidates;
679 std::vector<cv::Rect> rectList;
680 std::vector<int> rweights;
683 int totalclassifier=0;
685 GpuHidHaarClassifierCascade *gcascade;
686 GpuHidHaarStageClassifier *stage;
687 GpuHidHaarClassifier *classifier;
688 GpuHidHaarTreeNode *node;
693 bool findBiggestObject = (flags & CV_HAAR_FIND_BIGGEST_OBJECT) != 0;
695 if( maxSize.height == 0 || maxSize.width == 0 )
697 maxSize.height = gimg.rows;
698 maxSize.width = gimg.cols;
701 if( !CV_IS_HAAR_CLASSIFIER(cascade) )
702 CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier cascade" );
705 CV_Error( CV_StsNullPtr, "Null storage pointer" );
707 if( CV_MAT_DEPTH(gimg.type()) != CV_8U )
708 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit images are supported" );
710 if( scaleFactor <= 1 )
711 CV_Error( CV_StsOutOfRange, "scale factor must be > 1" );
713 if( findBiggestObject )
714 flags &= ~CV_HAAR_SCALE_IMAGE;
716 if( !cascade->hid_cascade )
717 gpuCreateHidHaarClassifierCascade(cascade, &datasize, &totalclassifier);
719 result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), storage );
721 if( CV_MAT_CN(gimg.type()) > 1 )
724 cvtColor( gimg, gtemp, CV_BGR2GRAY );
728 if( findBiggestObject )
729 flags &= ~(CV_HAAR_SCALE_IMAGE | CV_HAAR_DO_CANNY_PRUNING);
731 if( gimg.cols < minSize.width || gimg.rows < minSize.height )
732 CV_Error(CV_StsError, "Image too small");
734 cl_command_queue qu = getClCommandQueue(Context::getContext());
735 if( (flags & CV_HAAR_SCALE_IMAGE) )
737 CvSize winSize0 = cascade->orig_window_size;
741 vector<CvSize> sizev;
742 vector<float> scalev;
743 for(factor = 1.f;; factor *= scaleFactor)
745 CvSize winSize = { cvRound(winSize0.width * factor), cvRound(winSize0.height * factor) };
746 sz.width = cvRound( gimg.cols / factor ) + 1;
747 sz.height = cvRound( gimg.rows / factor ) + 1;
748 CvSize sz1 = { sz.width - winSize0.width - 1, sz.height - winSize0.height - 1 };
750 if( sz1.width <= 0 || sz1.height <= 0 )
752 if( winSize.width > maxSize.width || winSize.height > maxSize.height )
754 if( winSize.width < minSize.width || winSize.height < minSize.height )
757 totalheight += sz.height;
759 scalev.push_back(factor);
762 oclMat gimg1(gimg.rows, gimg.cols, CV_8UC1);
763 oclMat gsum(totalheight + 4, gimg.cols + 1, CV_32SC1);
764 oclMat gsqsum(totalheight + 4, gimg.cols + 1, CV_32FC1);
768 cl_mem candidatebuffer;
769 cl_mem scaleinfobuffer;
771 cv::Mat imgroi, imgroisq;
772 cv::ocl::oclMat resizeroi, gimgroi, gimgroisq;
775 size_t blocksize = 8;
776 size_t localThreads[3] = { blocksize, blocksize , 1 };
777 size_t globalThreads[3] = { grp_per_CU *(gsum.clCxt->getDeviceInfo().maxComputeUnits) *localThreads[0],
780 int outputsz = 256 * globalThreads[0] / localThreads[0];
781 int loopcount = sizev.size();
782 detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
784 for( int i = 0; i < loopcount; i++ )
788 roi = Rect(0, indexy, sz.width, sz.height);
789 roi2 = Rect(0, 0, sz.width - 1, sz.height - 1);
790 resizeroi = gimg1(roi2);
792 gimgroisq = gsqsum(roi);
793 int width = gimgroi.cols - 1 - cascade->orig_window_size.width;
794 int height = gimgroi.rows - 1 - cascade->orig_window_size.height;
795 scaleinfo[i].width_height = (width << 16) | height;
798 int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
799 int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
801 scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
802 scaleinfo[i].imgoff = gimgroi.offset >> 2;
803 scaleinfo[i].factor = factor;
804 cv::ocl::resize(gimg, resizeroi, Size(sz.width - 1, sz.height - 1), 0, 0, INTER_LINEAR);
805 cv::ocl::integral(resizeroi, gimgroi, gimgroisq);
809 gcascade = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
810 stage = (GpuHidHaarStageClassifier *)(gcascade + 1);
811 classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
812 node = (GpuHidHaarTreeNode *)(classifier->node);
814 int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
815 sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
817 candidate = (int *)malloc(4 * sizeof(int) * outputsz);
819 gpuSetImagesForHaarClassifierCascade( cascade, 1., gsum.step / 4 );
821 stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
822 openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
824 nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, nodenum * sizeof(GpuHidHaarTreeNode));
826 openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0, nodenum * sizeof(GpuHidHaarTreeNode),
827 node, 0, NULL, NULL));
828 candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY, 4 * sizeof(int) * outputsz);
830 scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
831 openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
834 int endstage = gcascade->count;
836 int pixelstep = gsum.step / 4;
838 int splitnode = stage[0].count + stage[1].count + stage[2].count;
840 p.s[0] = gcascade->p0;
841 p.s[1] = gcascade->p1;
842 p.s[2] = gcascade->p2;
843 p.s[3] = gcascade->p3;
844 pq.s[0] = gcascade->pq0;
845 pq.s[1] = gcascade->pq1;
846 pq.s[2] = gcascade->pq2;
847 pq.s[3] = gcascade->pq3;
848 float correction = gcascade->inv_window_area;
850 vector<pair<size_t, const void *> > args;
851 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
852 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
853 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
854 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
855 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
856 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
857 args.push_back ( make_pair(sizeof(cl_int) , (void *)&pixelstep ));
858 args.push_back ( make_pair(sizeof(cl_int) , (void *)&loopcount ));
859 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
860 args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
861 args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
862 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
863 args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitnode ));
864 args.push_back ( make_pair(sizeof(cl_int4) , (void *)&p ));
865 args.push_back ( make_pair(sizeof(cl_int4) , (void *)&pq ));
866 args.push_back ( make_pair(sizeof(cl_float) , (void *)&correction ));
868 const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
870 openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascade", globalThreads, localThreads, args, -1, -1, build_options);
872 openCLReadBuffer( gsum.clCxt, candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
874 for(int i = 0; i < outputsz; i++)
875 if(candidate[4 * i + 2] != 0)
876 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
877 candidate[4 * i + 2], candidate[4 * i + 3]));
881 openCLSafeCall(clReleaseMemObject(stagebuffer));
882 openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
883 openCLSafeCall(clReleaseMemObject(nodebuffer));
884 openCLSafeCall(clReleaseMemObject(candidatebuffer));
889 CvSize winsize0 = cascade->orig_window_size;
893 cv::ocl::integral(gimg, gsum, gsqsum);
895 vector<CvSize> sizev;
896 vector<float> scalev;
897 gpuSetHaarClassifierCascade(cascade);
898 gcascade = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
899 stage = (GpuHidHaarStageClassifier *)(gcascade + 1);
900 classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
901 node = (GpuHidHaarTreeNode *)(classifier->node);
904 cl_mem candidatebuffer;
905 cl_mem scaleinfobuffer;
907 cl_mem correctionbuffer;
908 for( n_factors = 0, factor = 1;
909 cvRound(factor * winsize0.width) < gimg.cols - 10 &&
910 cvRound(factor * winsize0.height) < gimg.rows - 10;
911 n_factors++, factor *= scaleFactor )
913 CvSize winSize = { cvRound( winsize0.width * factor ),
914 cvRound( winsize0.height * factor )
916 if( winSize.width < minSize.width || winSize.height < minSize.height )
920 sizev.push_back(winSize);
921 scalev.push_back(factor);
923 int loopcount = scalev.size();
928 sizev.push_back(minSize);
929 scalev.push_back( min(cvRound(minSize.width / winsize0.width), cvRound(minSize.height / winsize0.height)) );
932 detect_piramid_info *scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
933 cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * loopcount);
934 float *correction = (float *)malloc(sizeof(float) * loopcount);
936 size_t blocksize = 8;
937 size_t localThreads[3] = { blocksize, blocksize , 1 };
938 size_t globalThreads[3] = { grp_per_CU *gsum.clCxt->getDeviceInfo().maxComputeUnits *localThreads[0],
939 localThreads[1], 1 };
940 int outputsz = 256 * globalThreads[0] / localThreads[0];
941 int nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) -
942 sizeof(GpuHidHaarStageClassifier) * gcascade->count - sizeof(GpuHidHaarClassifier) * totalclassifier) / sizeof(GpuHidHaarTreeNode);
943 nodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY,
944 nodenum * sizeof(GpuHidHaarTreeNode));
945 openCLSafeCall(clEnqueueWriteBuffer(qu, nodebuffer, 1, 0,
946 nodenum * sizeof(GpuHidHaarTreeNode),
947 node, 0, NULL, NULL));
948 cl_mem newnodebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_WRITE,
949 loopcount * nodenum * sizeof(GpuHidHaarTreeNode));
951 int endstage = gcascade->count;
952 for(int i = 0; i < loopcount; i++)
956 int ystep = cvRound(std::max(2., factor));
957 int equRect_x = (int)(factor * gcascade->p0 + 0.5);
958 int equRect_y = (int)(factor * gcascade->p1 + 0.5);
959 int equRect_w = (int)(factor * gcascade->p3 + 0.5);
960 int equRect_h = (int)(factor * gcascade->p2 + 0.5);
961 p[i].s[0] = equRect_x;
962 p[i].s[1] = equRect_y;
963 p[i].s[2] = equRect_x + equRect_w;
964 p[i].s[3] = equRect_y + equRect_h;
965 correction[i] = 1. / (equRect_w * equRect_h);
966 int width = (gsum.cols - 1 - sz.width + ystep - 1) / ystep;
967 int height = (gsum.rows - 1 - sz.height + ystep - 1) / ystep;
968 int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
969 int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
971 scaleinfo[i].width_height = (width << 16) | height;
972 scaleinfo[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
973 scaleinfo[i].imgoff = 0;
974 scaleinfo[i].factor = factor;
975 int startnodenum = nodenum * i;
976 float factor2 = (float)factor;
978 vector<pair<size_t, const void *> > args1;
979 args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&nodebuffer ));
980 args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
981 args1.push_back ( make_pair(sizeof(cl_float) , (void *)&factor2 ));
982 args1.push_back ( make_pair(sizeof(cl_float) , (void *)&correction[i] ));
983 args1.push_back ( make_pair(sizeof(cl_int) , (void *)&startnodenum ));
985 size_t globalThreads2[3] = {nodenum, 1, 1};
986 openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
989 int step = gsum.step / 4;
992 stagebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(GpuHidHaarStageClassifier) * gcascade->count);
993 openCLSafeCall(clEnqueueWriteBuffer(qu, stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
994 candidatebuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR, 4 * sizeof(int) * outputsz);
995 scaleinfobuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
996 openCLSafeCall(clEnqueueWriteBuffer(qu, scaleinfobuffer, 1, 0, sizeof(detect_piramid_info)*loopcount, scaleinfo, 0, NULL, NULL));
997 pbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_int4) * loopcount);
998 openCLSafeCall(clEnqueueWriteBuffer(qu, pbuffer, 1, 0, sizeof(cl_int4)*loopcount, p, 0, NULL, NULL));
999 correctionbuffer = openCLCreateBuffer(gsum.clCxt, CL_MEM_READ_ONLY, sizeof(cl_float) * loopcount);
1000 openCLSafeCall(clEnqueueWriteBuffer(qu, correctionbuffer, 1, 0, sizeof(cl_float)*loopcount, correction, 0, NULL, NULL));
1002 vector<pair<size_t, const void *> > args;
1003 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&stagebuffer ));
1004 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&scaleinfobuffer ));
1005 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&newnodebuffer ));
1006 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1007 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1008 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&candidatebuffer ));
1009 args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1010 args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1011 args.push_back ( make_pair(sizeof(cl_int) , (void *)&step ));
1012 args.push_back ( make_pair(sizeof(cl_int) , (void *)&loopcount ));
1013 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1014 args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1015 args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1016 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1017 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&pbuffer ));
1018 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&correctionbuffer ));
1019 args.push_back ( make_pair(sizeof(cl_int) , (void *)&nodenum ));
1020 const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1021 openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1023 candidate = (int *)clEnqueueMapBuffer(qu, candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, &status);
1025 for(int i = 0; i < outputsz; i++)
1027 if(candidate[4 * i + 2] != 0)
1028 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1], candidate[4 * i + 2], candidate[4 * i + 3]));
1034 clEnqueueUnmapMemObject(qu, candidatebuffer, candidate, 0, 0, 0);
1035 openCLSafeCall(clReleaseMemObject(stagebuffer));
1036 openCLSafeCall(clReleaseMemObject(scaleinfobuffer));
1037 openCLSafeCall(clReleaseMemObject(nodebuffer));
1038 openCLSafeCall(clReleaseMemObject(newnodebuffer));
1039 openCLSafeCall(clReleaseMemObject(candidatebuffer));
1040 openCLSafeCall(clReleaseMemObject(pbuffer));
1041 openCLSafeCall(clReleaseMemObject(correctionbuffer));
1044 cvFree(&cascade->hid_cascade);
1045 rectList.resize(allCandidates.size());
1046 if(!allCandidates.empty())
1047 std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1049 if( minNeighbors != 0 || findBiggestObject )
1050 groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1052 rweights.resize(rectList.size(), 0);
1054 if( findBiggestObject && rectList.size() )
1056 CvAvgComp result_comp = {{0, 0, 0, 0}, 0};
1058 for( size_t i = 0; i < rectList.size(); i++ )
1060 cv::Rect r = rectList[i];
1061 if( r.area() > cv::Rect(result_comp.rect).area() )
1063 result_comp.rect = r;
1064 result_comp.neighbors = rweights[i];
1067 cvSeqPush( result_seq, &result_comp );
1071 for( size_t i = 0; i < rectList.size(); i++ )
1074 c.rect = rectList[i];
1075 c.neighbors = rweights[i];
1076 cvSeqPush( result_seq, &c );
1087 cl_mem candidatebuffer;
1088 cl_mem scaleinfobuffer;
1090 cl_mem correctionbuffer;
1091 cl_mem newnodebuffer;
1096 Rect operator()(const CvAvgComp &e) const
1102 void cv::ocl::OclCascadeClassifierBuf::detectMultiScale(oclMat &gimg, CV_OUT std::vector<cv::Rect>& faces,
1103 double scaleFactor, int minNeighbors, int flags,
1104 Size minSize, Size maxSize)
1107 int grp_per_CU = 12;
1108 size_t localThreads[3] = { blocksize, blocksize, 1 };
1109 size_t globalThreads[3] = { grp_per_CU * cv::ocl::Context::getContext()->getDeviceInfo().maxComputeUnits *localThreads[0],
1112 int outputsz = 256 * globalThreads[0] / localThreads[0];
1114 Init(gimg.rows, gimg.cols, scaleFactor, flags, outputsz, localThreads, minSize, maxSize);
1116 const double GROUP_EPS = 0.2;
1118 cv::ConcurrentRectVector allCandidates;
1119 std::vector<cv::Rect> rectList;
1120 std::vector<int> rweights;
1122 CvHaarClassifierCascade *cascade = oldCascade;
1123 GpuHidHaarClassifierCascade *gcascade;
1124 GpuHidHaarStageClassifier *stage;
1126 if( CV_MAT_DEPTH(gimg.type()) != CV_8U )
1127 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit images are supported" );
1129 if( CV_MAT_CN(gimg.type()) > 1 )
1132 cvtColor( gimg, gtemp, CV_BGR2GRAY );
1137 cl_command_queue qu = getClCommandQueue(Context::getContext());
1138 if( (flags & CV_HAAR_SCALE_IMAGE) )
1144 cv::ocl::oclMat resizeroi, gimgroi, gimgroisq;
1146 for( int i = 0; i < m_loopcount; i++ )
1149 roi = Rect(0, indexy, sz.width, sz.height);
1150 roi2 = Rect(0, 0, sz.width - 1, sz.height - 1);
1151 resizeroi = gimg1(roi2);
1152 gimgroi = gsum(roi);
1153 gimgroisq = gsqsum(roi);
1155 cv::ocl::resize(gimg, resizeroi, Size(sz.width - 1, sz.height - 1), 0, 0, INTER_LINEAR);
1156 cv::ocl::integral(resizeroi, gimgroi, gimgroisq);
1157 indexy += sz.height;
1160 gcascade = (GpuHidHaarClassifierCascade *)(cascade->hid_cascade);
1161 stage = (GpuHidHaarStageClassifier *)(gcascade + 1);
1164 int endstage = gcascade->count;
1166 int pixelstep = gsum.step / 4;
1168 int splitnode = stage[0].count + stage[1].count + stage[2].count;
1170 p.s[0] = gcascade->p0;
1171 p.s[1] = gcascade->p1;
1172 p.s[2] = gcascade->p2;
1173 p.s[3] = gcascade->p3;
1174 pq.s[0] = gcascade->pq0;
1175 pq.s[1] = gcascade->pq1;
1176 pq.s[2] = gcascade->pq2;
1177 pq.s[3] = gcascade->pq3;
1178 float correction = gcascade->inv_window_area;
1180 vector<pair<size_t, const void *> > args;
1181 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->stagebuffer ));
1182 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->scaleinfobuffer ));
1183 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->nodebuffer ));
1184 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1185 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1186 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->candidatebuffer ));
1187 args.push_back ( make_pair(sizeof(cl_int) , (void *)&pixelstep ));
1188 args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_loopcount ));
1189 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1190 args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1191 args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1192 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1193 args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitnode ));
1194 args.push_back ( make_pair(sizeof(cl_int4) , (void *)&p ));
1195 args.push_back ( make_pair(sizeof(cl_int4) , (void *)&pq ));
1196 args.push_back ( make_pair(sizeof(cl_float) , (void *)&correction ));
1198 const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1200 openCLExecuteKernel(gsum.clCxt, &haarobjectdetect, "gpuRunHaarClassifierCascade", globalThreads, localThreads, args, -1, -1, build_options);
1202 candidate = (int *)malloc(4 * sizeof(int) * outputsz);
1203 memset(candidate, 0, 4 * sizeof(int) * outputsz);
1205 openCLReadBuffer( gsum.clCxt, ((OclBuffers *)buffers)->candidatebuffer, candidate, 4 * sizeof(int)*outputsz );
1207 for(int i = 0; i < outputsz; i++)
1209 if(candidate[4 * i + 2] != 0)
1211 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
1212 candidate[4 * i + 2], candidate[4 * i + 3]));
1215 free((void *)candidate);
1220 cv::ocl::integral(gimg, gsum, gsqsum);
1222 gcascade = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1224 int step = gsum.step / 4;
1229 int endstage = gcascade->count;
1231 vector<pair<size_t, const void *> > args;
1232 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->stagebuffer ));
1233 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->scaleinfobuffer ));
1234 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->newnodebuffer ));
1235 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsum.data ));
1236 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&gsqsum.data ));
1237 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->candidatebuffer ));
1238 args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.rows ));
1239 args.push_back ( make_pair(sizeof(cl_int) , (void *)&gsum.cols ));
1240 args.push_back ( make_pair(sizeof(cl_int) , (void *)&step ));
1241 args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_loopcount ));
1242 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startstage ));
1243 args.push_back ( make_pair(sizeof(cl_int) , (void *)&splitstage ));
1244 args.push_back ( make_pair(sizeof(cl_int) , (void *)&endstage ));
1245 args.push_back ( make_pair(sizeof(cl_int) , (void *)&startnode ));
1246 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->pbuffer ));
1247 args.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->correctionbuffer ));
1248 args.push_back ( make_pair(sizeof(cl_int) , (void *)&m_nodenum ));
1250 const char * build_options = gcascade->is_stump_based ? "-D STUMP_BASED=1" : "-D STUMP_BASED=0";
1251 openCLExecuteKernel(gsum.clCxt, &haarobjectdetect_scaled2, "gpuRunHaarClassifierCascade_scaled2", globalThreads, localThreads, args, -1, -1, build_options);
1253 candidate = (int *)clEnqueueMapBuffer(qu, ((OclBuffers *)buffers)->candidatebuffer, 1, CL_MAP_READ, 0, 4 * sizeof(int) * outputsz, 0, 0, 0, NULL);
1255 for(int i = 0; i < outputsz; i++)
1257 if(candidate[4 * i + 2] != 0)
1258 allCandidates.push_back(Rect(candidate[4 * i], candidate[4 * i + 1],
1259 candidate[4 * i + 2], candidate[4 * i + 3]));
1261 clEnqueueUnmapMemObject(qu, ((OclBuffers *)buffers)->candidatebuffer, candidate, 0, 0, 0);
1263 rectList.resize(allCandidates.size());
1264 if(!allCandidates.empty())
1265 std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
1267 if( minNeighbors != 0 || findBiggestObject )
1268 groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
1270 rweights.resize(rectList.size(), 0);
1272 GenResult(faces, rectList, rweights);
1275 void cv::ocl::OclCascadeClassifierBuf::Init(const int rows, const int cols,
1276 double scaleFactor, int flags,
1277 const int outputsz, const size_t localThreads[],
1278 CvSize minSize, CvSize maxSize)
1282 return; // we only allow one time initialization
1284 CvHaarClassifierCascade *cascade = oldCascade;
1286 if( !CV_IS_HAAR_CLASSIFIER(cascade) )
1287 CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier cascade" );
1289 if( scaleFactor <= 1 )
1290 CV_Error( CV_StsOutOfRange, "scale factor must be > 1" );
1292 if( cols < minSize.width || rows < minSize.height )
1293 CV_Error(CV_StsError, "Image too small");
1296 int totalclassifier=0;
1298 if( !cascade->hid_cascade )
1300 gpuCreateHidHaarClassifierCascade(cascade, &datasize, &totalclassifier);
1303 if( maxSize.height == 0 || maxSize.width == 0 )
1305 maxSize.height = rows;
1306 maxSize.width = cols;
1309 findBiggestObject = (flags & CV_HAAR_FIND_BIGGEST_OBJECT) != 0;
1310 if( findBiggestObject )
1311 flags &= ~(CV_HAAR_SCALE_IMAGE | CV_HAAR_DO_CANNY_PRUNING);
1313 CreateBaseBufs(datasize, totalclassifier, flags, outputsz);
1314 CreateFactorRelatedBufs(rows, cols, flags, scaleFactor, localThreads, minSize, maxSize);
1316 m_scaleFactor = scaleFactor;
1320 m_minSize = minSize;
1321 m_maxSize = maxSize;
1324 GpuHidHaarClassifierCascade *gcascade;
1325 GpuHidHaarStageClassifier *stage;
1326 GpuHidHaarClassifier *classifier;
1327 GpuHidHaarTreeNode *node;
1328 cl_command_queue qu = getClCommandQueue(Context::getContext());
1329 if( (flags & CV_HAAR_SCALE_IMAGE) )
1331 gcascade = (GpuHidHaarClassifierCascade *)(cascade->hid_cascade);
1332 stage = (GpuHidHaarStageClassifier *)(gcascade + 1);
1333 classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1334 node = (GpuHidHaarTreeNode *)(classifier->node);
1336 gpuSetImagesForHaarClassifierCascade( cascade, 1., gsum.step / 4 );
1338 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->stagebuffer, 1, 0,
1339 sizeof(GpuHidHaarStageClassifier) * gcascade->count,
1340 stage, 0, NULL, NULL));
1342 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->nodebuffer, 1, 0,
1343 m_nodenum * sizeof(GpuHidHaarTreeNode),
1344 node, 0, NULL, NULL));
1348 gpuSetHaarClassifierCascade(cascade);
1350 gcascade = (GpuHidHaarClassifierCascade *)cascade->hid_cascade;
1351 stage = (GpuHidHaarStageClassifier *)(gcascade + 1);
1352 classifier = (GpuHidHaarClassifier *)(stage + gcascade->count);
1353 node = (GpuHidHaarTreeNode *)(classifier->node);
1355 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->nodebuffer, 1, 0,
1356 m_nodenum * sizeof(GpuHidHaarTreeNode),
1357 node, 0, NULL, NULL));
1359 cl_int4 *p = (cl_int4 *)malloc(sizeof(cl_int4) * m_loopcount);
1360 float *correction = (float *)malloc(sizeof(float) * m_loopcount);
1362 for(int i = 0; i < m_loopcount; i++)
1365 int equRect_x = (int)(factor * gcascade->p0 + 0.5);
1366 int equRect_y = (int)(factor * gcascade->p1 + 0.5);
1367 int equRect_w = (int)(factor * gcascade->p3 + 0.5);
1368 int equRect_h = (int)(factor * gcascade->p2 + 0.5);
1369 p[i].s[0] = equRect_x;
1370 p[i].s[1] = equRect_y;
1371 p[i].s[2] = equRect_x + equRect_w;
1372 p[i].s[3] = equRect_y + equRect_h;
1373 correction[i] = 1. / (equRect_w * equRect_h);
1374 int startnodenum = m_nodenum * i;
1375 float factor2 = (float)factor;
1377 vector<pair<size_t, const void *> > args1;
1378 args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->nodebuffer ));
1379 args1.push_back ( make_pair(sizeof(cl_mem) , (void *)&((OclBuffers *)buffers)->newnodebuffer ));
1380 args1.push_back ( make_pair(sizeof(cl_float) , (void *)&factor2 ));
1381 args1.push_back ( make_pair(sizeof(cl_float) , (void *)&correction[i] ));
1382 args1.push_back ( make_pair(sizeof(cl_int) , (void *)&startnodenum ));
1384 size_t globalThreads2[3] = {m_nodenum, 1, 1};
1386 openCLExecuteKernel(Context::getContext(), &haarobjectdetect_scaled2, "gpuscaleclassifier", globalThreads2, NULL/*localThreads2*/, args1, -1, -1);
1388 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->stagebuffer, 1, 0, sizeof(GpuHidHaarStageClassifier)*gcascade->count, stage, 0, NULL, NULL));
1389 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->pbuffer, 1, 0, sizeof(cl_int4)*m_loopcount, p, 0, NULL, NULL));
1390 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->correctionbuffer, 1, 0, sizeof(cl_float)*m_loopcount, correction, 0, NULL, NULL));
1398 void cv::ocl::OclCascadeClassifierBuf::CreateBaseBufs(const int datasize, const int totalclassifier,
1399 const int flags, const int outputsz)
1403 buffers = malloc(sizeof(OclBuffers));
1406 sizeof(GpuHidHaarStageClassifier) * ((GpuHidHaarClassifierCascade *)oldCascade->hid_cascade)->count;
1407 m_nodenum = (datasize - sizeof(GpuHidHaarClassifierCascade) - tempSize - sizeof(GpuHidHaarClassifier) * totalclassifier)
1408 / sizeof(GpuHidHaarTreeNode);
1410 ((OclBuffers *)buffers)->stagebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY, tempSize);
1411 ((OclBuffers *)buffers)->nodebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY, m_nodenum * sizeof(GpuHidHaarTreeNode));
1415 && ((m_flags & CV_HAAR_SCALE_IMAGE) ^ (flags & CV_HAAR_SCALE_IMAGE)))
1417 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->candidatebuffer));
1420 if (flags & CV_HAAR_SCALE_IMAGE)
1422 ((OclBuffers *)buffers)->candidatebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(),
1424 4 * sizeof(int) * outputsz);
1428 ((OclBuffers *)buffers)->candidatebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(),
1429 CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR,
1430 4 * sizeof(int) * outputsz);
1434 void cv::ocl::OclCascadeClassifierBuf::CreateFactorRelatedBufs(
1435 const int rows, const int cols, const int flags,
1436 const double scaleFactor, const size_t localThreads[],
1437 CvSize minSize, CvSize maxSize)
1441 if ((m_flags & CV_HAAR_SCALE_IMAGE) && !(flags & CV_HAAR_SCALE_IMAGE))
1447 else if (!(m_flags & CV_HAAR_SCALE_IMAGE) && (flags & CV_HAAR_SCALE_IMAGE))
1449 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1450 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1451 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1453 else if ((m_flags & CV_HAAR_SCALE_IMAGE) && (flags & CV_HAAR_SCALE_IMAGE))
1455 if (fabs(m_scaleFactor - scaleFactor) < 1e-6
1456 && (rows == m_rows && cols == m_cols)
1457 && (minSize.width == m_minSize.width)
1458 && (minSize.height == m_minSize.height)
1459 && (maxSize.width == m_maxSize.width)
1460 && (maxSize.height == m_maxSize.height))
1467 if (fabs(m_scaleFactor - scaleFactor) < 1e-6
1468 && (rows == m_rows && cols == m_cols)
1469 && (minSize.width == m_minSize.width)
1470 && (minSize.height == m_minSize.height)
1471 && (maxSize.width == m_maxSize.width)
1472 && (maxSize.height == m_maxSize.height))
1478 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1479 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1480 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1487 int totalheight = 0;
1491 CvSize winSize0 = oldCascade->orig_window_size;
1492 detect_piramid_info *scaleinfo;
1493 cl_command_queue qu = getClCommandQueue(Context::getContext());
1494 if (flags & CV_HAAR_SCALE_IMAGE)
1496 for(factor = 1.f;; factor *= scaleFactor)
1498 CvSize winSize = { cvRound(winSize0.width * factor), cvRound(winSize0.height * factor) };
1499 sz.width = cvRound( cols / factor ) + 1;
1500 sz.height = cvRound( rows / factor ) + 1;
1501 CvSize sz1 = { sz.width - winSize0.width - 1, sz.height - winSize0.height - 1 };
1503 if( sz1.width <= 0 || sz1.height <= 0 )
1505 if( winSize.width > maxSize.width || winSize.height > maxSize.height )
1507 if( winSize.width < minSize.width || winSize.height < minSize.height )
1510 totalheight += sz.height;
1511 sizev.push_back(sz);
1512 scalev.push_back(static_cast<float>(factor));
1515 loopcount = sizev.size();
1516 gimg1.create(rows, cols, CV_8UC1);
1517 gsum.create(totalheight + 4, cols + 1, CV_32SC1);
1518 gsqsum.create(totalheight + 4, cols + 1, CV_32FC1);
1520 scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1521 for( int i = 0; i < loopcount; i++ )
1524 roi = Rect(0, indexy, sz.width, sz.height);
1525 int width = sz.width - 1 - oldCascade->orig_window_size.width;
1526 int height = sz.height - 1 - oldCascade->orig_window_size.height;
1527 int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1528 int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1530 ((detect_piramid_info *)scaleinfo)[i].width_height = (width << 16) | height;
1531 ((detect_piramid_info *)scaleinfo)[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1532 ((detect_piramid_info *)scaleinfo)[i].imgoff = gsum(roi).offset >> 2;
1533 ((detect_piramid_info *)scaleinfo)[i].factor = scalev[i];
1535 indexy += sz.height;
1541 cvRound(factor * winSize0.width) < cols - 10 && cvRound(factor * winSize0.height) < rows - 10;
1542 factor *= scaleFactor)
1544 CvSize winSize = { cvRound( winSize0.width * factor ), cvRound( winSize0.height * factor ) };
1545 if( winSize.width < minSize.width || winSize.height < minSize.height )
1549 sizev.push_back(winSize);
1550 scalev.push_back(factor);
1553 loopcount = scalev.size();
1557 sizev.push_back(minSize);
1558 scalev.push_back( min(cvRound(minSize.width / winSize0.width), cvRound(minSize.height / winSize0.height)) );
1561 ((OclBuffers *)buffers)->pbuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,
1562 sizeof(cl_int4) * loopcount);
1563 ((OclBuffers *)buffers)->correctionbuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY,
1564 sizeof(cl_float) * loopcount);
1565 ((OclBuffers *)buffers)->newnodebuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_WRITE,
1566 loopcount * m_nodenum * sizeof(GpuHidHaarTreeNode));
1568 scaleinfo = (detect_piramid_info *)malloc(sizeof(detect_piramid_info) * loopcount);
1569 for( int i = 0; i < loopcount; i++ )
1573 int ystep = cvRound(std::max(2., factor));
1574 int width = (cols - 1 - sz.width + ystep - 1) / ystep;
1575 int height = (rows - 1 - sz.height + ystep - 1) / ystep;
1576 int grpnumperline = (width + localThreads[0] - 1) / localThreads[0];
1577 int totalgrp = ((height + localThreads[1] - 1) / localThreads[1]) * grpnumperline;
1579 ((detect_piramid_info *)scaleinfo)[i].width_height = (width << 16) | height;
1580 ((detect_piramid_info *)scaleinfo)[i].grpnumperline_totalgrp = (grpnumperline << 16) | totalgrp;
1581 ((detect_piramid_info *)scaleinfo)[i].imgoff = 0;
1582 ((detect_piramid_info *)scaleinfo)[i].factor = factor;
1586 if (loopcount != m_loopcount)
1590 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->scaleinfobuffer));
1592 ((OclBuffers *)buffers)->scaleinfobuffer = openCLCreateBuffer(cv::ocl::Context::getContext(), CL_MEM_READ_ONLY, sizeof(detect_piramid_info) * loopcount);
1595 openCLSafeCall(clEnqueueWriteBuffer(qu, ((OclBuffers *)buffers)->scaleinfobuffer, 1, 0,
1596 sizeof(detect_piramid_info)*loopcount,
1597 scaleinfo, 0, NULL, NULL));
1600 m_loopcount = loopcount;
1603 void cv::ocl::OclCascadeClassifierBuf::GenResult(CV_OUT std::vector<cv::Rect>& faces,
1604 const std::vector<cv::Rect> &rectList,
1605 const std::vector<int> &rweights)
1607 MemStorage tempStorage(cvCreateMemStorage(0));
1608 CvSeq *result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), tempStorage );
1610 if( findBiggestObject && rectList.size() )
1612 CvAvgComp result_comp = {{0, 0, 0, 0}, 0};
1614 for( size_t i = 0; i < rectList.size(); i++ )
1616 cv::Rect r = rectList[i];
1617 if( r.area() > cv::Rect(result_comp.rect).area() )
1619 result_comp.rect = r;
1620 result_comp.neighbors = rweights[i];
1623 cvSeqPush( result_seq, &result_comp );
1627 for( size_t i = 0; i < rectList.size(); i++ )
1630 c.rect = rectList[i];
1631 c.neighbors = rweights[i];
1632 cvSeqPush( result_seq, &c );
1636 vector<CvAvgComp> vecAvgComp;
1637 Seq<CvAvgComp>(result_seq).copyTo(vecAvgComp);
1638 faces.resize(vecAvgComp.size());
1639 std::transform(vecAvgComp.begin(), vecAvgComp.end(), faces.begin(), getRect());
1642 void cv::ocl::OclCascadeClassifierBuf::release()
1646 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->stagebuffer));
1647 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->scaleinfobuffer));
1648 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->nodebuffer));
1649 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->candidatebuffer));
1651 if( (m_flags & CV_HAAR_SCALE_IMAGE) )
1653 cvFree(&oldCascade->hid_cascade);
1657 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->newnodebuffer));
1658 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->correctionbuffer));
1659 openCLSafeCall(clReleaseMemObject(((OclBuffers *)buffers)->pbuffer));
1664 initialized = false;
1669 #define _MAX_PATH 1024