iCub-main
Loading...
Searching...
No Matches
particleFilter.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2009 RobotCub Consortium, European Commission FP6 Project IST-004370
3 * Authors: Vadim Tikhanoff, Carlo Ciliberto
4 *
5 * Algorithm taken from R. Hess, A. Fern, "Discriminatively trained particle filters for complex multi-object tracking," cvpr, pp.240-247, 2009 IEEE Conference on Computer Vision and Pattern Recognition, 2009
6 *
7 * email: vadim.tikhanoff@iit.it
8 * website: www.robotcub.org
9 * Permission is granted to copy, distribute, and/or modify this program
10 * under the terms of the GNU General Public License, version 2 or any
11 * later version published by the Free Software Foundation.
12 *
13 * A copy of the license can be found at
14 * http://www.robotcub.org/icub/license/gpl.txt
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 * Public License for more details
20 */
21
22#include <utility>
23#include <opencv2/imgproc.hpp>
24#include <yarp/cv/Cv.h>
25#include <iCub/particleFilter.h>
26
27using namespace std;
28using namespace yarp::os;
29using namespace yarp::sig;
30using namespace yarp::cv;
31
32/**********************************************************/
33int particle_cmp( const void* p1, const void* p2 )
34{
37
38 if( _p1->w > _p2->w )
39 return -1;
40 if( _p1->w < _p2->w )
41 return 1;
42 return 0;
43}
44/**********************************************************/
45
47{
48 cout << "deleting dynamic objects" << endl;
49 if(regions!=NULL)
50 free_regions ( regions, num_objects );
51
52 gsl_rng_free ( rng );
53 free_histos ( ref_histos, num_objects);
54 if(particles != NULL)
55 free ( particles);
56
57 if (temp)
58 {
59 cout << "releasing temp" << endl;
60 cvReleaseImage(&temp);
61 }
62 cout << "finished particle thread" << endl;
63}
64/**********************************************************/
66{
67 firstFrame = true;
68 num_objects = 0;
69 regions = (CvRect **) malloc(sizeof(CvRect*));
70 num_particles = PARTICLES; /* number of particles */
71 rng = gsl_rng_alloc( gsl_rng_mt19937 );
72 gsl_rng_set( rng, (unsigned long)time(NULL) );
73 i = 0;
74 getTemplate = false;
75 gotTemplate = false;
76 sendTarget = false;
77 getImage = false;
78 particles = NULL;
79 new_particles = NULL;
80 temp = NULL;
81 ref_histos = NULL;
82 tpl = NULL;
83 total = 0;
84}
85/**********************************************************/
86void PARTICLEThread::setName(string module)
87{
88 this->moduleName = module;
89}
90
91/**********************************************************/
93{
94 /* initialize variables and create data-structures if needed */
95
96 inputPortName = "/" + moduleName + "/image:i";
97 imageIn.open( inputPortName.c_str() );
98
99 outputPortName = "/" + moduleName + "/image:o";
100 imageOut.open( outputPortName.c_str() );
101
102 outputPortNameBlob = "/" + moduleName + "/blob/image:o";
103 imageOutBlob.open( outputPortNameBlob.c_str() );
104
105 num_objects = 0;
106 init = true;
107
108 updateNeeded=false;
109 bestTempl.templ=NULL;
110 bestTempl.w=0.0;
111 return true;
112}
113/**********************************************************/
115{
116 while (isStopping() != true) { // the thread continues to run until isStopping() returns true
117
118 getImage = ( imageIn.getInputCount() > 0 );
119
120 if ( !getImage )
121 Time::delay(0.1);
122 else{
123
124 if (init)
125 {//Get first RGB image to establish width, height:
126 cout << "initializing" << endl;
127 initAll();
128 }
129 else
130 {
131 iCubImage = imageIn.read();
132 lock_guard<mutex> lck(templateMutex);
133 imageIn.getEnvelope(targetTemp);
134 }
135
136 frame = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U, 3 );
137 cv::cvtColor(toCvMat(*iCubImage), cv::cvarrToMat(frame), cv::COLOR_RGB2BGR);
138 frame_blob = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U, 1 );
139
140 if ( tpl != NULL )
141 {
142 cv::Mat tplMat=toCvMat(*tpl);
143 tpl_width = tpl->width();
144 tpl_height = tpl->height();
145 res_width = width - tpl_width + 1;
146 res_height = height - tpl_height + 1;
147 cvReleaseImage(&temp);
148 temp = cvCreateImage(cvSize(tplMat.size().width,tplMat.size().height),tplMat.depth(),tplMat.channels() );
149 cv::cvtColor(tplMat, cv::cvarrToMat(temp), cv::COLOR_RGB2BGR);
150 gotTemplate = true;
151 firstFrame = true;
152 if (num_objects>0)
153 free(*regions);
154 num_objects = 0;
155 delete tpl;
156 tpl = NULL;
157
158 lock_guard<mutex> lck(templateMutex);
159 while(tempList.size())
160 {
161 delete tempList.back().templ;
162 tempList.pop_back();
163 }
164 if(bestTempl.templ!=NULL)
165 delete bestTempl.templ;
166 bestTempl.w=0.0;
167 updateNeeded=false;
168 }
169
170 if (gotTemplate)
171 {
172 runAll(frame);
173 }
174
175 //send it all
176 if (imageOut.getOutputCount()>0)
177 {
178 ImageOf<PixelBgr> &img = imageOut.prepare();
179 img.resize(width,height);
180 cv::cvarrToMat(frame).copyTo(toCvMat(img));
181 imageOut.write();
182 }
183 if (imageOutBlob.getOutputCount()>0)
184 {
185 ImageOf<PixelMono> &imgBlob = imageOutBlob.prepare();
186 imgBlob.resize(width,height);
187 cv::cvarrToMat(frame_blob).copyTo(toCvMat(imgBlob));
188 imageOutBlob.write();
189 }
190 cvReleaseImage(&frame);
191 cvReleaseImage(&frame_blob);
192 }
193 } //while
194}
195/**********************************************************/
197{
198 cout << "cleaning up..." << endl;
199 cout << "attempting to close ports" << endl;
200 imageIn.interrupt();
201 imageOut.interrupt();
202 imageOutBlob.interrupt();
203 imageIn.close();
204 imageOut.close();
205 imageOutBlob.close();
206
207 lock_guard<mutex> lck(templateMutex);
208 while(tempList.size())
209 {
210 delete tempList.back().templ;
211 tempList.pop_back();
212 }
213
214 if(bestTempl.templ!=NULL)
215 delete bestTempl.templ;
216 cout << "finished closing ports" << endl;
217}
218
219/**********************************************************/
220void PARTICLEThread::initAll()
221{
222 //here some initialization
223 iCubImage = imageIn.read();
224 width = iCubImage->width();
225 height = iCubImage->height();
226 init = false;
227}
228/**********************************************************/
229void PARTICLEThread::runAll(IplImage *img)
230{
231 img_hsv = bgr2hsv( img );
232 if (firstFrame)
233 {
234 w = img->width;
235 h = img->height;
236
237 while( num_objects == 0 )
238 {
239 num_objects = get_regionsImage( img, regions );
240 if( num_objects == 0 )
241 fprintf( stderr, "Problem! seg has issues\n" );
242 }
243 if (ref_histos!=NULL)
244 free_histos ( ref_histos, num_objects);
245
246 ref_histos = compute_ref_histos( img_hsv, *regions, num_objects );
247 if (particles != NULL)
248 free (particles);
249
250 particles= init_distribution( *regions, ref_histos, num_objects, num_particles );
251 }
252 else
253 {
254 // perform prediction and measurement for each particle
255 for( j = 0; j < num_particles; j++ )
256 {
257 particles[j] = transition( particles[j], w, h, rng );
258 s = particles[j].s;
259 particles[j].w = likelihood( img_hsv, cvRound(particles[j].y),
260 cvRound( particles[j].x ),
261 cvRound( particles[j].width * s ),
262 cvRound( particles[j].height * s ),
263 particles[j].histo );
264 }
265 // normalize weights and resample a set of unweighted particles
266 normalize_weights( particles, num_particles );
267 new_particles = resample( particles, num_particles );
268 free( particles );
269 particles = new_particles;
270 }
271 qsort( particles, num_particles, sizeof( PARTICLEThread::particle ), &particle_cmp );
272
273 averageMutex.lock();
274 for( j = 0; j < num_particles; j++ )
275 average += particles[j].w;
276
277 average = average/num_particles;
278 averageMutex.unlock();
279
280 //display most likely particle ------------------
281 color = cvScalar(255,0,0);
282 targetMutex.lock();
283 targetTemp.clear();
284 //if (imageOut.getOutputCount()>0)
285 display_particle( frame, particles[0], color, targetTemp );
286
287 if (imageOutBlob.getOutputCount()>0)
288 display_particleBlob( frame_blob, particles[0], targetTemp );
289 targetMutex.unlock();
290 trace_template( frame, particles[0] );
291
292 cvReleaseImage(&img_hsv);
293}
294/**********************************************************/
295void PARTICLEThread::setTemplate(ImageOf<PixelRgb> *_tpl)
296{
297 tpl = new ImageOf<PixelRgb> (*_tpl);
298}
299/**********************************************************/
300void PARTICLEThread::pushTarget(Vector &target, Stamp &stamp)
301{
302 lock_guard<mutex> lck(targetMutex);
303 for (size_t i=0; i< targetTemp.length(); i++ )
304 target.push_back(targetTemp[i]);
305
306 stamp=targetStamp;
307}
308/**********************************************************/
310{
311 lock_guard<mutex> lck(averageMutex);
312 float tmpAv = 0.0;
313 tmpAv = average;
314 return tmpAv;
315}
316/**********************************************************/
317int PARTICLEThread::get_regionsImage( IplImage* frame, CvRect** regions )
318{
319 firstFrame = false;
320 params p;
321 CvRect* r;
322 int i; //x1, y1, x2, y2, w, h;
323
324 p.orig_img = cvCloneImage( frame );
325 p.cur_img = NULL;
326 p.n = 0;
327
328 res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
329
330 cvMatchTemplate( frame, temp, res, cv::TM_SQDIFF );
331 cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );
332
333 cvReleaseImage( &(p.orig_img) ); //what was the purpose of this image?
334 cvReleaseImage( &res );
335 if( p.cur_img )
336 cvReleaseImage( &(p.cur_img) );
337 p.n = 1;
338 // extract regions defined by user; store as an array of rectangles ----------
339
340 r = (CvRect*) malloc ( p.n * sizeof( CvRect ) );
341
342 for( i = 0; i < p.n; i++ )
343 r[i] = cvRect( minloc.x, minloc.y, tpl_width, tpl_height );
344
345 *regions = r;
346
347 return p.n;
348}
349/**********************************************************/
350PARTICLEThread::histogram** PARTICLEThread::compute_ref_histos( IplImage* frame, CvRect* regions, int n )
351{
352 histogram** histos = (histogram**) malloc( n * sizeof( histogram* ) );
353 IplImage* tmp;
354 int i;
355
356 // extract each region from frame and compute its histogram
357 for( i = 0; i < n; i++ )
358 {
359 cvSetImageROI( frame, regions[i]);
360 tmp = cvCreateImage( cvGetSize(frame), IPL_DEPTH_32F, 3 );
361 cvCopy( frame, tmp, NULL );
362 cvResetImageROI( frame );
363 histos[i] = calc_histogram( &tmp, 1 );
364 normalize_histogram( histos[i] );
365 cvReleaseImage( &tmp );
366 }
367 return histos;
368}
369/**********************************************************/
370PARTICLEThread::histogram* PARTICLEThread::calc_histogram( IplImage** imgs, int n )
371{
372 IplImage* img;
373 histogram* histo;
374 IplImage* h, * s, * v;
375 float* hist;
376 int i, r, c, bin;
377 histo = (histogram*) malloc( sizeof(histogram) );
378 histo->n = NH*NS + NV;
379 hist = histo->histo;
380 memset( hist, 0, histo->n * sizeof(float) );
381 for( i = 0; i < n; i++ )
382 {
383 // extract individual HSV planes from image
384 img = imgs[i];
385 h = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 );
386 s = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 );
387 v = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 );
388 cvSplit( img, h, s, v, NULL );
389
390 // increment appropriate histogram bin for each pixel
391 for( r = 0; r < img->height; r++ )
392 for( c = 0; c < img->width; c++ )
393 {
394 bin = histo_bin( pixval32f( h, r, c ),
395 pixval32f( s, r, c ),
396 pixval32f( v, r, c ) );
397 hist[bin] += 1;
398 }
399 cvReleaseImage( &h );
400 cvReleaseImage( &s );
401 cvReleaseImage( &v );
402 }
403 return histo;
404}
405/**********************************************************/
406void PARTICLEThread::free_histos( PARTICLEThread::histogram** histo, int n)
407{
408 for (int i = 0; i < n; i++)
409 free (histo[i]);
410
411 free(histo);
412}
413/**********************************************************/
414void PARTICLEThread::free_regions( CvRect** regions, int n)
415{
416 for (int i = 0; i < n; i++)
417 free (regions[i]);
418
419 free(regions);
420}
421/**********************************************************/
422void PARTICLEThread::normalize_histogram( PARTICLEThread::histogram* histo )
423{
424 float* hist;
425 float sum = 0, inv_sum;
426 int i, n;
427
428 hist = histo->histo;
429 n = histo->n;
430
431 // compute sum of all bins and multiply each bin by the sum's inverse
432 for( i = 0; i < n; i++ )
433 sum += hist[i];
434 inv_sum = 1.0f / sum;
435 for( i = 0; i < n; i++ )
436 hist[i] *= inv_sum;
437}
438/**********************************************************/
439int PARTICLEThread::histo_bin( float h, float s, float v )
440{
441 int hd, sd, vd;
442
443 // if S or V is less than its threshold, return a "colorless" bin
444 vd = MIN( (int)(v * NV / V_MAX), NV-1 );
445 if( s < S_THRESH || v < V_THRESH )
446 return NH * NS + vd;
447
448 // otherwise determine "colorful" bin
449 hd = MIN( (int)(h * NH / H_MAX), NH-1 );
450 sd = MIN( (int)(s * NS / S_MAX), NS-1 );
451 return sd * NH + hd;
452}
453/**********************************************************/
454PARTICLEThread::particle* PARTICLEThread::init_distribution( CvRect* regions, histogram** histos, int n, int p)
455{
456 particle* particles;
457 int np;
458 float x, y;
459 int i, j, width, height, k = 0;
460
461 particles = (particle* )malloc( p * sizeof( particle ) );
462 np = p / n;
463
464 // create particles at the centers of each of n regions
465 for( i = 0; i < n; i++ ) {
466 width = regions[i].width;
467 height = regions[i].height;
468 x = regions[i].x + (float)(width / 2);
469 y = regions[i].y + (float) (height / 2);
470 for( j = 0; j < np; j++ )
471 {
472 particles[k].x0 = particles[k].xp = particles[k].x = x;
473 particles[k].y0 = particles[k].yp = particles[k].y = y;
474 particles[k].sp = particles[k].s = 1.0;
475 particles[k].width = width;
476 particles[k].height = height;
477 particles[k].histo = histos[i];
478 particles[k++].w = 0;
479 }
480 }
481 // make sure to create exactly p particles
482 i = 0;
483 while( k < p )
484 {
485 width = regions[i].width;
486 height = regions[i].height;
487 x = regions[i].x + (float) (width / 2);
488 y = regions[i].y + (float) (height / 2);
489 particles[k].x0 = particles[k].xp = particles[k].x = x;
490 particles[k].y0 = particles[k].yp = particles[k].y = y;
491 particles[k].sp = particles[k].s = 1.0;
492 particles[k].width = width;
493 particles[k].height = height;
494 particles[k].histo = histos[i];
495 particles[k++].w = 0;
496 i = ( i + 1 ) % n;
497 }
498 return particles;
499}
500/**********************************************************/
501PARTICLEThread::particle PARTICLEThread::transition( const PARTICLEThread::particle &p, int w, int h, gsl_rng* rng )
502{
503 float x, y, s;
505
506 // sample new state using second-order autoregressive dynamics
507 x = pfot_A1 * ( p.x - p.x0 ) + pfot_A2 * ( p.xp - p.x0 ) +
508 pfot_B0 * (float)(gsl_ran_gaussian( rng, TRANS_X_STD )) + p.x0;
509 pn.x = MAX( 0.0f, MIN( (float)w - 1.0f, x ) );
510 y = pfot_A1 * ( p.y - p.y0 ) + pfot_A2 * ( p.yp - p.y0 ) +
511 pfot_B0 * (float)(gsl_ran_gaussian( rng, TRANS_Y_STD )) + p.y0;
512 pn.y = MAX( 0.0f, MIN( (float)h - 1.0f, y ) );
513 s = pfot_A1 * ( p.s - 1.0f ) + pfot_A2 * ( p.sp - 1.0f ) +
514 pfot_B0 * (float)(gsl_ran_gaussian( rng, TRANS_S_STD )) + 1.0f;
515 pn.s = MAX( 0.1f, s );
516
517 pn.xp = p.x;
518 pn.yp = p.y;
519 pn.sp = p.s;
520 pn.x0 = p.x0;
521 pn.y0 = p.y0;
522 pn.width = p.width;
523 pn.height = p.height;
524 pn.histo = p.histo;
525 pn.w = 0;
526
527 return pn;
528}
529/**********************************************************/
530float PARTICLEThread::likelihood( IplImage* img, int r, int c, int w, int h, histogram* ref_histo )
531{
532 IplImage* tmp;
533 histogram* histo;
534 float d_sq;
535
536 // extract region around (r,c) and compute and normalize its histogram
537 cvSetImageROI( img, cvRect( c - w / 2, r - h / 2, w, h ) );
538 tmp = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 3 );
539 cvCopy( img, tmp, NULL );
540 cvResetImageROI( img );
541 histo = calc_histogram( &tmp, 1 );
542 cvReleaseImage( &tmp );
543 normalize_histogram( histo );
544
545 // compute likelihood as e^{\lambda D^2(h, h^*)}
546 d_sq = histo_dist_sq( histo, ref_histo );
547 free( histo );
548 return exp( -LAMBDA * d_sq );
549}
550/**********************************************************/
551float PARTICLEThread::histo_dist_sq( histogram* h1, histogram* h2 )
552{
553 float* hist1, * hist2;
554 float sum = 0;
555 int i, n;
556
557 n = h1->n;
558 hist1 = h1->histo;
559 hist2 = h2->histo;
560 // According the the Battacharyya similarity coefficient,
561 // D = \sqrt{ 1 - \sum_1^n{ \sqrt{ h_1(i) * h_2(i) } } }
562
563 for( i = 0; i < n; i++ )
564 sum += sqrt( hist1[i]*hist2[i] );
565
566 if(sum<1.0f)
567 return sqrt(1.0f - sum);
568 else
569 {
570 // should be impossible to get here...
571 fprintf(stdout,"Error in similarity computation!\n");
572 return 1.0f-sum;
573 }
574}
575/**********************************************************/
576void PARTICLEThread::normalize_weights( particle* particles, int n )
577{
578 float sum = 0;
579 int i;
580
581 for( i = 0; i < n; i++ )
582 sum += particles[i].w;
583 for( i = 0; i < n; i++ )
584 particles[i].w /= sum;
585}
586/**********************************************************/
587PARTICLEThread::particle* PARTICLEThread::resample( particle* particles, int n )
588{
589 particle* _new_particles;
590 int i, j, np, k = 0;
591
592 //new_particles = (particle* )malloc( sizeof( particle ) );
593 qsort( particles, n, sizeof( particle ), &particle_cmp );
594 _new_particles = (particle* ) malloc( n * sizeof( particle ) );
595
596 for( i = 0; i < n; i++ )
597 {
598 np = cvRound( particles[i].w * n );
599 for( j = 0; j < np; j++ )
600 {
601 _new_particles[k++] = particles[i];
602 if( k == n )
603 goto exit;
604 }
605 }
606 while( k < n )
607 _new_particles[k++] = particles[0];
608
609 exit:
610 return _new_particles;
611}
612/**********************************************************/
613void PARTICLEThread::display_particle( IplImage* img, const PARTICLEThread::particle &p, CvScalar color, Vector& target )
614{
615 int x0, y0, x1, y1;
616 x0 = cvRound( p.x - 0.5 * p.s * p.width );
617 y0 = cvRound( p.y - 0.5 * p.s * p.height );
618 x1 = x0 + cvRound( p.s * p.width );
619 y1 = y0 + cvRound( p.s * p.height );
620
621 cvRectangle( img, cvPoint( x0, y0 ), cvPoint( x1, y1 ), color, 1, 8, 0 );
622
623 cvCircle (img, cvPoint((x0+x1)/2, (y0+y1)/2), 3, cvScalar(255,0 ,0),1);
624 cvCircle (img, cvPoint( x0, y0), 3, cvScalar(0, 255 ,0),1);
625 cvCircle (img, cvPoint( x1, y1), 3, cvScalar(0, 255 ,0),1);
626
627 target.push_back((x0+x1)/2);
628 target.push_back((y0+y1)/2);
629 target.push_back(x0);
630 target.push_back(y0);
631 target.push_back(x1);
632 target.push_back(y1);
633}
634/**********************************************************/
635void PARTICLEThread::display_particleBlob( IplImage* img, const PARTICLEThread::particle &p, Vector& target )
636{
637 int x0, y0, x1, y1;
638 x0 = cvRound( p.x - 0.5 * p.s * p.width );
639 y0 = cvRound( p.y - 0.5 * p.s * p.height );
640 x1 = x0 + cvRound( p.s * p.width );
641 y1 = y0 + cvRound( p.s * p.height );
642
643 int step = img->widthStep/sizeof(uchar);
644 uchar* data = (uchar *)img->imageData;
645
646 for (int i=0; i<img->height; i++)
647 {
648 for (int j=0; j<img->width; j++)
649 {
650 data[i*step+j] = 0;
651 }
652 }
653 cvRectangle(img, cvPoint(x0,y0), cvPoint(x1,y1), cvScalar(255,255, 255), cv::FILLED);
654}
655/**********************************************************/
656void PARTICLEThread::trace_template( IplImage* img, const particle &p )
657{
659 {
660 //create the template image
662 t.w=p.w;
663 t.templ=new ImageOf<PixelRgb>;
664 t.templ->resize(cvRound(p.s*p.width),cvRound(p.s*p.height));
665
666 cv::Mat imgMat(cv::cvarrToMat(img),cv::Rect(cvRound(p.x-0.5*p.s*p.width),
667 cvRound(p.y-0.5*p.s*p.height),
668 cvRound(p.s*p.width),
669 cvRound(p.s*p.height)));
670
671 cv::cvtColor(imgMat,toCvMat(*t.templ),cv::COLOR_BGR2RGB);
672
673 cvResetImageROI(img);
674
675 tempList.push_front(t);
676 if (tempList.size()>TEMP_LIST_SIZE)
677 {
678 delete tempList.back().templ;
679 tempList.pop_back();
680 }
681 }
682 //keep in check the best template
683 lock_guard<mutex> lck(templateMutex);
684 //detect if the image tracker should be updated with a template from the stored ones
686 updateNeeded=true;
687
688 int best_idx=-1;
689 float best_w=0.0;
690 for(unsigned int i=0; i<tempList.size(); i++)
691 {
692 if(tempList[i].w<best_w)
693 {
694 best_idx=i;
695 best_w=tempList[i].w;
696 }
697 }
698
699 if(best_idx==-1)
700 {
701 updateNeeded=false;
702 }
703 else if(bestTempl.w!=best_w) //avoid releasing and copying the same image
704 {
705 if(bestTempl.templ==NULL)
706 bestTempl.templ=new ImageOf<PixelRgb>;
707
708 *bestTempl.templ=*tempList[best_idx].templ;
709 bestTempl.w=best_w;
710 }
711}
712/**********************************************************/
713float PARTICLEThread::pixval32f(IplImage* img, int r, int c)
714{
715 return ( (float*)(img->imageData + img->widthStep*r) )[c];
716}
717/**********************************************************/
718IplImage* PARTICLEThread::bgr2hsv( IplImage* bgr )
719{
720 IplImage* bgr32f, * hsv;
721
722 bgr32f = cvCreateImage( cvGetSize(bgr), IPL_DEPTH_32F, 3 );
723 hsv = cvCreateImage( cvGetSize(bgr), IPL_DEPTH_32F, 3 );
724 cvConvertScale( bgr, bgr32f, 1.0 / 255.0, 0 );
725 cvCvtColor( bgr32f, hsv, cv::COLOR_BGR2HSV );
726 cvReleaseImage( &bgr32f );
727 return hsv;
728}
729/**********************************************************/
731{
732 TemplateStruct best;
733 best.templ=NULL;
734 best.w=0.0;
735
736 lock_guard<mutex> lck(templateMutex);
737 if(updateNeeded)
738 {
739 best.templ=new ImageOf<PixelRgb>;
740 *best.templ=*bestTempl.templ;
741 best.w=bestTempl.w;
742 }
743 return best;
744}
745/**********************************************************/
746PARTICLEManager::PARTICLEManager() : PeriodicThread(0.02)
747{
748 tpl = NULL;
749}
750/**********************************************************/
752/**********************************************************/
753void PARTICLEManager::setName(string module)
754{
755 this->moduleName = module;
756}
757/**********************************************************/
759{
760 //create all ports
761 inputPortNameTemp = "/" + moduleName + "/template/image:i";
762 imageInTemp.open( inputPortNameTemp.c_str() );
763
764 outputPortNameTarget = "/" + moduleName + "/target:o";
765 target.open( outputPortNameTarget.c_str() );
766
767 disparityPort.open(("/"+moduleName+"/triangulation:io").c_str());
768 target3D.open(("/"+moduleName+"/target3d:o").c_str());
769
770 particleThreadLeft = new PARTICLEThread();
771 particleThreadRight = new PARTICLEThread();
772
773 particleThreadLeft->setName((moduleName + "/left").c_str());
774 particleThreadRight->setName((moduleName + "/right").c_str());
775
776 shouldSend = false;
777 particleThreadLeft->start();
778 particleThreadRight->start();
779 return true;
780}
781/**********************************************************/
783{
784 TemplateStruct templLeft,templRight;
785
786 // if there is no need for a template update, the NULL pointers are returned
787 templLeft=particleThreadLeft->getBestTemplate();
788 templRight=particleThreadRight->getBestTemplate();
789
790 ImageOf<PixelRgb> *tmp_tpl=templLeft.w>templRight.w?templLeft.templ:templRight.templ;
791
792 // copy tmp_tpl whether it is NULL or not
793 tpl = tmp_tpl;
794 tpl = imageInTemp.read(false);
795
796 if (tpl!=NULL)
797 {
798 shouldSend = true;
799 particleThreadLeft->setTemplate(tpl);
800 particleThreadRight->setTemplate(tpl);
801 }
802 Vector targetTemp;
803 Stamp leftStamp,rightStamp;
804
805 particleThreadLeft->pushTarget(targetTemp,leftStamp);
806 particleThreadRight->pushTarget(targetTemp,rightStamp);
807
808 float averageTempLeft = 0.0;
809 float averageTempRight = 0.0;
810
811 averageTempLeft = particleThreadLeft->getAverage();
812 averageTempLeft = averageTempLeft *100;
813 //fprintf(stdout,"the average is %lf \n",averageTempLeft *100);
814
815
816 if (shouldSend)
817 {
818 if (target.getOutputCount() > 0 && targetTemp.size() > 4 &&
819 fabs(leftStamp.getTime()-rightStamp.getTime())<0.002)
820 {
821 //fprintf(stdout,"output %lf %lf %lf %lf\n", targetTemp[0], targetTemp[1], targetTemp[2], targetTemp[3]);
822 Stamp propagatedStamp(leftStamp.getCount(),0.5*(leftStamp.getTime()+rightStamp.getTime()));
823 target.setEnvelope(propagatedStamp);
824 target.write(targetTemp);
825 }
826 if (disparityPort.getOutputCount() > 0 && targetTemp.size())
827 {
828 //fprintf(stdout,"getting ready to send\n");
829 Bottle cmd, reply;
830 cmd.addFloat64(targetTemp[0]);
831 cmd.addFloat64(targetTemp[1]);
832 cmd.addFloat64(targetTemp[6]);
833 cmd.addFloat64(targetTemp[7]);
834 fprintf(stdout,"output %lf %lf %lf %lf\n", targetTemp[0], targetTemp[1], targetTemp[6], targetTemp[7]);
835
836 disparityPort.write(cmd,reply);
837
838 Bottle targets;
839 targets.addFloat64(reply.get(0).asFloat64());
840 targets.addFloat64(reply.get(1).asFloat64());
841 targets.addFloat64(reply.get(2).asFloat64());
842 targets.addFloat64(0.0);
843 targets.addFloat64(0.0);
844 targets.addFloat64(0.0);
845 targets.addFloat64(averageTempLeft);
846
847 target3D.write(targets);
848 }
849 }
850 //clear templates
851 if(templLeft.templ!=NULL)
852 delete templLeft.templ;
853 if(templRight.templ!=NULL)
854 delete templRight.templ;
855}
856/**********************************************************/
858{
859 cout << "cleaning up Manager..." << endl;
860 cout << "attempting to close ports Manager" << endl;
861 particleThreadLeft->stop();
862 particleThreadRight->stop();
863
864 imageInTemp.interrupt();
865 target.interrupt();
866 imageInTemp.close();
867 target.close();
868
869 disparityPort.interrupt();
870 disparityPort.close();
871
872 target3D.interrupt();
873 target3D.close();
874
875 cout << "deleteing thread " << endl;
876 delete particleThreadLeft;
877 delete particleThreadRight;
878 cout << "finished closing ports Manager" << endl;
879}
880/**********************************************************/
881bool PARTICLEModule::configure(yarp::os::ResourceFinder &rf)
882{
883 /* Process all parameters from both command-line and .ini file */
884
885 moduleName = rf.check("name",
886 Value("templatePFTracker"),
887 "module name (string)").asString();
888
889 setName(moduleName.c_str());
890
891 handlerPortName = "/";
892 handlerPortName += getName(); // use getName() rather than a literal
893
894 if (!handlerPort.open(handlerPortName.c_str()))
895 {
896 cout << getName() << ": Unable to open port " << handlerPortName << endl;
897 return false;
898 }
899
900 attach(handlerPort);
901
902 /* create the thread and pass pointers to the module parameters */
903 particleManager = new PARTICLEManager();
904
905 /*pass the name of the module in order to create ports*/
906 particleManager->setName(moduleName);
907 /* now start the thread to do the work */
908 particleManager->start();
909
910
911 return true ;
912}
913/**********************************************************/
915{
916 handlerPort.interrupt();
917 return true;
918}
919/**********************************************************/
921{
922 handlerPort.close();
923 /* stop the thread */
924 particleManager->stop();
925 cout << "deleteing thread " << endl;
926 delete particleManager;
927 return true;
928}
929/**********************************************************/
930bool PARTICLEModule::respond(const Bottle& command, Bottle& reply)
931{
932 string helpMessage = string(getName().c_str()) +
933 " commands are: \n" +
934 "help \n" +
935 "quit \n";
936
937 reply.clear();
938
939 if (command.get(0).asString()=="quit")
940 {
941 reply.addString("quitting");
942 return false;
943 }
944 else if (command.get(0).asString()=="help")
945 {
946 cout << helpMessage;
947 reply.addString("ok");
948 }
949 else if (command.get(0).asString()=="reset")
950 {
951 cout << "reset has been asked "<< endl;
952 particleManager->shouldSend=false;
953 reply.addString("ok");
954 }
955 else
956 {
957 cout << "command not known - type help for more info" << endl;
958 }
959 return true;
960}
961/**********************************************************/
963{
964 return true;
965}
966/**********************************************************/
968{
969 return 0.1;
970}
971
972
@ data
void setName(std::string module)
bool respond(const yarp::os::Bottle &command, yarp::os::Bottle &reply)
bool configure(yarp::os::ResourceFinder &rf)
TemplateStruct getBestTemplate()
void setName(std::string module)
void setTemplate(yarp::sig::ImageOf< yarp::sig::PixelRgb > *tpl)
struct PARTICLEThread::particle particle
void pushTarget(yarp::sig::Vector &target, yarp::os::Stamp &stamp)
exp(-x3 *T)]
cmd
Definition dataTypes.h:30
int n
#define MIN(a, b)
int particle_cmp(const void *p1, const void *p2)
#define NS
struct TemplateStruct TemplateStruct
#define V_THRESH
#define pfot_B0
#define TEMP_LIST_SIZE
#define TRANS_S_STD
#define S_MAX
int particle_cmp(const void *p1, const void *p2)
#define LAMBDA
#define pfot_A2
#define PARTICLES
#define S_THRESH
#define TRANS_Y_STD
#define TEMP_LIST_PARTICLE_THRES_HIGH
#define NH
#define V_MAX
#define H_MAX
#define TEMP_LIST_PARTICLE_THRES_LOW
#define NV
#define pfot_A1
#define TRANS_X_STD
fprintf(fid,'\n')
degrees time
Definition sine.m:5
yarp::sig::ImageOf< yarp::sig::PixelRgb > * templ