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