Visual Servoing Platform  version 3.0.1
servoViper850FourPointsKinect.cpp
1 /****************************************************************************
2  *
3  * This file is part of the ViSP software.
4  * Copyright (C) 2005 - 2017 by Inria. All rights reserved.
5  *
6  * This software is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * ("GPL") version 2 as published by the Free Software Foundation.
9  * See the file LICENSE.txt at the root directory of this source
10  * distribution for additional information about the GNU GPL.
11  *
12  * For using ViSP with software that can not be combined with the GNU
13  * GPL, please contact Inria about acquiring a ViSP Professional
14  * Edition License.
15  *
16  * See http://visp.inria.fr for more information.
17  *
18  * This software was developed at:
19  * Inria Rennes - Bretagne Atlantique
20  * Campus Universitaire de Beaulieu
21  * 35042 Rennes Cedex
22  * France
23  *
24  * If you have questions regarding the use of this file, please contact
25  * Inria at visp@inria.fr
26  *
27  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
28  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29  *
30  * Description:
31  * tests the control law
32  * eye-in-hand control
33  * velocity computed in the camera frame
34  *
35  * Authors:
36  * Fabien Spindler
37  *
38  *****************************************************************************/
50 #include <visp3/core/vpConfig.h>
51 #include <visp3/core/vpDebug.h> // Debug trace
52 
53 #include <stdio.h>
54 #include <iostream>
55 #include <fstream>
56 #include <sstream>
57 #include <stdlib.h>
58 
59 #if (defined (VISP_HAVE_VIPER850) && defined (VISP_HAVE_LIBFREENECT_AND_DEPENDENCIES) )
60 
61 
62 #include <visp3/sensor/vp1394TwoGrabber.h>
63 #include <visp3/core/vpImage.h>
64 #include <visp3/core/vpImageConvert.h>
65 #include <visp3/core/vpDisplay.h>
66 #include <visp3/gui/vpDisplayX.h>
67 #include <visp3/gui/vpDisplayOpenCV.h>
68 #include <visp3/gui/vpDisplayGTK.h>
69 #include <visp3/core/vpMath.h>
70 #include <visp3/core/vpHomogeneousMatrix.h>
71 #include <visp3/visual_features/vpFeaturePoint.h>
72 #include <visp3/core/vpPoint.h>
73 #include <visp3/vs/vpServo.h>
74 #include <visp3/visual_features/vpFeatureBuilder.h>
75 #include <visp3/core/vpIoTools.h>
76 #include <visp3/robot/vpRobotViper850.h>
77 #include <visp3/vision/vpPose.h>
78 #include <visp3/sensor/vpKinect.h>
79 
80 // Exception
81 #include <visp3/core/vpException.h>
82 #include <visp3/vs/vpServoDisplay.h>
83 
84 #include <visp3/blob/vpDot2.h>
85 #define L 0.05 // to deal with a 10cm by 10cm square
86 
87 
113 void compute_pose(vpPoint point[], vpDot2 dot[], int ndot,
114  vpCameraParameters cam,
115  vpHomogeneousMatrix &cMo,
116  vpTranslationVector &cto,
117  vpRxyzVector &cro, bool init)
118 {
119  vpHomogeneousMatrix cMo_dementhon; // computed pose with dementhon
120  vpHomogeneousMatrix cMo_lagrange; // computed pose with dementhon
121  vpRotationMatrix cRo;
122  vpPose pose;
123  vpImagePoint cog;
124  for (int i=0; i < ndot; i ++) {
125 
126  double x=0, y=0;
127  cog = dot[i].getCog();
128  vpPixelMeterConversion::convertPoint(cam, cog, x, y) ; //pixel to meter conversion
129  point[i].set_x(x) ;//projection perspective p
130  point[i].set_y(y) ;
131  pose.addPoint(point[i]) ;
132  }
133 
134  if (init == true) {
135  pose.computePose(vpPose::DEMENTHON, cMo_dementhon) ;
136  // Compute and return the residual expressed in meter for the pose matrix
137  // 'cMo'
138  double residual_dementhon = pose.computeResidual(cMo_dementhon);
139  pose.computePose(vpPose::LAGRANGE, cMo_lagrange) ;
140  double residual_lagrange = pose.computeResidual(cMo_lagrange);
141 
142  // Select the best pose to initialize the lowe pose computation
143  if (residual_lagrange < residual_dementhon)
144  cMo = cMo_lagrange;
145  else
146  cMo = cMo_dementhon;
147 
148  }
149  else { // init = false; use of the previous pose to initialise LOWE
150  cRo.buildFrom(cro);
151  cMo.buildFrom(cto, cRo);
152  }
153  pose.computePose(vpPose::LOWE, cMo) ;
154  cMo.extract(cto);
155  cMo.extract(cRo);
156  cro.buildFrom(cRo);
157 }
158 
159 int main()
160 {
161  // Log file creation in /tmp/$USERNAME/log.dat
162  // This file contains by line:
163  // - the 6 computed joint velocities (m/s, rad/s) to achieve the task
164  // - the 6 mesured joint velocities (m/s, rad/s)
165  // - the 6 mesured joint positions (m, rad)
166  // - the 8 values of s - s*
167  std::string username;
168  // Get the user login name
169  vpIoTools::getUserName(username);
170 
171  // Create a log filename to save velocities...
172  std::string logdirname;
173  logdirname ="/tmp/" + username;
174 
175  // Test if the output path exist. If no try to create it
176  if (vpIoTools::checkDirectory(logdirname) == false) {
177  try {
178  // Create the dirname
179  vpIoTools::makeDirectory(logdirname);
180  }
181  catch (...) {
182  std::cerr << std::endl
183  << "ERROR:" << std::endl;
184  std::cerr << " Cannot create " << logdirname << std::endl;
185  return(-1);
186  }
187  }
188  std::string logfilename;
189  logfilename = logdirname + "/log.dat";
190 
191  // Open the log file name
192  std::ofstream flog(logfilename.c_str());
193 
194  try {
195  vpRobotViper850 robot ;
196  // Load the end-effector to camera frame transformation obtained
197  // using a camera intrinsic model with distortion
200  robot.init(vpRobotViper850::TOOL_GENERIC_CAMERA, projModel);
201 
202  vpServo task ;
203 
205  vpImage<vpRGBa> Irgb;
206  int i ;
207 
208 #ifdef VISP_HAVE_LIBFREENECT_OLD
209  // This is the way to initialize Freenect with an old version of libfreenect packages under ubuntu lucid 10.04
210  Freenect::Freenect<vpKinect> freenect;
211  vpKinect & kinect = freenect.createDevice(0);
212 #else
213  Freenect::Freenect freenect;
214  vpKinect & kinect = freenect.createDevice<vpKinect>(0);
215 #endif
216 
218  kinect.getRGB(Irgb);
219  vpImageConvert::convert(Irgb, I);
220 
221 #ifdef VISP_HAVE_X11
222  vpDisplayX display(I,100,100,"Current image") ;
223 #elif defined(VISP_HAVE_OPENCV)
224  vpDisplayOpenCV display(I,100,100,"Current image") ;
225 #elif defined(VISP_HAVE_GTK)
226  vpDisplayGTK display(I,100,100,"Current image") ;
227 #endif
228 
229  vpDisplay::display(I) ;
230  vpDisplay::flush(I) ;
231 
232  std::cout << std::endl ;
233  std::cout << "-------------------------------------------------------" << std::endl ;
234  std::cout << " Test program for vpServo " <<std::endl ;
235  std::cout << " Eye-in-hand task control, velocity computed in the camera space" << std::endl ;
236  std::cout << " Use of the Viper850 robot " << std::endl ;
237  std::cout << " task : servo 4 points on a square with dimention " << L << " meters" << std::endl ;
238  std::cout << "-------------------------------------------------------" << std::endl ;
239  std::cout << std::endl ;
240 
241  vpDot2 dot[4] ;
242  vpImagePoint cog;
243 
244  std::cout << "Click on the 4 dots clockwise starting from upper/left dot..."
245  << std::endl;
246 
247  for (i=0 ; i < 4 ; i++) {
248  dot[i].initTracking(I) ;
249  cog = dot[i].getCog();
251  vpDisplay::flush(I);
252  }
253 
254  // Get Kinect Camera Parameters
255  vpCameraParameters cam ;
256  //kinect.getRGBCamParameters(cam);
257 
258  robot.getCameraParameters(cam, I);
259 
260  cam.printParameters();
261 
262  // Sets the current position of the visual feature
263  vpFeaturePoint p[4] ;
264  for (i=0 ; i < 4 ; i++)
265  vpFeatureBuilder::create(p[i], cam, dot[i]); //retrieve x,y of the vpFeaturePoint structure
266 
267  // Set the position of the square target in a frame which origin is
268  // centered in the middle of the square
269  vpPoint point[4] ;
270  point[0].setWorldCoordinates(-L, -L, 0) ;
271  point[1].setWorldCoordinates( L, -L, 0) ;
272  point[2].setWorldCoordinates( L, L, 0) ;
273  point[3].setWorldCoordinates(-L, L, 0) ;
274 
275  // Initialise a desired pose to compute s*, the desired 2D point features
277  vpTranslationVector cto(0, 0, 0.5); // tz = 0.5 meter
279  vpRotationMatrix cRo(cro); // Build the rotation matrix
280  cMo.buildFrom(cto, cRo); // Build the homogeneous matrix
281 
282  // Sets the desired position of the 2D visual feature
283  vpFeaturePoint pd[4] ;
284  // Compute the desired position of the features from the desired pose
285  for (int i=0; i < 4; i ++) {
286  vpColVector cP, p ;
287  point[i].changeFrame(cMo, cP) ;
288  point[i].projection(cP, p) ;
289 
290  pd[i].set_x(p[0]) ;
291  pd[i].set_y(p[1]) ;
292  pd[i].set_Z(cP[2]);
293  }
294 
295  // We want to see a point on a point
296  for (i=0 ; i < 4 ; i++)
297  task.addFeature(p[i],pd[i]) ;
298 
299  // Set the proportional gain
300  task.setLambda(0.5) ;
301 
302  // Display task information
303  task.print() ;
304 
305  // Define the task
306  // - we want an eye-in-hand control law
307  // - articular velocity are computed
310  task.print() ;
311 
312  // Initialise the velocity control of the robot
314 
315  std::cout << "\nHit CTRL-C to stop the loop...\n" << std::flush;
316  for ( ; ; ) {
317  // Acquire a new image from the kinect
318  kinect.getRGB(Irgb);
319  vpImageConvert::convert(Irgb, I);
320 
321  // Display this image
322  vpDisplay::display(I) ;
323 
324  try {
325  // For each point...
326  for (i=0 ; i < 4 ; i++) {
327  // Achieve the tracking of the dot in the image
328  dot[i].track(I) ;
329  // Display a green cross at the center of gravity position in the
330  // image
331  cog = dot[i].getCog();
333  }
334  }
335  catch(...) {
336  flog.close() ; // Close the log file
337  vpTRACE("Error detected while tracking visual features") ;
338  robot.stopMotion() ;
339  kinect.stop();
340  return(1) ;
341  }
342 
343  // During the servo, we compute the pose using LOWE method. For the
344  // initial pose used in the non linear minimisation we use the pose
345  // computed at the previous iteration.
346  compute_pose(point, dot, 4, cam, cMo, cto, cro, false);
347 
348  for (i=0 ; i < 4 ; i++) {
349  // Update the point feature from the dot location
350  vpFeatureBuilder::create(p[i], cam, dot[i]);
351  // Set the feature Z coordinate from the pose
352  vpColVector cP;
353  point[i].changeFrame(cMo, cP) ;
354 
355  p[i].set_Z(cP[2]);
356  }
357 
358  vpColVector v ;
359  // Compute the visual servoing skew vector
360  v = task.computeControlLaw() ;
361 
362  // Display the current and desired feature points in the image display
363  vpServoDisplay::display(task,cam,I) ;
364 
365  // Apply the computed joint velocities to the robot
367 
368  // Save velocities applied to the robot in the log file
369  // v[0], v[1], v[2] correspond to joint translation velocities in m/s
370  // v[3], v[4], v[5] correspond to joint rotation velocities in rad/s
371  flog << v[0] << " " << v[1] << " " << v[2] << " "
372  << v[3] << " " << v[4] << " " << v[5] << " ";
373 
374  // Get the measured joint velocities of the robot
375  vpColVector qvel;
377  // Save measured joint velocities of the robot in the log file:
378  // - qvel[0], qvel[1], qvel[2] correspond to measured joint translation
379  // velocities in m/s
380  // - qvel[3], qvel[4], qvel[5] correspond to measured joint rotation
381  // velocities in rad/s
382  flog << qvel[0] << " " << qvel[1] << " " << qvel[2] << " "
383  << qvel[3] << " " << qvel[4] << " " << qvel[5] << " ";
384 
385  // Get the measured joint positions of the robot
386  vpColVector q;
388  // Save measured joint positions of the robot in the log file
389  // - q[0], q[1], q[2] correspond to measured joint translation
390  // positions in m
391  // - q[3], q[4], q[5] correspond to measured joint rotation
392  // positions in rad
393  flog << q[0] << " " << q[1] << " " << q[2] << " "
394  << q[3] << " " << q[4] << " " << q[5] << " ";
395 
396  // Save feature error (s-s*) for the 4 feature points. For each feature
397  // point, we have 2 errors (along x and y axis). This error is expressed
398  // in meters in the camera frame
399  flog << ( task.getError() ).t() << std::endl;
400 
401  // Flush the display
402  vpDisplay::flush(I) ;
403 
404  // std::cout << "|| s - s* || = " << ( task.getError() ).sumSquare() << std::endl;
405  }
406 
407  kinect.stop();
408  std::cout << "Display task information: " << std::endl;
409  task.print() ;
410  task.kill();
411  flog.close() ; // Close the log file
412  return 0;
413  }
414  catch (...)
415  {
416  flog.close() ; // Close the log file
417  vpERROR_TRACE(" Test failed") ;
418  return 0;
419  }
420 }
421 
422 #else
423 int main()
424 {
425  vpERROR_TRACE("You do not have a Viper robot or a kinect connected to your computer...");
426 }
427 
428 #endif
429 //#endif
void getPosition(const vpRobot::vpControlFrameType frame, vpColVector &position)
void start(vpKinect::vpDMResolution res=DMAP_LOW_RES)
Definition: vpKinect.cpp:78
vpRxyzVector buildFrom(const vpRotationMatrix &R)
void projection(const vpColVector &_cP, vpColVector &_p)
Projection onto the image plane of a point. Input: the 3D coordinates in the camera frame _cP...
Definition: vpPoint.cpp:229
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:358
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
void getCameraParameters(vpCameraParameters &cam, const unsigned int &image_width, const unsigned int &image_height) const
Definition: vpViper850.cpp:564
Implementation of an homogeneous matrix and operations on such kind of matrices.
Control of Irisa&#39;s Viper S850 robot named Viper850.
#define vpERROR_TRACE
Definition: vpDebug.h:391
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:153
void addFeature(vpBasicFeature &s, vpBasicFeature &s_star, const unsigned int select=vpBasicFeature::FEATURE_ALL)
Definition: vpServo.cpp:512
vpRobot::vpRobotStateType setRobotState(vpRobot::vpRobotStateType newState)
void set_x(const double x)
Set the point x coordinate in the image plane.
Definition: vpPoint.cpp:496
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)
Point coordinates conversion from pixel coordinates to normalized coordinates in meter...
void extract(vpRotationMatrix &R) const
static const vpColor green
Definition: vpColor.h:166
This tracker is meant to track a blob (connex pixels with same gray level) on a vpImage.
Definition: vpDot2.h:125
Driver for the Kinect-1 device.
Definition: vpKinect.h:110
void track(const vpImage< unsigned char > &I)
Definition: vpDot2.cpp:461
static void flush(const vpImage< unsigned char > &I)
void set_y(const double y)
Class that defines what is a point.
Definition: vpPoint.h:59
Implementation of a rotation matrix and operations on such kind of matrices.
void set_x(const double x)
static void makeDirectory(const char *dirname)
Definition: vpIoTools.cpp:427
void kill()
Definition: vpServo.cpp:191
Initialize the velocity controller.
Definition: vpRobot.h:68
vpColVector computeControlLaw()
Definition: vpServo.cpp:954
vpRotationMatrix buildFrom(const vpHomogeneousMatrix &M)
#define vpTRACE
Definition: vpDebug.h:414
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:76
Generic class defining intrinsic camera parameters.
void setLambda(double c)
Definition: vpServo.h:391
void set_y(const double y)
Set the point y coordinate in the image plane.
Definition: vpPoint.cpp:498
static std::string getUserName()
Definition: vpIoTools.cpp:177
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:138
bool computePose(vpPoseMethodType method, vpHomogeneousMatrix &cMo, bool(*func)(vpHomogeneousMatrix *)=NULL)
Definition: vpPose.cpp:372
bool getRGB(vpImage< vpRGBa > &IRGB)
Definition: vpKinect.cpp:240
Perspective projection with distortion model.
void buildFrom(const vpTranslationVector &t, const vpRotationMatrix &R)
void setInteractionMatrixType(const vpServoIteractionMatrixType &interactionMatrixType, const vpServoInversionType &interactionMatrixInversion=PSEUDO_INVERSE)
Definition: vpServo.cpp:585
static double rad(double deg)
Definition: vpMath.h:104
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:111
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:118
void initTracking(const vpImage< unsigned char > &I, unsigned int size=0)
Definition: vpDot2.cpp:262
void print(const vpServo::vpServoPrintType display_level=ALL, std::ostream &os=std::cout)
Definition: vpServo.cpp:314
vpImagePoint getCog() const
Definition: vpDot2.h:161
Implementation of a rotation vector as Euler angle minimal representation.
Definition: vpRxyzVector.h:154
vpColVector getError() const
Definition: vpServo.h:271
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)
double computeResidual(const vpHomogeneousMatrix &cMo) const
Compute and return the residual expressed in meter for the pose matrix &#39;cMo&#39;.
Definition: vpPose.cpp:337
void changeFrame(const vpHomogeneousMatrix &cMo, vpColVector &_cP)
Definition: vpPoint.cpp:247
void addPoint(const vpPoint &P)
Definition: vpPose.cpp:145
void setServo(const vpServoType &servo_type)
Definition: vpServo.cpp:222
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)
static const vpColor blue
Definition: vpColor.h:169