23#include <opencv2/imgproc.hpp>
24#include <yarp/cv/Cv.h>
28using namespace yarp::os;
29using namespace yarp::sig;
30using namespace yarp::cv;
48 cout <<
"deleting dynamic objects" << endl;
50 free_regions ( regions, num_objects );
53 free_histos ( ref_histos, num_objects);
59 cout <<
"releasing temp" << endl;
60 cvReleaseImage(&temp);
62 cout <<
"finished particle thread" << endl;
69 regions = (CvRect **) malloc(
sizeof(CvRect*));
71 rng = gsl_rng_alloc( gsl_rng_mt19937 );
72 gsl_rng_set( rng, (
unsigned long)
time(NULL) );
88 this->moduleName =
module;
96 inputPortName =
"/" + moduleName +
"/image:i";
97 imageIn.open( inputPortName.c_str() );
99 outputPortName =
"/" + moduleName +
"/image:o";
100 imageOut.open( outputPortName.c_str() );
102 outputPortNameBlob =
"/" + moduleName +
"/blob/image:o";
103 imageOutBlob.open( outputPortNameBlob.c_str() );
109 bestTempl.templ=NULL;
116 while (isStopping() !=
true) {
118 getImage = ( imageIn.getInputCount() > 0 );
126 cout <<
"initializing" << endl;
131 iCubImage = imageIn.read();
132 lock_guard<mutex> lck(templateMutex);
133 imageIn.getEnvelope(targetTemp);
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 );
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);
158 lock_guard<mutex> lck(templateMutex);
159 while(tempList.size())
161 delete tempList.back().templ;
164 if(bestTempl.templ!=NULL)
165 delete bestTempl.templ;
176 if (imageOut.getOutputCount()>0)
178 ImageOf<PixelBgr> &img = imageOut.prepare();
179 img.resize(width,height);
180 cv::cvarrToMat(frame).copyTo(toCvMat(img));
183 if (imageOutBlob.getOutputCount()>0)
185 ImageOf<PixelMono> &imgBlob = imageOutBlob.prepare();
186 imgBlob.resize(width,height);
187 cv::cvarrToMat(frame_blob).copyTo(toCvMat(imgBlob));
188 imageOutBlob.write();
190 cvReleaseImage(&frame);
191 cvReleaseImage(&frame_blob);
198 cout <<
"cleaning up..." << endl;
199 cout <<
"attempting to close ports" << endl;
201 imageOut.interrupt();
202 imageOutBlob.interrupt();
205 imageOutBlob.close();
207 lock_guard<mutex> lck(templateMutex);
208 while(tempList.size())
210 delete tempList.back().templ;
214 if(bestTempl.templ!=NULL)
215 delete bestTempl.templ;
216 cout <<
"finished closing ports" << endl;
220void PARTICLEThread::initAll()
223 iCubImage = imageIn.read();
224 width = iCubImage->width();
225 height = iCubImage->height();
229void PARTICLEThread::runAll(IplImage *img)
231 img_hsv = bgr2hsv( img );
237 while( num_objects == 0 )
239 num_objects = get_regionsImage( img, regions );
240 if( num_objects == 0 )
241 fprintf( stderr,
"Problem! seg has issues\n" );
243 if (ref_histos!=NULL)
244 free_histos ( ref_histos, num_objects);
246 ref_histos = compute_ref_histos( img_hsv, *regions, num_objects );
247 if (particles != NULL)
250 particles= init_distribution( *regions, ref_histos, num_objects, num_particles );
255 for( j = 0; j < num_particles; j++ )
257 particles[j] = transition( particles[j], w, h, rng );
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 );
266 normalize_weights( particles, num_particles );
267 new_particles = resample( particles, num_particles );
269 particles = new_particles;
274 for( j = 0; j < num_particles; j++ )
278 averageMutex.unlock();
281 color = cvScalar(255,0,0);
285 display_particle( frame, particles[0], color, targetTemp );
287 if (imageOutBlob.getOutputCount()>0)
288 display_particleBlob( frame_blob, particles[0], targetTemp );
289 targetMutex.unlock();
290 trace_template( frame, particles[0] );
292 cvReleaseImage(&img_hsv);
297 tpl =
new ImageOf<PixelRgb> (*_tpl);
302 lock_guard<mutex> lck(targetMutex);
303 for (
size_t i=0; i< targetTemp.length(); i++ )
304 target.push_back(targetTemp[i]);
311 lock_guard<mutex> lck(averageMutex);
317int PARTICLEThread::get_regionsImage( IplImage* frame, CvRect** regions )
324 p.orig_img = cvCloneImage( frame );
328 res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
330 cvMatchTemplate( frame, temp, res, cv::TM_SQDIFF );
331 cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );
333 cvReleaseImage( &(
p.orig_img) );
334 cvReleaseImage( &res );
336 cvReleaseImage( &(
p.cur_img) );
340 r = (CvRect*) malloc (
p.n *
sizeof( CvRect ) );
342 for( i = 0; i <
p.n; i++ )
343 r[i] = cvRect( minloc.x, minloc.y, tpl_width, tpl_height );
357 for( i = 0; i <
n; i++ )
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 );
374 IplImage* h, * s, * v;
380 memset( hist, 0, histo->n *
sizeof(
float) );
381 for( i = 0; i <
n; 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 );
391 for( r = 0; r < img->height; r++ )
392 for( c = 0; c < img->width; c++ )
394 bin = histo_bin( pixval32f( h, r, c ),
395 pixval32f( s, r, c ),
396 pixval32f( v, r, c ) );
399 cvReleaseImage( &h );
400 cvReleaseImage( &s );
401 cvReleaseImage( &v );
408 for (
int i = 0; i <
n; i++)
414void PARTICLEThread::free_regions( CvRect** regions,
int n)
416 for (
int i = 0; i <
n; i++)
425 float sum = 0, inv_sum;
432 for( i = 0; i <
n; i++ )
434 inv_sum = 1.0f / sum;
435 for( i = 0; i <
n; i++ )
439int PARTICLEThread::histo_bin(
float h,
float s,
float v )
459 int i, j, width, height, k = 0;
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++ )
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;
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;
509 pn.
x = MAX( 0.0f,
MIN( (
float)w - 1.0f, x ) );
512 pn.
y = MAX( 0.0f,
MIN( (
float)h - 1.0f, y ) );
515 pn.
s = MAX( 0.1f, s );
530float PARTICLEThread::likelihood( IplImage* img,
int r,
int c,
int w,
int h, histogram* ref_histo )
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 );
546 d_sq = histo_dist_sq( histo, ref_histo );
551float PARTICLEThread::histo_dist_sq( histogram* h1, histogram* h2 )
553 float* hist1, * hist2;
563 for( i = 0; i <
n; i++ )
564 sum += sqrt( hist1[i]*hist2[i] );
567 return sqrt(1.0f - sum);
571 fprintf(stdout,
"Error in similarity computation!\n");
576void PARTICLEThread::normalize_weights( particle* particles,
int n )
581 for( i = 0; i <
n; i++ )
582 sum += particles[i].w;
583 for( i = 0; i <
n; i++ )
584 particles[i].w /= sum;
596 for( i = 0; i <
n; i++ )
598 np = cvRound( particles[i].w *
n );
599 for( j = 0; j < np; j++ )
601 _new_particles[k++] = particles[i];
607 _new_particles[k++] = particles[0];
610 return _new_particles;
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 );
621 cvRectangle( img, cvPoint( x0, y0 ), cvPoint(
x1, y1 ), color, 1, 8, 0 );
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);
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);
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 );
643 int step = img->widthStep/
sizeof(uchar);
644 uchar*
data = (uchar *)img->imageData;
646 for (
int i=0; i<img->height; i++)
648 for (
int j=0; j<img->width; j++)
653 cvRectangle(img, cvPoint(x0,y0), cvPoint(
x1,y1), cvScalar(255,255, 255), cv::FILLED);
656void PARTICLEThread::trace_template( IplImage* img,
const particle &
p )
663 t.
templ=
new ImageOf<PixelRgb>;
664 t.
templ->resize(cvRound(
p.s*
p.width),cvRound(
p.s*
p.height));
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)));
671 cv::cvtColor(imgMat,toCvMat(*t.
templ),cv::COLOR_BGR2RGB);
673 cvResetImageROI(img);
675 tempList.push_front(t);
678 delete tempList.back().templ;
683 lock_guard<mutex> lck(templateMutex);
690 for(
unsigned int i=0; i<tempList.size(); i++)
692 if(tempList[i].w<best_w)
695 best_w=tempList[i].w;
703 else if(bestTempl.w!=best_w)
705 if(bestTempl.templ==NULL)
706 bestTempl.templ=
new ImageOf<PixelRgb>;
708 *bestTempl.templ=*tempList[best_idx].templ;
713float PARTICLEThread::pixval32f(IplImage* img,
int r,
int c)
715 return ( (
float*)(img->imageData + img->widthStep*r) )[c];
718IplImage* PARTICLEThread::bgr2hsv( IplImage* bgr )
720 IplImage* bgr32f, * hsv;
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 );
736 lock_guard<mutex> lck(templateMutex);
739 best.
templ=
new ImageOf<PixelRgb>;
740 *best.
templ=*bestTempl.templ;
755 this->moduleName =
module;
761 inputPortNameTemp =
"/" + moduleName +
"/template/image:i";
762 imageInTemp.open( inputPortNameTemp.c_str() );
764 outputPortNameTarget =
"/" + moduleName +
"/target:o";
765 target.open( outputPortNameTarget.c_str() );
767 disparityPort.open((
"/"+moduleName+
"/triangulation:io").c_str());
768 target3D.open((
"/"+moduleName+
"/target3d:o").c_str());
773 particleThreadLeft->setName((moduleName +
"/left").c_str());
774 particleThreadRight->setName((moduleName +
"/right").c_str());
777 particleThreadLeft->start();
778 particleThreadRight->start();
787 templLeft=particleThreadLeft->getBestTemplate();
788 templRight=particleThreadRight->getBestTemplate();
790 ImageOf<PixelRgb> *tmp_tpl=templLeft.
w>templRight.
w?templLeft.
templ:templRight.
templ;
794 tpl = imageInTemp.read(
false);
799 particleThreadLeft->setTemplate(tpl);
800 particleThreadRight->setTemplate(tpl);
803 Stamp leftStamp,rightStamp;
805 particleThreadLeft->pushTarget(targetTemp,leftStamp);
806 particleThreadRight->pushTarget(targetTemp,rightStamp);
808 float averageTempLeft = 0.0;
809 float averageTempRight = 0.0;
811 averageTempLeft = particleThreadLeft->getAverage();
812 averageTempLeft = averageTempLeft *100;
818 if (target.getOutputCount() > 0 && targetTemp.size() > 4 &&
819 fabs(leftStamp.getTime()-rightStamp.getTime())<0.002)
822 Stamp propagatedStamp(leftStamp.getCount(),0.5*(leftStamp.getTime()+rightStamp.getTime()));
823 target.setEnvelope(propagatedStamp);
824 target.write(targetTemp);
826 if (disparityPort.getOutputCount() > 0 && targetTemp.size())
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]);
836 disparityPort.write(
cmd,reply);
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);
847 target3D.write(targets);
851 if(templLeft.
templ!=NULL)
852 delete templLeft.
templ;
853 if(templRight.
templ!=NULL)
854 delete templRight.
templ;
859 cout <<
"cleaning up Manager..." << endl;
860 cout <<
"attempting to close ports Manager" << endl;
861 particleThreadLeft->stop();
862 particleThreadRight->stop();
864 imageInTemp.interrupt();
869 disparityPort.interrupt();
870 disparityPort.close();
872 target3D.interrupt();
875 cout <<
"deleteing thread " << endl;
876 delete particleThreadLeft;
877 delete particleThreadRight;
878 cout <<
"finished closing ports Manager" << endl;
885 moduleName = rf.check(
"name",
886 Value(
"templatePFTracker"),
887 "module name (string)").asString();
889 setName(moduleName.c_str());
891 handlerPortName =
"/";
892 handlerPortName += getName();
894 if (!handlerPort.open(handlerPortName.c_str()))
896 cout << getName() <<
": Unable to open port " << handlerPortName << endl;
906 particleManager->setName(moduleName);
908 particleManager->start();
916 handlerPort.interrupt();
924 particleManager->stop();
925 cout <<
"deleteing thread " << endl;
926 delete particleManager;
932 string helpMessage = string(getName().c_str()) +
933 " commands are: \n" +
939 if (command.get(0).asString()==
"quit")
941 reply.addString(
"quitting");
944 else if (command.get(0).asString()==
"help")
947 reply.addString(
"ok");
949 else if (command.get(0).asString()==
"reset")
951 cout <<
"reset has been asked "<< endl;
952 particleManager->shouldSend=
false;
953 reply.addString(
"ok");
957 cout <<
"command not known - type help for more info" << endl;
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)
int particle_cmp(const void *p1, const void *p2)
struct TemplateStruct TemplateStruct
int particle_cmp(const void *p1, const void *p2)
#define TEMP_LIST_PARTICLE_THRES_HIGH
#define TEMP_LIST_PARTICLE_THRES_LOW
yarp::sig::ImageOf< yarp::sig::PixelRgb > * templ