Visual Servoing Platform  version 3.2.0 under development (2019-01-22)
servoViper850FourPointsKinect.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  * tests the control law
33  * eye-in-hand control
34  * velocity computed in the camera frame
35  *
36  * Authors:
37  * Fabien Spindler
38  *
39  *****************************************************************************/
50 #include <visp3/core/vpConfig.h>
51 #include <visp3/core/vpDebug.h> // Debug trace
52 
53 #include <fstream>
54 #include <iostream>
55 #include <sstream>
56 #include <stdio.h>
57 #include <stdlib.h>
58 
59 #if (defined(VISP_HAVE_VIPER850) && defined(VISP_HAVE_LIBFREENECT_AND_DEPENDENCIES))
60 
61 #include <visp3/core/vpDisplay.h>
62 #include <visp3/core/vpHomogeneousMatrix.h>
63 #include <visp3/core/vpImage.h>
64 #include <visp3/core/vpImageConvert.h>
65 #include <visp3/core/vpIoTools.h>
66 #include <visp3/core/vpMath.h>
67 #include <visp3/core/vpPoint.h>
68 #include <visp3/gui/vpDisplayGTK.h>
69 #include <visp3/gui/vpDisplayOpenCV.h>
70 #include <visp3/gui/vpDisplayX.h>
71 #include <visp3/robot/vpRobotViper850.h>
72 #include <visp3/sensor/vp1394TwoGrabber.h>
73 #include <visp3/sensor/vpKinect.h>
74 #include <visp3/vision/vpPose.h>
75 #include <visp3/visual_features/vpFeatureBuilder.h>
76 #include <visp3/visual_features/vpFeaturePoint.h>
77 #include <visp3/vs/vpServo.h>
78 
79 // Exception
80 #include <visp3/core/vpException.h>
81 #include <visp3/vs/vpServoDisplay.h>
82 
83 #include <visp3/blob/vpDot2.h>
84 #define L 0.05 // to deal with a 10cm by 10cm square
85 
111 void compute_pose(vpPoint point[], vpDot2 dot[], int ndot, vpCameraParameters cam, vpHomogeneousMatrix &cMo,
112  vpTranslationVector &cto, vpRxyzVector &cro, bool init)
113 {
114  vpHomogeneousMatrix cMo_dementhon; // computed pose with dementhon
115  vpHomogeneousMatrix cMo_lagrange; // computed pose with dementhon
116  vpRotationMatrix cRo;
117  vpPose pose;
118  vpImagePoint cog;
119  for (int i = 0; i < ndot; i++) {
120 
121  double x = 0, y = 0;
122  cog = dot[i].getCog();
124  y); // pixel to meter conversion
125  point[i].set_x(x); // projection perspective p
126  point[i].set_y(y);
127  pose.addPoint(point[i]);
128  }
129 
130  if (init == true) {
131  pose.computePose(vpPose::DEMENTHON, cMo_dementhon);
132  // Compute and return the residual expressed in meter for the pose matrix
133  // 'cMo'
134  double residual_dementhon = pose.computeResidual(cMo_dementhon);
135  pose.computePose(vpPose::LAGRANGE, cMo_lagrange);
136  double residual_lagrange = pose.computeResidual(cMo_lagrange);
137 
138  // Select the best pose to initialize the lowe pose computation
139  if (residual_lagrange < residual_dementhon)
140  cMo = cMo_lagrange;
141  else
142  cMo = cMo_dementhon;
143 
144  } else { // init = false; use of the previous pose to initialise LOWE
145  cRo.buildFrom(cro);
146  cMo.buildFrom(cto, cRo);
147  }
148  pose.computePose(vpPose::LOWE, cMo);
149  cMo.extract(cto);
150  cMo.extract(cRo);
151  cro.buildFrom(cRo);
152 }
153 
154 int main()
155 {
156  // Log file creation in /tmp/$USERNAME/log.dat
157  // This file contains by line:
158  // - the 6 computed joint velocities (m/s, rad/s) to achieve the task
159  // - the 6 mesured joint velocities (m/s, rad/s)
160  // - the 6 mesured joint positions (m, rad)
161  // - the 8 values of s - s*
162  std::string username;
163  // Get the user login name
164  vpIoTools::getUserName(username);
165 
166  // Create a log filename to save velocities...
167  std::string logdirname;
168  logdirname = "/tmp/" + username;
169 
170  // Test if the output path exist. If no try to create it
171  if (vpIoTools::checkDirectory(logdirname) == false) {
172  try {
173  // Create the dirname
174  vpIoTools::makeDirectory(logdirname);
175  } catch (...) {
176  std::cerr << std::endl << "ERROR:" << std::endl;
177  std::cerr << " Cannot create " << logdirname << std::endl;
178  return (-1);
179  }
180  }
181  std::string logfilename;
182  logfilename = logdirname + "/log.dat";
183 
184  // Open the log file name
185  std::ofstream flog(logfilename.c_str());
186 
187  try {
188  vpRobotViper850 robot;
189  // Load the end-effector to camera frame transformation obtained
190  // using a camera intrinsic model with distortion
192  robot.init(vpRobotViper850::TOOL_GENERIC_CAMERA, projModel);
193 
194  vpServo task;
195 
197  vpImage<vpRGBa> Irgb;
198  int i;
199 
200 #ifdef VISP_HAVE_LIBFREENECT_OLD
201  // This is the way to initialize Freenect with an old version of
202  // libfreenect packages under ubuntu lucid 10.04
203  Freenect::Freenect<vpKinect> freenect;
204  vpKinect &kinect = freenect.createDevice(0);
205 #else
206  Freenect::Freenect freenect;
207  vpKinect &kinect = freenect.createDevice<vpKinect>(0);
208 #endif
209 
211  kinect.getRGB(Irgb);
212  vpImageConvert::convert(Irgb, I);
213 
214 #ifdef VISP_HAVE_X11
215  vpDisplayX display(I, 100, 100, "Current image");
216 #elif defined(VISP_HAVE_OPENCV)
217  vpDisplayOpenCV display(I, 100, 100, "Current image");
218 #elif defined(VISP_HAVE_GTK)
219  vpDisplayGTK display(I, 100, 100, "Current image");
220 #endif
221 
223  vpDisplay::flush(I);
224 
225  std::cout << std::endl;
226  std::cout << "-------------------------------------------------------" << std::endl;
227  std::cout << " Test program for vpServo " << std::endl;
228  std::cout << " Eye-in-hand task control, velocity computed in the camera space" << std::endl;
229  std::cout << " Use of the Viper850 robot " << std::endl;
230  std::cout << " task : servo 4 points on a square with dimention " << L << " meters" << std::endl;
231  std::cout << "-------------------------------------------------------" << std::endl;
232  std::cout << std::endl;
233 
234  vpDot2 dot[4];
235  vpImagePoint cog;
236 
237  std::cout << "Click on the 4 dots clockwise starting from upper/left dot..." << std::endl;
238 
239  for (i = 0; i < 4; i++) {
240  dot[i].initTracking(I);
241  cog = dot[i].getCog();
243  vpDisplay::flush(I);
244  }
245 
246  // Get Kinect Camera Parameters
247  vpCameraParameters cam;
248  // kinect.getRGBCamParameters(cam);
249 
250  robot.getCameraParameters(cam, I);
251 
252  cam.printParameters();
253 
254  // Sets the current position of the visual feature
255  vpFeaturePoint p[4];
256  for (i = 0; i < 4; i++)
257  vpFeatureBuilder::create(p[i], cam, dot[i]); // retrieve x,y of the vpFeaturePoint structure
258 
259  // Set the position of the square target in a frame which origin is
260  // centered in the middle of the square
261  vpPoint point[4];
262  point[0].setWorldCoordinates(-L, -L, 0);
263  point[1].setWorldCoordinates(L, -L, 0);
264  point[2].setWorldCoordinates(L, L, 0);
265  point[3].setWorldCoordinates(-L, L, 0);
266 
267  // Initialise a desired pose to compute s*, the desired 2D point features
269  vpTranslationVector cto(0, 0, 0.5); // tz = 0.5 meter
271  vpRotationMatrix cRo(cro); // Build the rotation matrix
272  cMo.buildFrom(cto, cRo); // Build the homogeneous matrix
273 
274  // Sets the desired position of the 2D visual feature
275  vpFeaturePoint pd[4];
276  // Compute the desired position of the features from the desired pose
277  for (int i = 0; i < 4; i++) {
278  vpColVector cP, p;
279  point[i].changeFrame(cMo, cP);
280  point[i].projection(cP, p);
281 
282  pd[i].set_x(p[0]);
283  pd[i].set_y(p[1]);
284  pd[i].set_Z(cP[2]);
285  }
286 
287  // We want to see a point on a point
288  for (i = 0; i < 4; i++)
289  task.addFeature(p[i], pd[i]);
290 
291  // Set the proportional gain
292  task.setLambda(0.5);
293 
294  // Display task information
295  task.print();
296 
297  // Define the task
298  // - we want an eye-in-hand control law
299  // - articular velocity are computed
302  task.print();
303 
304  // Initialise the velocity control of the robot
306 
307  std::cout << "\nHit CTRL-C to stop the loop...\n" << std::flush;
308  for (;;) {
309  // Acquire a new image from the kinect
310  kinect.getRGB(Irgb);
311  vpImageConvert::convert(Irgb, I);
312 
313  // Display this image
315 
316  try {
317  // For each point...
318  for (i = 0; i < 4; i++) {
319  // Achieve the tracking of the dot in the image
320  dot[i].track(I);
321  // Display a green cross at the center of gravity position in the
322  // image
323  cog = dot[i].getCog();
325  }
326  } catch (...) {
327  flog.close(); // Close the log file
328  vpTRACE("Error detected while tracking visual features");
329  robot.stopMotion();
330  kinect.stop();
331  return (1);
332  }
333 
334  // During the servo, we compute the pose using LOWE method. For the
335  // initial pose used in the non linear minimisation we use the pose
336  // computed at the previous iteration.
337  compute_pose(point, dot, 4, cam, cMo, cto, cro, false);
338 
339  for (i = 0; i < 4; i++) {
340  // Update the point feature from the dot location
341  vpFeatureBuilder::create(p[i], cam, dot[i]);
342  // Set the feature Z coordinate from the pose
343  vpColVector cP;
344  point[i].changeFrame(cMo, cP);
345 
346  p[i].set_Z(cP[2]);
347  }
348 
349  vpColVector v;
350  // Compute the visual servoing skew vector
351  v = task.computeControlLaw();
352 
353  // Display the current and desired feature points in the image display
354  vpServoDisplay::display(task, cam, I);
355 
356  // Apply the computed joint velocities to the robot
358 
359  // Save velocities applied to the robot in the log file
360  // v[0], v[1], v[2] correspond to joint translation velocities in m/s
361  // v[3], v[4], v[5] correspond to joint rotation velocities in rad/s
362  flog << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << " " << v[5] << " ";
363 
364  // Get the measured joint velocities of the robot
365  vpColVector qvel;
367  // Save measured joint velocities of the robot in the log file:
368  // - qvel[0], qvel[1], qvel[2] correspond to measured joint translation
369  // velocities in m/s
370  // - qvel[3], qvel[4], qvel[5] correspond to measured joint rotation
371  // velocities in rad/s
372  flog << qvel[0] << " " << qvel[1] << " " << qvel[2] << " " << qvel[3] << " " << qvel[4] << " " << qvel[5] << " ";
373 
374  // Get the measured joint positions of the robot
375  vpColVector q;
377  // Save measured joint positions of the robot in the log file
378  // - q[0], q[1], q[2] correspond to measured joint translation
379  // positions in m
380  // - q[3], q[4], q[5] correspond to measured joint rotation
381  // positions in rad
382  flog << q[0] << " " << q[1] << " " << q[2] << " " << q[3] << " " << q[4] << " " << q[5] << " ";
383 
384  // Save feature error (s-s*) for the 4 feature points. For each feature
385  // point, we have 2 errors (along x and y axis). This error is
386  // expressed in meters in the camera frame
387  flog << (task.getError()).t() << std::endl;
388 
389  // Flush the display
390  vpDisplay::flush(I);
391 
392  // std::cout << "|| s - s* || = " << ( task.getError() ).sumSquare() <<
393  // std::endl;
394  }
395 
396  kinect.stop();
397  std::cout << "Display task information: " << std::endl;
398  task.print();
399  task.kill();
400  flog.close(); // Close the log file
401  return EXIT_SUCCESS;
402  }
403  catch (const vpException &e) {
404  flog.close(); // Close the log file
405  std::cout << "Catch an exception: " << e.getMessage() << std::endl;
406  return EXIT_FAILURE;
407  }
408 }
409 
410 #else
411 int main()
412 {
413  std::cout << "You do not have an Viper 850 robot connected to your computer..." << std::endl;
414  return EXIT_SUCCESS;
415 }
416 #endif
void getPosition(const vpRobot::vpControlFrameType frame, vpColVector &position)
void start(vpKinect::vpDMResolution res=DMAP_LOW_RES)
Definition: vpKinect.cpp:73
vpRxyzVector buildFrom(const vpRotationMatrix &R)
bool computePose(vpPoseMethodType method, vpHomogeneousMatrix &cMo, bool(*func)(const vpHomogeneousMatrix &)=NULL)
Definition: vpPose.cpp:362
void projection(const vpColVector &_cP, vpColVector &_p)
Definition: vpPoint.cpp:216
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:467
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
Implementation of an homogeneous matrix and operations on such kind of matrices.
void getCameraParameters(vpCameraParameters &cam, const unsigned int &image_width, const unsigned int &image_height) const
Definition: vpViper850.cpp:540
Control of Irisa&#39;s Viper S850 robot named Viper850.
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:151
void addFeature(vpBasicFeature &s, vpBasicFeature &s_star, const unsigned int select=vpBasicFeature::FEATURE_ALL)
Definition: vpServo.cpp:497
vpRobot::vpRobotStateType setRobotState(vpRobot::vpRobotStateType newState)
error that can be emited by ViSP classes.
Definition: vpException.h:71
void set_x(const double x)
Set the point x coordinate in the image plane.
Definition: vpPoint.cpp:470
Class that defines a 2D point visual feature which is composed by two parameters that are the cartes...
static void convertPoint(const vpCameraParameters &cam, const double &u, const double &v, double &x, double &y)
static const vpColor green
Definition: vpColor.h:183
This tracker is meant to track a blob (connex pixels with same gray level) on a vpImage.
Definition: vpDot2.h:126
Driver for the Kinect-1 device.
Definition: vpKinect.h:110
void track(const vpImage< unsigned char > &I)
Definition: vpDot2.cpp:438
static void flush(const vpImage< unsigned char > &I)
void set_y(const double y)
Class that defines what is a point.
Definition: vpPoint.h:58
Implementation of a rotation matrix and operations on such kind of matrices.
vpImagePoint getCog() const
Definition: vpDot2.h:161
void set_x(const double x)
static void makeDirectory(const char *dirname)
Definition: vpIoTools.cpp:597
void kill()
Definition: vpServo.cpp:192
Initialize the velocity controller.
Definition: vpRobot.h:67
vpColVector getError() const
Definition: vpServo.h:282
vpColVector computeControlLaw()
Definition: vpServo.cpp:935
vpRotationMatrix buildFrom(const vpHomogeneousMatrix &M)
#define vpTRACE
Definition: vpDebug.h:416
static void display(const vpImage< unsigned char > &I)
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
Class used for pose computation from N points (pose from point only). Some of the algorithms implemen...
Definition: vpPose.h:78
Generic class defining intrinsic camera parameters.
void setLambda(double c)
Definition: vpServo.h:406
void set_y(const double y)
Set the point y coordinate in the image plane.
Definition: vpPoint.cpp:472
static std::string getUserName()
Definition: vpIoTools.cpp:298
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:138
void extract(vpRotationMatrix &R) const
const char * getMessage(void) const
Definition: vpException.cpp:90
bool getRGB(vpImage< vpRGBa > &IRGB)
Definition: vpKinect.cpp:231
void buildFrom(const vpTranslationVector &t, const vpRotationMatrix &R)
void setInteractionMatrixType(const vpServoIteractionMatrixType &interactionMatrixType, const vpServoInversionType &interactionMatrixInversion=PSEUDO_INVERSE)
Definition: vpServo.cpp:574
static double rad(double deg)
Definition: vpMath.h:102
void setVelocity(const vpRobot::vpControlFrameType frame, const vpColVector &velocity)
static void displayCross(const vpImage< unsigned char > &I, const vpImagePoint &ip, unsigned int size, const vpColor &color, unsigned int thickness=1)
void setWorldCoordinates(const double oX, const double oY, const double oZ)
Definition: vpPoint.cpp:113
void getVelocity(const vpRobot::vpControlFrameType frame, vpColVector &velocity)
Implementation of column vector and the associated operations.
Definition: vpColVector.h:72
void stop()
Definition: vpKinect.cpp:116
void initTracking(const vpImage< unsigned char > &I, unsigned int size=0)
Definition: vpDot2.cpp:253
void print(const vpServo::vpServoPrintType display_level=ALL, std::ostream &os=std::cout)
Definition: vpServo.cpp:313
Implementation of a rotation vector as Euler angle minimal representation.
Definition: vpRxyzVector.h:156
void set_Z(const double Z)
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:88
static void create(vpFeaturePoint &s, const vpCameraParameters &cam, const vpDot &d)
void changeFrame(const vpHomogeneousMatrix &cMo, vpColVector &_cP)
Definition: vpPoint.cpp:233
void addPoint(const vpPoint &P)
Definition: vpPose.cpp:137
void setServo(const vpServoType &servo_type)
Definition: vpServo.cpp:223
Class that consider the case of a translation vector.
static void display(const vpServo &s, const vpCameraParameters &cam, const vpImage< unsigned char > &I, vpColor currentColor=vpColor::green, vpColor desiredColor=vpColor::red, unsigned int thickness=1)
double computeResidual(const vpHomogeneousMatrix &cMo) const
Compute and return the sum of squared residuals expressed in meter^2 for the pose matrix cMo...
Definition: vpPose.cpp:324
static const vpColor blue
Definition: vpColor.h:186