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