19 #include "powerGrasp.h" 35 PowerGrasp::PowerGrasp() : cloud(new
pcl::PointCloud<
pcl::PointXYZRGB>),
36 cloudxyz(new
pcl::PointCloud<
pcl::PointXYZ>),
37 normals(new
pcl::PointCloud <
pcl::Normal>)
39 modality=MODALITY_AUTO;
42 chosenPoint.resize(3,0.0);
43 chosenNormal.resize(3,0.0);
44 chosenPixel.resize(2,0.0);
48 offsetR.resize(3,0.0);
49 offsetL.resize(3,0.0);
59 fromFileFinished=
false;
61 graspSpecificPoint=
false;
67 data.boundingBox=&boundingBox;
68 data.goodPointsIndexes=&rankIndices;
70 currentState=STATE_WAIT;
71 visualizationThread=
new VisualizationThread(data);
75 void PowerGrasp::configureGeneralInfo(ResourceFinder &rf)
77 radiusSearch=rf.check(
"radiusSearch",Value(0.045)).asDouble();
78 numberOfBestPoints=rf.check(
"numberOfBestPoints",Value(10)).asInt();
79 bestCurvature=(float)rf.check(
"curvature",Value(0.005)).asDouble();
80 handSize=rf.check(
"handSize",Value(0.08)).asDouble();
81 fingerSize=rf.check(
"fingerSize",Value(0.08)).asDouble();
82 string useFile=rf.check(
"fromFile",Value(
"false")).asString().c_str();
83 string useLearning=rf.check(
"useLearning",Value(
"false")).asString().c_str();
84 fromFile=(useFile==
"true");
85 testWithLearning=(useLearning==
"true");
86 posx=rf.check(
"x",Value(0)).asInt();
87 posy=rf.check(
"y",Value(0)).asInt();
88 visualizationThread->setPosition(posx, posy);
89 sizex=rf.check(
"w",Value(320)).asInt();
90 sizey=rf.check(
"h",Value(240)).asInt();
91 visualizationThread->setSize(sizex, sizey);
93 if (!rf.check(
"disableRight"))
94 orientationThreadRight=
new OrientationThread();
98 printf(
"**********RIGHT ARM DISABLED**************\n");
100 if (!rf.check(
"disableLeft"))
101 orientationThreadLeft=
new OrientationThread();
105 printf(
"**********LEFT ARM DISABLED**************\n");
110 void PowerGrasp::configureSVM(Bottle &bottleSVM)
113 scalerIn.setLowerBoundIn(0.0);
114 scalerIn.setUpperBoundIn(0.03);
115 scalerIn.setLowerBoundOut(0.0);
116 scalerIn.setUpperBoundOut(1.0);
118 scalerOut.setLowerBoundIn(0.0);
119 scalerOut.setUpperBoundIn(0.6);
120 scalerOut.setLowerBoundOut(0.0);
121 scalerOut.setUpperBoundOut(1.0);
123 machine.setDomainSize(1);
124 machine.setCoDomainSize(1);
126 machine.getKernel()->setGamma(100.0);
128 if (!bottleSVM.isNull())
130 if (bottleSVM.check(
"c"))
131 machine.setC(bottleSVM.find(
"c").asDouble());
133 if (bottleSVM.check(
"gamma"))
134 machine.getKernel()->setGamma(bottleSVM.find(
"gamma").asDouble());
136 if (Bottle *v=bottleSVM.find(
"in_bounds").asList())
140 scalerIn.setLowerBoundIn(v->get(0).asDouble());
141 scalerIn.setUpperBoundIn(v->get(1).asDouble());
145 if (Bottle *v=bottleSVM.find(
"out_bounds").asList())
149 scalerOut.setLowerBoundIn(v->get(0).asDouble());
150 scalerOut.setUpperBoundIn(v->get(1).asDouble());
154 if (Bottle *v=bottleSVM.find(
"machine").asList())
155 testWithLearningEnabled=machine.fromString(v->toString().c_str());
157 testWithLearningEnabled=
false;
160 testWithLearningEnabled=
false;
164 bool PowerGrasp::configure(ResourceFinder &rf)
166 configureGeneralInfo(rf);
168 string name=rf.check(
"name",Value(
"power-grasp")).asString().c_str();
170 int nAngles=rf.check(
"nAngles",Value(50)).asInt();
171 string robot=rf.check(
"robot",Value(
"icub")).asString().c_str();
172 string rightArm=
"right_arm";
173 string leftArm=
"left_arm";
175 if (rightDisabled && leftDisabled)
177 printf(
"Both arms disabled\n");
183 rightOK=orientationThreadRight->open(name,rightArm,robot,nAngles);
186 leftOK=orientationThreadLeft->open(name,leftArm,robot,nAngles);
187 if (!rightOK || !leftOK)
189 printf(
"Orientation threads did not open\n");
193 outputDir=rf.find(
"outputDir").asString().c_str();
197 path=rf.find(
"path").asString().c_str();
200 printf(
"Please specify a folder to find the .ply file\n");
205 Bottle *pR=rf.find(
"offsetR").asList();
208 for (
int i=0; i<pR->size(); i++)
209 offsetR[i]=pR->get(i).asDouble();
212 Bottle *pL=rf.find(
"offsetL").asList();
215 for (
int i=0; i<pL->size(); i++)
216 offsetR[i]=pL->get(i).asDouble();
219 rpc.open((
"/"+name+
"/rpc").c_str());
222 if (!meshPort.open((
"/"+name+
"/mesh:i").c_str()))
225 if (!areCmdPort.open((
"/"+name+
"/are/cmd:o").c_str()))
228 if (!reconstructionPort.open((
"/"+name+
"/reconstruction").c_str()))
231 if (!depth2kin.open((
"/"+name+
"/depth2kin:o").c_str()))
234 Bottle &bMachine=rf.findGroup(
"lssvm");
235 configureSVM(bMachine);
238 orientationThreadRight->start();
240 orientationThreadLeft->start();
246 bool PowerGrasp::interruptModule()
249 reconstructionPort.interrupt();
250 areCmdPort.interrupt();
251 depth2kin.interrupt();
252 meshPort.interrupt();
259 bool PowerGrasp::close()
261 reconstructionPort.close();
267 if (visualizationThread->isRunning())
268 visualizationThread->stop();
269 delete visualizationThread;
273 orientationThreadRight->stop();
274 delete orientationThreadRight;
278 orientationThreadLeft->stop();
279 delete orientationThreadLeft;
286 void PowerGrasp::filter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_in,pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_in_filtered)
288 pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;
289 sor.setInputCloud (cloud_in);
290 sor.setMeanK (cloud_in->size()/2);
291 sor.setStddevMulThresh (1.0);
292 sor.filter (*cloud_in_filtered);
296 void PowerGrasp::write(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_in,
const int nFile)
300 string str = ss.str();
301 string filename=outputDir+
"/cloud"+str+
".ply";
303 cloudFile.open (filename.c_str());
304 cloudFile <<
"ply\n";
305 cloudFile <<
"format ascii 1.0\n";
306 cloudFile <<
"element vertex " << cloud_in->size() <<
"\n";
307 cloudFile <<
"property float x\n";
308 cloudFile <<
"property float y\n";
309 cloudFile <<
"property float z\n";
310 cloudFile <<
"property uchar diffuse_red\n";
311 cloudFile <<
"property uchar diffuse_green\n";
312 cloudFile <<
"property uchar diffuse_blue\n";
313 cloudFile <<
"end_header\n";
314 for (
int i=0; i<cloud_in->size(); i++)
316 cloudFile << cloud_in->at(i).x <<
" " << cloud_in->at(i).y <<
" " << cloud_in->at(i).z <<
" " << (int)cloud_in->at(i).r <<
" " << (int)cloud_in->at(i).g <<
" " << (int)cloud_in->at(i).b <<
"\n";
322 void PowerGrasp::fromSurfaceMesh (
const SurfaceMeshWithBoundingBox& msg)
327 for (
size_t i = 0; i<msg.mesh.points.size(); ++i)
329 PointXYZRGB pointrgb;
330 pointrgb.x=msg.mesh.points.at(i).x;
331 pointrgb.y=msg.mesh.points.at(i).y;
332 pointrgb.z=msg.mesh.points.at(i).z;
333 if (i<msg.mesh.rgbColour.size())
335 int32_t rgb= msg.mesh.rgbColour.at(i).rgba;
337 pointrgb.r = (rgb >> 16) & 0x0000ff;
338 pointrgb.g = (rgb >> 8) & 0x0000ff;
339 pointrgb.b = (rgb) & 0x0000ff;
348 cloudxyz->push_back(point);
349 cloud->push_back(pointrgb);
352 boundingBox.setBoundingBox(msg.boundingBox);
356 bool PowerGrasp::fillCloudFromFile()
358 struct dirent *entry;
361 dp = opendir(path.c_str());
368 while((entry = readdir(dp)))
370 if (strcmp(entry->d_name,
".") == 0 || strcmp(entry->d_name,
"..") == 0)
376 if (entry->d_name!=NULL)
378 pcl::PointCloud<PointXYZRGB>::Ptr cloud_in_rgb(
new pcl::PointCloud<PointXYZRGB>);
380 string root=path+
"/";
381 string name=entry->d_name;
382 string file=root+name;
384 if (loadPLYFile(file.c_str(), *cloud_in_rgb) == -1)
389 pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_in_filtered(
new pcl::PointCloud<pcl::PointXYZRGB>);
390 filter(cloud_in_rgb,cloud_in_filtered);
391 addPointCloud(cloud_in_filtered);
394 addPointCloud(cloud_in_rgb);
401 int PowerGrasp::findIndexFromCloud(
const yarp::sig::Vector &point)
405 for (
int i=0; i<cloud->size(); i++)
407 yarp::sig::Vector currentPoint=vectorFromCloud(i);
409 if (norm(point-currentPoint)<minNorm)
412 minNorm=norm(point-currentPoint);
419 void PowerGrasp::normalEstimation()
421 pcl::search::Search<pcl::PointXYZ>::Ptr tree=boost::shared_ptr<pcl::search::Search<pcl::PointXYZ> >(
new pcl::search::KdTree<pcl::PointXYZ>);
422 pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator;
423 normal_estimator.setSearchMethod (tree);
424 normal_estimator.setRadiusSearch (radiusSearch);
425 normal_estimator.setInputCloud (cloudxyz);
426 normal_estimator.compute (*normals);
430 void PowerGrasp::rankPoints()
432 pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
433 kdtree.setInputCloud (cloudxyz);
435 yarp::sig::Vector center=boundingBox.getCenter();
437 std::vector<int> pointIdxRadiusSearch;
438 std::vector<float> pointRadiusSquaredDistance;
444 int minNeighbohrs=300;
449 for (
int i=0; i<cloudxyz->size(); i++)
452 int n_neighbohrs=kdtree.radiusSearch(cloudxyz->at(index),radiusSearch,pointIdxRadiusSearch,pointRadiusSquaredDistance);
453 if (n_neighbohrs>minNeighbohrs)
455 if (normalPointingOut(index,center))
458 double score=scoreFunction(index);
459 insertElement(score,index);
463 if (nGoodPoints<numberOfBestPoints && minNeighbohrs>0)
477 yarp::sig::Vector PowerGrasp::vectorFromNormal(
const int index)
479 yarp::sig::Vector currNormal(3);
480 currNormal[0]=normals->at(index).normal_x;
481 currNormal[1]=normals->at(index).normal_y;
482 currNormal[2]=normals->at(index).normal_z;
488 yarp::sig::Vector PowerGrasp::vectorFromCloud(
const int index)
490 yarp::sig::Vector currPoint(3);
491 currPoint[0]=cloudxyz->at(index).x;
492 currPoint[1]=cloudxyz->at(index).y;
493 currPoint[2]=cloudxyz->at(index).z;
499 void PowerGrasp::chooseCandidatePoints()
503 double tmp=Random::uniform();
504 currentCurvature=(float)fmod(tmp,maxCurvature);
505 printf(
"Chosen curvature %g\n", currentCurvature);
506 printf(
"Max curvature %g\n", maxCurvature);
509 currentCurvature=bestCurvature;
511 currentModality=modality;
513 if (currentModality==MODALITY_AUTO)
519 if (currentModality==MODALITY_CENTER)
521 else if (currentModality==MODALITY_LEFT)
523 else if (currentModality==MODALITY_RIGHT)
528 printf(
"modality chosen %s\n", smodality.c_str());
532 void PowerGrasp::startVisualization()
534 data.chosenPoint=chosenPoint;
535 data.chosenOrientation=chosenOrientation;
536 data.hand=chosenHand;
538 visualizationThread->start();
542 bool PowerGrasp::updateModule()
546 if ((fromFile && !fromFileFinished) || (currentState==STATE_ESTIMATE))
548 double totTime=Time::now();
551 if (!fillCloudFromFile())
553 printf(
"Error in reading the .ply file\n");
560 if (currentState==STATE_ESTIMATE)
562 if (SurfaceMeshWithBoundingBox *receivedMesh=meshPort.read())
563 fromSurfaceMesh(*receivedMesh);
569 if (writeCloud && outputDir!=
"")
582 if (graspSpecificPoint)
585 pointIndex=findIndexFromCloud(chosenPoint);
586 chosenNormal=vectorFromNormal(pointIndex);
589 insertElement(score,pointIndex);
592 chooseCandidatePoints();
594 Matrix designedOrientation=eye(4,4);
597 string hand=chooseBestPointAndOrientation(winnerIndex,designedOrientation);
599 yarp::sig::Vector tmp=dcm2axis(designedOrientation);
601 if (hand==NO_HAND || tmp.size()==0)
603 currentState=STATE_WAIT;
606 fromFileFinished=
true;
611 chosenOrientation=designedOrientation;
613 if (!graspSpecificPoint)
615 chosenPoint=vectorFromCloud(winnerIndex);
616 chosenNormal=vectorFromNormal(winnerIndex);
620 startVisualization();
622 printf(
"Chosen point: %s\n", chosenPoint.toString().c_str());
623 printf(
"Chosen orientation: %s\n", tmp.toString().c_str());
624 printf(
"Chosen hand: %s\n", chosenHand.c_str());
629 currentState=straight?STATE_GRASP:STATE_WAIT;
632 fromFileFinished=
true;
634 graspSpecificPoint=
false;
635 printf(
"Tot time %g\n", Time::now()-totTime);
639 if (currentState==STATE_GRASP)
642 currentState=STATE_WAIT;
651 yarp::sig::Vector PowerGrasp::assignIndexToAxes(
double &anglez)
653 yarp::sig::Vector indices(3); indices=-1;
654 yarp::sig::Vector refz(3); refz=0.0; refz[2]=1.0;
655 yarp::sig::Vector refy(3); refy=0.0; refy[1]=1.0;
656 yarp::sig::Vector x,y,z;
657 boundingBox.getAxis(x,y,z);
661 double dotzx=fabs(dot(x,refz));
662 double dotzy=fabs(dot(y,refz));
663 double dotzz=fabs(dot(z,refz));
664 double dotyx=fabs(dot(x,refy));
665 double dotyy=fabs(dot(y,refy));
666 double dotyz=fabs(dot(z,refy));
668 if (dotzx>dotzy && dotzx>dotzz)
683 else if (dotzy>dotzx && dotzy>dotzz)
718 void PowerGrasp::manageModality()
720 yarp::sig::Vector center=boundingBox.getCenter();
721 yarp::sig::Vector dim=boundingBox.getDim();
724 yarp::sig::Vector indices=assignIndexToAxes(anglez);
726 yarp::sig::Vector right(3); right=0.0;
727 right[0]=-0.3; right[1]=0.3;
728 yarp::sig::Vector left(3); left=0.0;
729 left[0]=-0.3; left[1]=-0.3;
731 double distRight=norm(right-center);
732 double distLeft=norm(left-center);
734 if (distRight/distLeft>1.8)
736 printf(
"left closer\n");
739 else if (distLeft/distRight>1.8)
741 printf(
"right closer\n");
745 if (dimz<handSize/2 || dimz<fingerSize)
747 printf(
"object too small to be taken from side %g\n", dimz);
748 currentModality=MODALITY_TOP;
750 else if ((dim[indices[2]]/dim[indices[1]]>1.8) && (dim[indices[2]]/dim[indices[0]]>1.8) && (anglez<60.0*M_PI/180.0))
752 printf(
"object very tall, going from side\n");
753 if (distRight/distLeft>1.3 || rightBlocked || rightDisabled || blockRightTmp)
754 currentModality=MODALITY_LEFT;
755 else if (distLeft/distRight>1.3 || leftBlocked || leftDisabled || blockLeftTmp)
756 currentModality=MODALITY_RIGHT;
758 currentModality=(int)(Random::uniform(0,1)+0.5);
760 else if ((dim[indices[0]]/dim[indices[1]]>1.5 && dim[indices[0]]/dim[indices[2]]>1.5) || (dim[indices[1]]/dim[indices[0]]>1.5 && dim[indices[1]]/dim[indices[2]]>1.5))
763 currentModality=MODALITY_CENTER;
768 Random::seed((
int)Time::now()*1000);
769 if (rightDisabled || rightBlocked)
771 int tmp=(int)(Random::uniform(0,1)+0.5);
773 currentModality=MODALITY_TOP;
775 currentModality=MODALITY_LEFT;
777 else if (leftDisabled || leftBlocked)
779 int tmp=(int)(Random::uniform(0,1)+0.5);
781 currentModality=MODALITY_TOP;
783 currentModality=MODALITY_RIGHT;
786 currentModality=(int)(Random::uniform(0,2)+0.5);
788 if (currentModality==MODALITY_LEFT)
790 if (currentModality==MODALITY_RIGHT)
795 yarp::sig::Vector PowerGrasp::computeApproachVector(
const yarp::sig::Vector &chosenPoint)
797 yarp::sig::Vector approachVector(4); approachVector=0.0;
798 yarp::sig::Vector center=boundingBox.getCenter();
800 if (currentModality==MODALITY_LEFT || currentModality==MODALITY_RIGHT)
802 if (chosenHand==LEFT_HAND)
804 approachVector[2]=0.08;
805 approachVector[3]=40.0;
809 approachVector[2]=-0.08;
810 approachVector[3]=-40.0;
813 else if (currentModality==MODALITY_TOP)
816 if (chosenPoint[0]-center[0]<-handSize/2)
817 approachVector[0]=-0.08;
818 if (chosenHand==LEFT_HAND)
820 approachVector[2]=0.08;
821 approachVector[3]=15.0;
825 approachVector[2]=-0.08;
826 approachVector[3]=-15.0;
830 return approachVector;
834 void PowerGrasp::askToGrasp()
836 yarp::sig::Vector approachVector=computeApproachVector(chosenPoint);
838 if (depth2kin.getOutputCount()>0)
840 cmd.addString(
"getPoint");
841 cmd.addString(chosenHand.c_str());
842 cmd.addDouble(chosenPoint[0]);
843 cmd.addDouble(chosenPoint[1]);
844 cmd.addDouble(chosenPoint[2]);
846 depth2kin.write(cmd,reply);
847 if (reply.get(0).asString()==
"ok")
848 chosenPoint=pointFromBottle(reply,1);
851 cmd.clear(); reply.clear();
852 printf(
"Chosen point depth2kin %g %g %g\n", chosenPoint[0],chosenPoint[1],chosenPoint[2]);
854 yarp::sig::Vector tmp=dcm2axis(chosenOrientation);
856 printf(
"dimz %g fingerSize %g\n", dimz, fingerSize);
858 if (currentModality=MODALITY_TOP && dimz<fingerSize)
860 double diff=fingerSize-dimz;
861 chosenPoint+=(chosenNormal*diff);
862 printf(
"dbg: chosen point %s\n", chosenPoint.toString().c_str());
865 if (chosenHand==
"left")
866 chosenPoint+=offsetL;
867 if (chosenHand==
"right")
868 chosenPoint+=offsetR;
870 cmd.addString(
"grasp");
871 Bottle &point=cmd.addList();
872 point.addDouble(chosenPoint[0]);
873 point.addDouble(chosenPoint[1]);
874 point.addDouble(chosenPoint[2]);
875 point.addDouble(tmp[0]);
876 point.addDouble(tmp[1]);
877 point.addDouble(tmp[2]);
878 point.addDouble(tmp[3]);
879 cmd.addString(chosenHand.c_str());
880 Bottle &approach=cmd.addList();
881 approach.addString(
"approach");
882 Bottle &vector=approach.addList();
883 vector.addDouble(approachVector[0]);
884 vector.addDouble(approachVector[1]);
885 vector.addDouble(approachVector[2]);
886 vector.addDouble(approachVector[3]);
888 if (areCmdPort.getOutputCount()>0)
890 areCmdPort.write(cmd,reply);
891 if (reply.get(0).asString()==ACK)
898 void PowerGrasp::resetBools()
909 yarp::sig::Vector PowerGrasp::pointFromBottle(
const Bottle &bot,
const int index)
911 yarp::sig::Vector vector(3);
912 vector[0]=bot.get(index).asDouble();
913 vector[1]=bot.get(index+1).asDouble();
914 vector[2]=bot.get(index+2).asDouble();
920 bool PowerGrasp::get3DPoint(
const yarp::sig::Vector &point2D, yarp::sig::Vector &point3D)
922 Bottle cmd; Bottle reply;
923 cmd.clear(); reply.clear();
924 cmd.addString(
"get");
925 cmd.addString(
"point");
926 cmd.addDouble(point2D[0]);
927 cmd.addDouble(point2D[1]);
929 if (reconstructionPort.getOutputCount()>0)
930 reconstructionPort.write(cmd,reply);
932 if (reply.size()>0 && reply.get(0).asString()!=NACK)
934 point3D=pointFromBottle(reply,0);
942 bool PowerGrasp::respond(
const Bottle& command, Bottle& reply)
946 string tag_0=command.get(0).asString().c_str();
949 if (command.size()<3)
950 reply.addString(
"command not recognized");
953 string tag_1=command.get(1).asString().c_str();
954 if (tag_1==
"visualization")
956 visualize=(command.get(2).asString()==
"on");
957 reply.addString(ACK);
961 if (command.size()>1)
963 posx=command.get(1).asInt();
964 visualizationThread->setPosition(posx,posy);
965 reply.addString(ACK);
970 if (command.size()>1)
972 posy=command.get(1).asInt();
973 visualizationThread->setPosition(posx,posy);
974 reply.addString(ACK);
979 if (command.size()>1)
981 sizex=command.get(1).asInt();
982 visualizationThread->setSize(sizex,sizey);
983 reply.addString(ACK);
988 if (command.size()>1)
990 sizey=command.get(1).asInt();
991 visualizationThread->setSize(sizex,sizey);
992 reply.addString(ACK);
995 else if (tag_1==
"train")
997 if (command.get(2).asString()==
"on")
1000 testWithLearning=
false;
1004 reply.addString(ACK);
1006 else if (tag_1==
"testWithSVM")
1008 if (command.get(2).asString()==
"on")
1010 if (testWithLearningEnabled)
1012 testWithLearning=
true;
1016 printf(
"SVM machine not set\n");
1019 testWithLearning=
false;
1020 reply.addString(ACK);
1022 else if (tag_1==
"offsetR")
1024 if (command.size()<5)
1025 reply.addString(
"nack, check offset size");
1028 offsetR=pointFromBottle(command,2);
1029 reply.addString(ACK);
1032 else if (tag_1==
"offsetL")
1034 if (command.size()<5)
1035 reply.addString(
"nack, check offset size");
1038 offsetL=pointFromBottle(command,2);
1039 reply.addString(ACK);
1042 else if (tag_1==
"modality")
1044 if (command.get(2).asString()==
"right")
1045 modality=MODALITY_RIGHT;
1046 else if (command.get(2).asString()==
"left")
1047 modality=MODALITY_LEFT;
1048 else if (command.get(2).asString()==
"center")
1049 modality=MODALITY_CENTER;
1050 else if (command.get(2).asString()==
"top")
1051 modality=MODALITY_TOP;
1053 modality=MODALITY_AUTO;
1054 reply.addString(ACK);
1056 else if (tag_1==
"filter")
1058 filterCloud=(command.get(2).asString()==
"on");
1059 reply.addString(ACK);
1061 else if (tag_1==
"write")
1063 writeCloud=(command.get(2).asString()==
"on");
1064 reply.addString(ACK);
1068 else if (tag_0==
"help")
1070 reply.addString(
"set visualization on/off");
1071 reply.addString(
"set x");
1072 reply.addString(
"set y");
1073 reply.addString(
"set w");
1074 reply.addString(
"set h");
1075 reply.addString(
"set train on/off");
1076 reply.addString(
"set testWithSVM on/off");
1077 reply.addString(
"set offsetL x y z");
1078 reply.addString(
"set offsetR x y z");
1079 reply.addString(
"set modality right/left/top/center");
1080 reply.addString(
"set filter on/off");
1081 reply.addString(
"set write on/off");
1082 reply.addString(
"block right/left");
1083 reply.addString(
"unblock right/left");
1084 reply.addString(
"grasp (x y) [wait]");
1085 reply.addString(
"go");
1086 reply.addString(
"dont");
1087 reply.addString(
"isGrasped");
1089 else if (tag_0==
"go")
1093 currentState=STATE_GRASP;
1096 reply.addString(ACK);
1099 else if (tag_0==
"block")
1101 if (command.size()>=2)
1103 if (command.get(1).asString()==
"right")
1107 reply.addString(ACK);
1110 else if (tag_0==
"unblock")
1112 if (command.size()>=2)
1114 if (command.get(1).asString()==
"right")
1118 reply.addString(ACK);
1121 else if (tag_0==
"isGrasped")
1122 reply.addString(grasped?ACK:NACK);
1123 else if (tag_0==
"dont")
1126 currentState=STATE_WAIT;
1127 reply.addString(ACK);
1129 else if (tag_0==
"grasp")
1131 if ((currentState!=STATE_ESTIMATE) && (currentState!=STATE_GRASP))
1133 if (Bottle *pos=command.get(1).asList())
1137 chosenPixel[0]=pos->get(0).asInt();
1138 chosenPixel[1]=pos->get(1).asInt();
1141 cmd1.addInt(chosenPixel[0]);
1142 cmd1.addInt(chosenPixel[1]);
1144 if (reconstructionPort.getOutputCount()>0)
1145 reconstructionPort.write(cmd1,rep1);
1147 if (visualizationThread->isRunning())
1148 visualizationThread->stop();
1152 if (train && (command.size()>1))
1153 currentCurvature=(float)command.get(1).asDouble();
1157 if (pos->get(2).asString()==
"point")
1159 if (get3DPoint(chosenPixel,chosenPoint))
1160 graspSpecificPoint=
true;
1163 reply.addString(NACK);
1170 cmd2.addString(
"3Drec");
1172 cmd2.addString(
"visualize");
1174 if (reconstructionPort.getOutputCount()>0)
1175 reconstructionPort.write(cmd2,rep2);
1177 if ((rep2.size()>0) && (rep2.get(0).asString()==ACK))
1179 currentState=STATE_ESTIMATE;
1181 if (command.size()>2)
1182 straight=(command.get(2).asString()!=
"wait");
1191 reply.addString(NACK);
1192 reply.addString(
"no_result");
1197 reply.addString(NACK);
1198 reply.addString(
"too_far");
1202 reply.addString(ACK);
1209 if (reply.size()==0)
1210 reply.addString(NACK);
1216 yarp::sig::Vector PowerGrasp::findBiggestAxis(
int &ind)
1218 yarp::sig::Vector biggestAxis;
1219 yarp::sig::Vector vx,vy,vz;
1220 boundingBox.getAxis(vx,vy,vz);
1222 double normx=norm(vx);
1223 double normy=norm(vy);
1224 double normz=norm(vz);
1227 if (normx>normy && normx>normz)
1232 else if (normy>normx && normy>normz)
1243 biggestAxis/=norm(biggestAxis);
1248 string PowerGrasp::chooseBestPointAndOrientation(
int &winnerIndex, yarp::sig::Matrix &designedOrientation)
1250 yarp::sig::Vector center(3), eePos(3);
1251 yarp::sig::Vector pyRight(3), pxRight(3), pyLeft(3), pxLeft(3);
1252 yarp::sig::Vector pointNormal(3), normalRight(3), normalLeft(3);
1253 yarp::sig::Vector tmpRight(3), tmpLeft(3);
1254 yarp::sig::Vector xhandaxisRight(3), xhandaxisLeft(3);
1255 Matrix orientationRight, orientationLeft;
1256 Matrix tmpOrientationRight, tmpOrientationLeft;
1257 double rightMan,leftMan;
1258 double bestRightMan=0.0;
1259 double bestLeftMan=0.0;
1263 yarp::sig::Vector x(3);
1268 string hand=NO_HAND;
1271 yarp::sig::Vector biggestAxis=findBiggestAxis(indB);
1275 orientationThreadRight->reset();
1277 orientationThreadRight->preAskForPose();
1281 orientationThreadLeft->reset();
1283 orientationThreadLeft->preAskForPose();
1285 for (
int i=0; i<rankScores.size(); i++)
1289 pointNormal=vectorFromNormal(rankIndices[i]);
1290 normalRight=-1.0*pointNormal;
1291 normalLeft=pointNormal;
1294 tmpRight=cross(x,normalRight);
1295 pxRight=cross(normalRight,tmpRight);
1296 pxRight=pxRight/norm(pxRight);
1299 tmpLeft=cross(x,normalLeft);
1300 pxLeft=cross(normalLeft,tmpLeft);
1301 pxLeft=pxLeft/norm(pxLeft);
1303 pyRight=cross(normalRight,pxRight);
1304 pyRight=pyRight/norm(pyRight);
1306 pyLeft=cross(normalLeft,pxLeft);
1307 pyLeft=pyLeft/norm(pyLeft);
1309 center=vectorFromCloud(rankIndices[i])+pointNormal;
1310 eePos=vectorFromCloud(rankIndices[i]);
1312 yarp::sig::Vector tmpBiggest=biggestAxis;
1314 if (!rightBlocked && !blockRightTmp && !rightDisabled)
1316 orientationThreadRight->setInfo(eePos,pxRight,pyRight,normalRight,center,tmpBiggest);
1317 orientationThreadRight->resume();
1319 if (!leftBlocked && !blockLeftTmp && !leftDisabled)
1321 orientationThreadLeft->setInfo(eePos,pxLeft,pyLeft,normalLeft,center,tmpBiggest);
1322 orientationThreadLeft->resume();
1327 while (!orientationThreadRight->checkDone())
1335 while (!orientationThreadLeft->checkDone())
1341 if (!rightBlocked && !blockRightTmp && !rightDisabled)
1343 orientationThreadRight->getBestManip(rightMan,tmpOrientationRight);
1344 if (rightMan>bestRightMan)
1346 bestRightMan=rightMan;
1347 orientationRight=tmpOrientationRight;
1352 if (!leftBlocked && !blockLeftTmp && !leftDisabled)
1354 orientationThreadLeft->getBestManip(leftMan,tmpOrientationLeft);
1355 if (leftMan>bestLeftMan)
1357 bestLeftMan=leftMan;
1358 orientationLeft=tmpOrientationLeft;
1364 bool noResultR=
true;
1365 bool noResultL=
true;
1366 if (!rightBlocked && !blockRightTmp && !rightDisabled)
1369 orientationThreadRight->postAskForPose();
1370 noResultR=orientationThreadRight->getResult();
1372 if (!leftBlocked && !blockLeftTmp && !leftDisabled)
1375 orientationThreadLeft->postAskForPose();
1376 noResultL=orientationThreadLeft->getResult();
1379 if (noResultR && noResultL)
1384 if (bestLeftMan==0.0 && bestRightMan==0.0)
1390 if (rightBlocked || blockRightTmp || bestLeftMan>bestRightMan)
1392 winnerIndex=rankIndices[leftIndex];
1393 designedOrientation=orientationLeft;
1397 if (leftBlocked || blockLeftTmp || bestRightMan>bestLeftMan)
1399 winnerIndex=rankIndices[rightIndex];
1400 designedOrientation=orientationRight;
1408 void PowerGrasp::addPointCloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_in)
1413 for (
size_t j = 0; j < cloud_in->points.size (); ++j)
1415 PointXYZRGB pointrgb=cloud_in->points[j];
1416 pcl::PointXYZ point;
1420 cloudxyz->push_back(point);
1421 cloud->push_back(pointrgb);
1426 double PowerGrasp::getPeriod()
1432 double PowerGrasp::scoreFunction(
const int index)
1436 yarp::sig::Vector point=vectorFromCloud(index);
1437 yarp::sig::Vector center=boundingBox.getCenter();
1439 if (point[2]<center[2])
1442 yarp::sig::Vector normal=vectorFromNormal(index);
1443 float curvature=normals->at(index).curvature;
1445 yarp::sig::Vector x,y,z;
1446 boundingBox.getAxis(x,y,z);
1447 x/=norm(x); y/=norm(y); z/=norm(z);
1449 yarp::sig::Vector dim=boundingBox.getDim();
1459 for (
int i=0; i<boundingBox.getCorners().size(); i++)
1461 iCub::data3D::PointXYZ p=boundingBox.getCorners().at(i);
1462 yarp::sig::Vector tmp(3);
1466 if (norm(tmp-point)>minDim/2)
1474 return exp(-(fabs(curvature-currentCurvature)/maxCurvature))/2;
1476 if (testWithLearning)
1478 Vector in(1,scalerIn.transform(curvature));
1479 Prediction prediction=machine.predict(in);
1480 Vector out=prediction.getPrediction();
1481 score+=scalerOut.unTransform(out[0]);
1484 score+=exp(-(fabs(curvature-currentCurvature)/maxCurvature))/2;
1486 if (currentModality==MODALITY_TOP)
1488 if (point[2]-center[2]>0.0)
1489 return score+fabs(point[2]-center[2])/dimz;
1493 else if (currentModality==MODALITY_RIGHT)
1495 if (point[1]-center[1]>0.0)
1497 yarp::sig::Vector tmp=center;
1498 tmp[1]=center[1]+(dimy/2);
1499 return score+exp(-(norm(point-tmp)/dimy))/2;
1504 else if (currentModality==MODALITY_LEFT)
1506 if (point[1]-center[1]<0.0)
1508 yarp::sig::Vector tmp=center;
1509 tmp[1]=center[1]-(dimy/2);
1510 return score+exp(-(norm(point-tmp)/dimy))/2;
1517 yarp::sig::Vector tmp(3);
1519 tmp[2]=center[2]+(dimz/2);
1521 return score+=exp(-(norm(point-tmp)/dimz))/2;
1526 void PowerGrasp::insertElement(
const double score,
const int index)
1528 if (rankScores.size()==0)
1530 rankScores.push_back(score);
1531 rankIndices.push_back(index);
1533 else if (rankScores.size()<numberOfBestPoints)
1535 bool assigned=
false;
1536 std::vector<int>::iterator itind=rankIndices.begin();
1537 for (std::vector<double>::iterator itsc = rankScores.begin(); itsc!=rankScores.end(); itsc++)
1541 rankScores.insert(itsc,score);
1542 rankIndices.insert(itind,index);
1550 rankScores.push_back(score);
1551 rankIndices.push_back(index);
1556 if (rankScores[rankScores.size()-1]>score)
1560 else if (rankScores[0]<score)
1562 std::vector<double>::iterator itsc=rankScores.begin();
1563 std::vector<int>::iterator itind=rankIndices.begin();
1564 rankScores.insert(itsc,score);
1565 rankIndices.insert(itind,index);
1566 rankScores.pop_back();
1567 rankIndices.pop_back();
1571 std::vector<int>::iterator itind=rankIndices.begin();
1572 for (std::vector<double>::iterator itsc = rankScores.begin(); itsc!=rankScores.end(); itsc++)
1576 rankScores.insert(itsc,score);
1577 rankIndices.insert(itind,index);
1578 rankScores.pop_back();
1579 rankIndices.pop_back();
1589 bool PowerGrasp::normalPointingOut(
const int index,
const yarp::sig::Vector ¢er)
1591 yarp::sig::Vector p=vectorFromCloud(index);
1592 yarp::sig::Vector n=vectorFromNormal(index);
1594 yarp::sig::Vector fromCenter=(center-p)/norm(center-p);
1597 return (dot(n,fromCenter)<0);
1601 void PowerGrasp::computeDim()
1607 for (
int i=0; i<cloudxyz->size(); i++)
1609 pcl::PointXYZ point=cloudxyz->at(i);
1621 printf(
"maxz %g minz %g max-min %g\n", maxz, minz, maxz-minz);
iCub::data3D::BoundingBox getMinimumBoundingBox(pcl::PointCloud< pcl::PointXYZRGB >::Ptr cloud)
Given a point cloud (defined in the Point Cloud Library), it computes the minimum enclosing bounding ...