Visual Servoing Platform  version 3.4.0
servoMomentPolygon.cpp
1 /****************************************************************************
2  *
3  * ViSP, open source Visual Servoing Platform software.
4  * Copyright (C) 2005 - 2019 by Inria. All rights reserved.
5  *
6  * This software is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * See the file LICENSE.txt at the root directory of this source
11  * distribution for additional information about the GNU GPL.
12  *
13  * For using ViSP with software that can not be combined with the GNU
14  * GPL, please contact Inria about acquiring a ViSP Professional
15  * Edition License.
16  *
17  * See http://visp.inria.fr for more information.
18  *
19  * This software was developed at:
20  * Inria Rennes - Bretagne Atlantique
21  * Campus Universitaire de Beaulieu
22  * 35042 Rennes Cedex
23  * France
24  *
25  * If you have questions regarding the use of this file, please contact
26  * Inria at visp@inria.fr
27  *
28  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
29  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
30  *
31  * Description:
32  * Example of visual servoing with moments using a polygon as object container
33  *
34  * Authors:
35  * Filip Novotny
36  *
37  *****************************************************************************/
38 
44 #include <iostream>
45 #include <visp3/core/vpCameraParameters.h>
46 #include <visp3/core/vpConfig.h>
47 #include <visp3/core/vpDebug.h>
48 #include <visp3/core/vpHomogeneousMatrix.h>
49 #include <visp3/core/vpIoTools.h>
50 #include <visp3/core/vpMath.h>
51 #include <visp3/core/vpMomentCommon.h>
52 #include <visp3/core/vpMomentDatabase.h>
53 #include <visp3/core/vpMomentObject.h>
54 #include <visp3/core/vpPlane.h>
55 #include <visp3/gui/vpDisplayD3D.h>
56 #include <visp3/gui/vpDisplayGDI.h>
57 #include <visp3/gui/vpDisplayGTK.h>
58 #include <visp3/gui/vpDisplayOpenCV.h>
59 #include <visp3/gui/vpDisplayX.h>
60 #include <visp3/gui/vpPlot.h>
61 #include <visp3/robot/vpSimulatorAfma6.h>
62 #include <visp3/visual_features/vpFeatureBuilder.h>
63 #include <visp3/visual_features/vpFeatureMomentCommon.h>
64 #include <visp3/visual_features/vpFeaturePoint.h>
65 #include <visp3/vs/vpServo.h>
66 
67 #if !defined(_WIN32) && !defined(VISP_HAVE_PTHREAD)
68 // Robot simulator used in this example is not available
69 int main()
70 {
71  std::cout << "Can't run this example since vpSimulatorAfma6 capability is "
72  "not available."
73  << std::endl;
74  std::cout << "You should install pthread third-party library." << std::endl;
75  return EXIT_SUCCESS;
76 }
77 // No display available
78 #elif !defined(VISP_HAVE_X11) && !defined(VISP_HAVE_OPENCV) && !defined(VISP_HAVE_GDI) && !defined(VISP_HAVE_D3D9) && \
79  !defined(VISP_HAVE_GTK)
80 int main()
81 {
82  std::cout << "Can't run this example since no display capability is available." << std::endl;
83  std::cout << "You should install one of the following third-party library: "
84  "X11, OpenCV, GDI, GTK."
85  << std::endl;
86  return EXIT_SUCCESS;
87 }
88 #else
89 
90 #ifndef DOXYGEN_SHOULD_SKIP_THIS
91 class servoMoment
92 {
93 public:
94  servoMoment()
95  : m_width(640), m_height(480), m_cMo(), m_cdMo(), m_robot(false), m_Iint(m_height, m_width, 255), m_task(), m_cam(),
96  m_error(0), m_imsim(), m_interaction_type(), m_src(6), m_dst(6), m_moments(NULL), m_momentsDes(NULL),
97  m_featureMoments(NULL), m_featureMomentsDes(NULL), m_displayInt(NULL)
98  {
99  }
100  ~servoMoment()
101  {
102 #ifdef VISP_HAVE_DISPLAY
103  if (m_displayInt) {
104  delete m_displayInt;
105  }
106 #endif
107  delete m_moments;
108  delete m_momentsDes;
109  delete m_featureMoments;
110  delete m_featureMomentsDes;
111  }
112 
113  void initScene()
114  {
115  std::vector<vpPoint> src_pts;
116  std::vector<vpPoint> dst_pts;
117 
118  double x[5] = {0.2, 0.2, -0.2, -0.2, 0.2};
119  double y[5] = {-0.1, 0.1, 0.1, -0.1, -0.1};
120  int nbpoints = 4;
121 
122  for (int i = 0; i < nbpoints; i++) {
123  vpPoint p(x[i], y[i], 0.0);
124  p.track(m_cMo);
125  src_pts.push_back(p);
126  }
127 
128  m_src.setType(vpMomentObject::DENSE_POLYGON);
129  m_src.fromVector(src_pts);
130  for (int i = 0; i < nbpoints; i++) {
131  vpPoint p(x[i], y[i], 0.0);
132  p.track(m_cdMo);
133  dst_pts.push_back(p);
134  }
135  m_dst.setType(vpMomentObject::DENSE_POLYGON);
136  m_dst.fromVector(dst_pts);
137  }
138 
139  void refreshScene(vpMomentObject &obj)
140  {
141  double x[5] = {0.2, 0.2, -0.2, -0.2, 0.2};
142  double y[5] = {-0.1, 0.1, 0.1, -0.1, -0.1};
143  int nbpoints = 5;
144  std::vector<vpPoint> cur_pts;
145 
146  for (int i = 0; i < nbpoints; i++) {
147  vpPoint p(x[i], y[i], 0.0);
148  p.track(m_cMo);
149  cur_pts.push_back(p);
150  }
151  obj.fromVector(cur_pts);
152  }
153 
154  void init(vpHomogeneousMatrix &cMo, vpHomogeneousMatrix &cdMo)
155  {
156  m_cMo = cMo; // init source matrix
157  m_cdMo = cdMo; // init destination matrix
158 
159  m_interaction_type = vpServo::CURRENT; // use interaction matrix for current position
160 
161 #ifdef VISP_HAVE_DISPLAY
162  // init the right display
163 #if defined VISP_HAVE_X11
164  m_displayInt = new vpDisplayX;
165 #elif defined VISP_HAVE_OPENCV
166  m_displayInt = new vpDisplayOpenCV;
167 #elif defined VISP_HAVE_GDI
168  m_displayInt = new vpDisplayGDI;
169 #elif defined VISP_HAVE_D3D9
170  m_displayInt = new vpDisplayD3D;
171 #elif defined VISP_HAVE_GTK
172  m_displayInt = new vpDisplayGTK;
173 #endif
174  m_displayInt->init(m_Iint, 50, 50, "Visual servoing with moments");
175 #endif
176 
177  paramRobot(); // set up robot parameters
178 
179  m_task.setServo(vpServo::EYEINHAND_CAMERA);
180  initScene(); // initialize graphical scene (for interface)
181  initFeatures(); // initialize moment features
182  }
183 
184  void initFeatures()
185  {
186  // A,B,C parameters of source and destination plane
187  double A;
188  double B;
189  double C;
190  double Ad;
191  double Bd;
192  double Cd;
193  // init main object: using moments up to order 6
194 
195  // Initializing values from regular plane (with ax+by+cz=d convention)
196  vpPlane pl;
197  pl.setABCD(0, 0, 1.0, 0);
198  pl.changeFrame(m_cMo);
199  planeToABC(pl, A, B, C);
200 
201  pl.setABCD(0, 0, 1.0, 0);
202  pl.changeFrame(m_cdMo);
203  planeToABC(pl, Ad, Bd, Cd);
204 
205  // extracting initial position (actually we only care about Zdst)
207  m_cdMo.extract(vec);
208 
211  // don't need to be specific, vpMomentCommon automatically loads
212  // Xg,Yg,An,Ci,Cj,Alpha moments
214  vpMomentCommon::getAlpha(m_dst), vec[2]);
215  m_momentsDes = new vpMomentCommon(vpMomentCommon::getSurface(m_dst), vpMomentCommon::getMu3(m_dst),
216  vpMomentCommon::getAlpha(m_dst), vec[2]);
217  // same thing with common features
218  m_featureMoments = new vpFeatureMomentCommon(*m_moments);
219  m_featureMomentsDes = new vpFeatureMomentCommon(*m_momentsDes);
220 
221  m_moments->updateAll(m_src);
222  m_momentsDes->updateAll(m_dst);
223 
224  m_featureMoments->updateAll(A, B, C);
225  m_featureMomentsDes->updateAll(Ad, Bd, Cd);
226 
227  // setup the interaction type
228  m_task.setInteractionMatrixType(m_interaction_type);
231  m_task.addFeature(m_featureMoments->getFeatureGravityNormalized(),
232  m_featureMomentsDes->getFeatureGravityNormalized());
233  m_task.addFeature(m_featureMoments->getFeatureAn(), m_featureMomentsDes->getFeatureAn());
234  // the moments are different in case of a symmetric object
235  m_task.addFeature(m_featureMoments->getFeatureCInvariant(), m_featureMomentsDes->getFeatureCInvariant(),
236  (1 << 10) | (1 << 11));
237  m_task.addFeature(m_featureMoments->getFeatureAlpha(), m_featureMomentsDes->getFeatureAlpha());
238 
239  m_task.setLambda(0.4);
240  }
241 
242  void execute(unsigned int nbIter)
243  {
244  vpPlot ViSP_plot;
245  init_visp_plot(ViSP_plot); // Initialize plot object
246 
247  // init main object: using moments up to order 5
248  vpMomentObject obj(6);
249  // setting object type (disrete, continuous[form polygon])
251 
252  std::cout << "Display task information " << std::endl;
253  m_task.print();
254 
255  vpDisplay::display(m_Iint);
256  m_robot.getInternalView(m_Iint);
257  vpDisplay::flush(m_Iint);
258  unsigned int iter = 0;
259 
261  while (iter++ < nbIter) {
262  vpColVector v;
263  double t = vpTime::measureTimeMs();
264  // get the cMo
265  m_cMo = m_robot.get_cMo();
266  // setup the plane in A,B,C style
267  vpPlane pl;
268  double A, B, C;
269  pl.setABCD(0, 0, 1.0, 0);
270  pl.changeFrame(m_cMo);
271  planeToABC(pl, A, B, C);
272 
273  // track points, draw points and add refresh our object
274  refreshScene(obj);
275  // this is the most important thing to do: update our moments
276  m_moments->updateAll(obj);
277  // and update our features. Do it in that order. Features need to use the
278  // information computed by moments
279  m_featureMoments->updateAll(A, B, C);
280 
281  vpDisplay::display(m_Iint);
282  m_robot.getInternalView(m_Iint);
283  vpDisplay::flush(m_Iint);
284 
285  if (iter == 1) {
286  vpDisplay::displayText(m_Iint, 20, 20, "Click to start servoing", vpColor::red);
287  vpDisplay::flush(m_Iint);
288  vpDisplay::getClick(m_Iint);
289  }
290  v = m_task.computeControlLaw();
291 
292  m_robot.setVelocity(vpRobot::CAMERA_FRAME, v);
293 
294  ViSP_plot.plot(0, iter, v);
295  ViSP_plot.plot(1, iter, vpPoseVector(m_cMo)); // Plot the velocities
296  ViSP_plot.plot(2, iter, m_task.getError()); // cMo as translations and theta_u
297 
298  m_error = (m_task.getError()).sumSquare();
299 
300  vpDisplay::displayText(m_Iint, 20, 20, "Click to stop visual servo...", vpColor::red);
301  if (vpDisplay::getClick(m_Iint, false)) {
302  break;
303  }
304  vpDisplay::flush(m_Iint);
305  vpTime::wait(t, 10);
306  }
307 
308  vpDisplay::display(m_Iint);
309  m_robot.getInternalView(m_Iint);
310  vpDisplay::displayText(m_Iint, 20, 20, "Click to quit...", vpColor::red);
311  vpDisplay::flush(m_Iint);
312  vpDisplay::getClick(m_Iint);
313  }
314 
315  void setInteractionMatrixType(vpServo::vpServoIteractionMatrixType type) { m_interaction_type = type; }
316 
317  double error() { return m_error; }
318 
319  void removeJointLimits(vpSimulatorAfma6 &robot)
320  {
321  vpColVector limMin(6);
322  vpColVector limMax(6);
323  limMin[0] = vpMath::rad(-3600);
324  limMin[1] = vpMath::rad(-3600);
325  limMin[2] = vpMath::rad(-3600);
326  limMin[3] = vpMath::rad(-3600);
327  limMin[4] = vpMath::rad(-3600);
328  limMin[5] = vpMath::rad(-3600);
329 
330  limMax[0] = vpMath::rad(3600);
331  limMax[1] = vpMath::rad(3600);
332  limMax[2] = vpMath::rad(3600);
333  limMax[3] = vpMath::rad(3600);
334  limMax[4] = vpMath::rad(3600);
335  limMax[5] = vpMath::rad(3600);
336 
337  robot.setJointLimit(limMin, limMax);
338  }
339 
340  void planeToABC(vpPlane &pl, double &A, double &B, double &C)
341  {
342  if (fabs(pl.getD()) < std::numeric_limits<double>::epsilon()) {
343  std::cout << "Invalid position:" << std::endl;
344  std::cout << m_cMo << std::endl;
345  std::cout << "Cannot put plane in the form 1/Z=Ax+By+C." << std::endl;
346  throw vpException(vpException::divideByZeroError, "invalid position!");
347  }
348  A = -pl.getA() / pl.getD();
349  B = -pl.getB() / pl.getD();
350  C = -pl.getC() / pl.getD();
351  }
352 
353  void paramRobot()
354  {
355  /*Initialise the robot and especially the camera*/
357  m_robot.setCurrentViewColor(vpColor(150, 150, 150));
358  m_robot.setDesiredViewColor(vpColor(200, 200, 200));
359  m_robot.setRobotState(vpRobot::STATE_VELOCITY_CONTROL);
360  removeJointLimits(m_robot);
362  /*Initialise the position of the object relative to the pose of the robot's
363  * camera*/
364  m_robot.initialiseObjectRelativeToCamera(m_cMo);
365 
366  /*Set the desired position (for the displaypart)*/
367  m_robot.setDesiredCameraPosition(m_cdMo);
368  m_robot.getCameraParameters(m_cam, m_Iint);
369  }
370 
371  void init_visp_plot(vpPlot &ViSP_plot)
372  {
373  /* -------------------------------------
374  * Initialize ViSP Plotting
375  * -------------------------------------
376  */
377  const unsigned int NbGraphs = 3; // No. of graphs
378  const unsigned int NbCurves_in_graph[NbGraphs] = {6, 6, 6}; // Curves in each graph
379 
380  ViSP_plot.init(NbGraphs, 800, 800, 100 + static_cast<int>(m_width), 50, "Visual Servoing results...");
381 
382  vpColor Colors[6] = {// Colour for s1, s2, s3, in 1st plot
384 
385  for (unsigned int p = 0; p < NbGraphs; p++) {
386  ViSP_plot.initGraph(p, NbCurves_in_graph[p]);
387  for (unsigned int c = 0; c < NbCurves_in_graph[p]; c++)
388  ViSP_plot.setColor(p, c, Colors[c]);
389  }
390 
391  ViSP_plot.setTitle(0, "Robot velocities");
392  ViSP_plot.setLegend(0, 0, "v_x");
393  ViSP_plot.setLegend(0, 1, "v_y");
394  ViSP_plot.setLegend(0, 2, "v_z");
395  ViSP_plot.setLegend(0, 3, "w_x");
396  ViSP_plot.setLegend(0, 4, "w_y");
397  ViSP_plot.setLegend(0, 5, "w_z");
398 
399  ViSP_plot.setTitle(1, "Camera pose cMo");
400  ViSP_plot.setLegend(1, 0, "tx");
401  ViSP_plot.setLegend(1, 1, "ty");
402  ViSP_plot.setLegend(1, 2, "tz");
403  ViSP_plot.setLegend(1, 3, "tu_x");
404  ViSP_plot.setLegend(1, 4, "tu_y");
405  ViSP_plot.setLegend(1, 5, "tu_z");
406 
407  ViSP_plot.setTitle(2, "Error in visual features: ");
408  ViSP_plot.setLegend(2, 0, "x_n");
409  ViSP_plot.setLegend(2, 1, "y_n");
410  ViSP_plot.setLegend(2, 2, "a_n");
411  ViSP_plot.setLegend(2, 3, "sx");
412  ViSP_plot.setLegend(2, 4, "sy");
413  ViSP_plot.setLegend(2, 5, "alpha");
414  }
415 
416 protected:
417  // start and destination positioning matrices
418  unsigned int m_width;
419  unsigned int m_height;
420 
421  // start and destination positioning matrices
422  vpHomogeneousMatrix m_cMo;
423  vpHomogeneousMatrix m_cdMo;
424 
425  vpSimulatorAfma6 m_robot; // robot used in this simulation
426  vpImage<vpRGBa> m_Iint; // internal image used for interface display
427  vpServo m_task; // servoing task
428  vpCameraParameters m_cam; // robot camera parameters
429  double m_error; // current error
430  vpImageSimulator m_imsim; // image simulator used to simulate the perspective-projection camera
431 
432  vpServo::vpServoIteractionMatrixType m_interaction_type; // current or desired
433  // source and destination objects for moment manipulation
434  vpMomentObject m_src;
435  vpMomentObject m_dst;
436 
437  // moment sets and their corresponding features
438  vpMomentCommon *m_moments;
439  vpMomentCommon *m_momentsDes;
440  vpFeatureMomentCommon *m_featureMoments;
441  vpFeatureMomentCommon *m_featureMomentsDes;
442 
443  vpDisplay *m_displayInt;
444 };
445 #endif // #ifndef DOXYGEN_SHOULD_SKIP_THIS
446 
447 int main()
448 {
449  try { // intial pose
450  vpHomogeneousMatrix cMo(-0.1, -0.1, 1.5, -vpMath::rad(20), -vpMath::rad(20), -vpMath::rad(30));
451  // Desired pose
453 
454  servoMoment servo;
455  // init and run the simulation
456  servo.init(cMo, cdMo);
457  servo.execute(1500);
458  return EXIT_SUCCESS;
459  } catch (const vpException &e) {
460  std::cout << "Catch an exception: " << e << std::endl;
461  return EXIT_FAILURE;
462  }
463 }
464 
465 #endif
VISP_EXPORT int wait(double t0, double t)
Definition: vpTime.cpp:173
Class that defines generic functionnalities for display.
Definition: vpDisplay.h:177
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
Implementation of an homogeneous matrix and operations on such kind of matrices.
void init(unsigned int nbGraph, unsigned int height=700, unsigned int width=700, int x=-1, int y=-1, const std::string &title="")
Definition: vpPlot.cpp:100
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:128
Class to define RGB colors available for display functionnalities.
Definition: vpColor.h:157
static void displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:150
This class allows to access common vpFeatureMoments in a pre-filled database.
error that can be emited by ViSP classes.
Definition: vpException.h:71
void setJointLimit(const vpColVector &limitMin, const vpColVector &limitMax)
Class for generic objects.
static const vpColor green
Definition: vpColor.h:220
void setLegend(unsigned int graphNum, unsigned int curveNum, const std::string &legend)
Definition: vpPlot.cpp:547
static void flush(const vpImage< unsigned char > &I)
VISP_EXPORT double measureTimeMs()
Definition: vpTime.cpp:126
static const vpColor red
Definition: vpColor.h:217
Class that defines a 3D point in the object frame and allows forward projection of a 3D point in the ...
Definition: vpPoint.h:81
static const vpColor orange
Definition: vpColor.h:227
Display for windows using Direct3D 3rd party. Thus to enable this class Direct3D should be installed...
Definition: vpDisplayD3D.h:106
Initialize the velocity controller.
Definition: vpRobot.h:66
static const vpColor cyan
Definition: vpColor.h:226
void changeFrame(const vpHomogeneousMatrix &cMo)
Definition: vpPlane.cpp:354
static std::vector< double > getMu3(vpMomentObject &object)
static void display(const vpImage< unsigned char > &I)
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
Generic class defining intrinsic camera parameters.
void init(vpImage< unsigned char > &I, int win_x=-1, int win_y=-1, const std::string &win_title="")
Class which enables to project an image in the 3D space and get the view of a virtual camera...
Simulator of Irisa&#39;s gantry robot named Afma6.
void setTitle(unsigned int graphNum, const std::string &title)
Definition: vpPlot.cpp:498
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:134
void plot(unsigned int graphNum, unsigned int curveNum, double x, double y)
Definition: vpPlot.cpp:286
vpServoIteractionMatrixType
Definition: vpServo.h:181
void setABCD(double a, double b, double c, double d)
Definition: vpPlane.h:90
void fromVector(std::vector< vpPoint > &points)
static double getSurface(vpMomentObject &object)
static double rad(double deg)
Definition: vpMath.h:110
void initGraph(unsigned int graphNum, unsigned int curveNbr)
Definition: vpPlot.cpp:206
This class initializes and allows access to commonly used moments.
static double getAlpha(vpMomentObject &object)
Implementation of column vector and the associated operations.
Definition: vpColVector.h:130
Implementation of a pose vector and operations on poses.
Definition: vpPoseVector.h:151
double getB() const
Definition: vpPlane.h:104
void setType(vpObjectType input_type)
double getA() const
Definition: vpPlane.h:102
This class enables real time drawing of 2D or 3D graphics. An instance of the class open a window whi...
Definition: vpPlot.h:115
double getC() const
Definition: vpPlane.h:106
This class defines the container for a plane geometrical structure.
Definition: vpPlane.h:58
void setColor(unsigned int graphNum, unsigned int curveNum, vpColor color)
Definition: vpPlot.cpp:261
static const vpColor purple
Definition: vpColor.h:228
Class that consider the case of a translation vector.
double getD() const
Definition: vpPlane.h:108
static const vpColor blue
Definition: vpColor.h:223