ViSP  2.6.2
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 - 2012 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/vpMath.h>
73 #include <visp/vpHomogeneousMatrix.h>
74 #include <visp/vpFeaturePoint.h>
75 #include <visp/vpPoint.h>
76 #include <visp/vpServo.h>
77 #include <visp/vpFeatureBuilder.h>
78 #include <visp/vpIoTools.h>
79 #include <visp/vpRobotViper850.h>
80 #include <visp/vpPose.h>
81 #include <visp/vpKinect.h>
82 
83 // Exception
84 #include <visp/vpException.h>
85 #include <visp/vpMatrixException.h>
86 #include <visp/vpServoDisplay.h>
87 
88 #include <visp/vpDot2.h>
89 #define L 0.05 // to deal with a 10cm by 10cm square
90 
91 
117 void compute_pose(vpPoint point[], vpDot2 dot[], int ndot,
118  vpCameraParameters cam,
119  vpHomogeneousMatrix &cMo,
120  vpTranslationVector &cto,
121  vpRxyzVector &cro, bool init)
122 {
123  vpHomogeneousMatrix cMo_dementhon; // computed pose with dementhon
124  vpHomogeneousMatrix cMo_lagrange; // computed pose with dementhon
125  vpRotationMatrix cRo;
126  vpPose pose;
127  vpImagePoint cog;
128  for (int i=0; i < ndot; i ++) {
129 
130  double x=0, y=0;
131  cog = dot[i].getCog();
132  vpPixelMeterConversion::convertPoint(cam, cog, x, y) ; //pixel to meter conversion
133  point[i].set_x(x) ;//projection perspective p
134  point[i].set_y(y) ;
135  pose.addPoint(point[i]) ;
136  }
137 
138  if (init == true) {
139  pose.computePose(vpPose::DEMENTHON, cMo_dementhon) ;
140  // Compute and return the residual expressed in meter for the pose matrix
141  // 'cMo'
142  double residual_dementhon = pose.computeResidual(cMo_dementhon);
143  pose.computePose(vpPose::LAGRANGE, cMo_lagrange) ;
144  double residual_lagrange = pose.computeResidual(cMo_lagrange);
145 
146  // Select the best pose to initialize the lowe pose computation
147  if (residual_lagrange < residual_dementhon)
148  cMo = cMo_lagrange;
149  else
150  cMo = cMo_dementhon;
151 
152  }
153  else { // init = false; use of the previous pose to initialise LOWE
154  cRo.buildFrom(cro);
155  cMo.buildFrom(cto, cRo);
156  }
157  pose.computePose(vpPose::LOWE, cMo) ;
158  cMo.extract(cto);
159  cMo.extract(cRo);
160  cro.buildFrom(cRo);
161 }
162 
163 int main()
164 {
165  // Log file creation in /tmp/$USERNAME/log.dat
166  // This file contains by line:
167  // - the 6 computed joint velocities (m/s, rad/s) to achieve the task
168  // - the 6 mesured joint velocities (m/s, rad/s)
169  // - the 6 mesured joint positions (m, rad)
170  // - the 8 values of s - s*
171  std::string username;
172  // Get the user login name
173  vpIoTools::getUserName(username);
174 
175  // Create a log filename to save velocities...
176  std::string logdirname;
177  logdirname ="/tmp/" + username;
178 
179  // Test if the output path exist. If no try to create it
180  if (vpIoTools::checkDirectory(logdirname) == false) {
181  try {
182  // Create the dirname
183  vpIoTools::makeDirectory(logdirname);
184  }
185  catch (...) {
186  std::cerr << std::endl
187  << "ERROR:" << std::endl;
188  std::cerr << " Cannot create " << logdirname << std::endl;
189  return(-1);
190  }
191  }
192  std::string logfilename;
193  logfilename = logdirname + "/log.dat";
194 
195  // Open the log file name
196  std::ofstream flog(logfilename.c_str());
197 
198  try {
199  vpRobotViper850 robot ;
200  // Load the end-effector to camera frame transformation obtained
201  // using a camera intrinsic model with distortion
204  robot.init(vpRobotViper850::TOOL_GENERIC_CAMERA, projModel);
205 
206  vpServo task ;
207 
209  vpImage<vpRGBa> Irgb;
210  int i ;
211 
212 #ifdef VISP_HAVE_LIBFREENECT_OLD
213  // This is the way to initialize Freenect with an old version of libfreenect packages under ubuntu lucid 10.04
214  Freenect::Freenect<vpKinect> freenect;
215  vpKinect & kinect = freenect.createDevice(0);
216 #else
217  Freenect::Freenect freenect;
218  vpKinect & kinect = freenect.createDevice<vpKinect>(0);
219 #endif
220 
222  kinect.getRGB(Irgb);
223  vpImageConvert::convert(Irgb, I);
224 
225  vpDisplayX display(I, 100, 100, "Camera view ") ;
226  vpTRACE(" ") ;
227 
228  vpDisplay::display(I) ;
229  vpDisplay::flush(I) ;
230 
231  std::cout << std::endl ;
232  std::cout << "-------------------------------------------------------" << std::endl ;
233  std::cout << " Test program for vpServo " <<std::endl ;
234  std::cout << " Eye-in-hand task control, velocity computed in the camera space" << std::endl ;
235  std::cout << " Use of the Viper850 robot " << std::endl ;
236  std::cout << " task : servo 4 points on a square with dimention " << L << " meters" << std::endl ;
237  std::cout << "-------------------------------------------------------" << std::endl ;
238  std::cout << std::endl ;
239 
240  vpDot2 dot[4] ;
241  vpImagePoint cog;
242 
243  std::cout << "Click on the 4 dots clockwise starting from upper/left dot..."
244  << std::endl;
245 
246  for (i=0 ; i < 4 ; i++) {
247  dot[i].initTracking(I) ;
248  cog = dot[i].getCog();
250  vpDisplay::flush(I);
251  }
252 
253  // Get Kinect Camera Parameters
254  vpCameraParameters cam ;
255  //kinect.getRGBCamParameters(cam);
256 
257  robot.getCameraParameters(cam, I);
258 
259  cam.printParameters();
260 
261  // Sets the current position of the visual feature
262  vpFeaturePoint p[4] ;
263  for (i=0 ; i < 4 ; i++)
264  vpFeatureBuilder::create(p[i], cam, dot[i]); //retrieve x,y of the vpFeaturePoint structure
265 
266  // Set the position of the square target in a frame which origin is
267  // centered in the middle of the square
268  vpPoint point[4] ;
269  point[0].setWorldCoordinates(-L, -L, 0) ;
270  point[1].setWorldCoordinates( L, -L, 0) ;
271  point[2].setWorldCoordinates( L, L, 0) ;
272  point[3].setWorldCoordinates(-L, L, 0) ;
273 
274  // Initialise a desired pose to compute s*, the desired 2D point features
276  vpTranslationVector cto(0, 0, 0.5); // tz = 0.5 meter
278  vpRotationMatrix cRo(cro); // Build the rotation matrix
279  cMo.buildFrom(cto, cRo); // Build the homogeneous matrix
280 
281  // Sets the desired position of the 2D visual feature
282  vpFeaturePoint pd[4] ;
283  // Compute the desired position of the features from the desired pose
284  for (int i=0; i < 4; i ++) {
285  vpColVector cP, p ;
286  point[i].changeFrame(cMo, cP) ;
287  point[i].projection(cP, p) ;
288 
289  pd[i].set_x(p[0]) ;
290  pd[i].set_y(p[1]) ;
291  pd[i].set_Z(cP[2]);
292  }
293 
294  // We want to see a point on a point
295  for (i=0 ; i < 4 ; i++)
296  task.addFeature(p[i],pd[i]) ;
297 
298  // Set the proportional gain
299  task.setLambda(0.5) ;
300 
301  // Display task information
302  task.print() ;
303 
304  // Define the task
305  // - we want an eye-in-hand control law
306  // - articular velocity are computed
309  task.print() ;
310 
311  // Initialise the velocity control of the robot
313 
314  std::cout << "\nHit CTRL-C to stop the loop...\n" << std::flush;
315  for ( ; ; ) {
316  // Acquire a new image from the kinect
317  kinect.getRGB(Irgb);
318  vpImageConvert::convert(Irgb, I);
319 
320  // Display this image
321  vpDisplay::display(I) ;
322 
323  try {
324  // For each point...
325  for (i=0 ; i < 4 ; i++) {
326  // Achieve the tracking of the dot in the image
327  dot[i].track(I) ;
328  // Display a green cross at the center of gravity position in the
329  // image
330  cog = dot[i].getCog();
332  }
333  }
334  catch(...) {
335  flog.close() ; // Close the log file
336  vpTRACE("Error detected while tracking visual features") ;
337  robot.stopMotion() ;
338  kinect.stop();
339  return(1) ;
340  }
341 
342  // During the servo, we compute the pose using LOWE method. For the
343  // initial pose used in the non linear minimisation we use the pose
344  // computed at the previous iteration.
345  compute_pose(point, dot, 4, cam, cMo, cto, cro, false);
346 
347  for (i=0 ; i < 4 ; i++) {
348  // Update the point feature from the dot location
349  vpFeatureBuilder::create(p[i], cam, dot[i]);
350  // Set the feature Z coordinate from the pose
351  vpColVector cP;
352  point[i].changeFrame(cMo, cP) ;
353 
354  p[i].set_Z(cP[2]);
355  }
356 
357  vpColVector v ;
358  // Compute the visual servoing skew vector
359  v = task.computeControlLaw() ;
360 
361  // Display the current and desired feature points in the image display
362  vpServoDisplay::display(task,cam,I) ;
363 
364  // Apply the computed joint velocities to the robot
366 
367  // Save velocities applied to the robot in the log file
368  // v[0], v[1], v[2] correspond to joint translation velocities in m/s
369  // v[3], v[4], v[5] correspond to joint rotation velocities in rad/s
370  flog << v[0] << " " << v[1] << " " << v[2] << " "
371  << v[3] << " " << v[4] << " " << v[5] << " ";
372 
373  // Get the measured joint velocities of the robot
374  vpColVector qvel;
376  // Save measured joint velocities of the robot in the log file:
377  // - qvel[0], qvel[1], qvel[2] correspond to measured joint translation
378  // velocities in m/s
379  // - qvel[3], qvel[4], qvel[5] correspond to measured joint rotation
380  // velocities in rad/s
381  flog << qvel[0] << " " << qvel[1] << " " << qvel[2] << " "
382  << qvel[3] << " " << qvel[4] << " " << qvel[5] << " ";
383 
384  // Get the measured joint positions of the robot
385  vpColVector q;
387  // Save measured joint positions of the robot in the log file
388  // - q[0], q[1], q[2] correspond to measured joint translation
389  // positions in m
390  // - q[3], q[4], q[5] correspond to measured joint rotation
391  // positions in rad
392  flog << q[0] << " " << q[1] << " " << q[2] << " "
393  << q[3] << " " << q[4] << " " << q[5] << " ";
394 
395  // Save feature error (s-s*) for the 4 feature points. For each feature
396  // point, we have 2 errors (along x and y axis). This error is expressed
397  // in meters in the camera frame
398  flog << ( task.getError() ).t() << std::endl;
399 
400  // Flush the display
401  vpDisplay::flush(I) ;
402 
403  // vpTRACE("\t\t || s - s* || = %f ", ( task.getError() ).sumSquare()) ;
404  }
405 
406  vpTRACE("Display task information " ) ;
407  kinect.stop();
408  task.print() ;
409  task.kill();
410  flog.close() ; // Close the log file
411  return 0;
412  }
413  catch (...)
414  {
415  flog.close() ; // Close the log file
416  vpERROR_TRACE(" Test failed") ;
417  return 0;
418  }
419 }
420 
421 #else
422 int main()
423 {
424  vpERROR_TRACE("You do not have a Viper robot or a kinect connected to your computer...");
425 
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: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 void display(vpServo &s, const vpCameraParameters &cam, vpImage< unsigned char > &I, vpColor currentColor=vpColor::green, vpColor desiredColor=vpColor::red, unsigned int thickness=1)
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:289
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:379
Control of Irisa's Viper S850 robot named Viper850.
#define vpTRACE
Definition: vpDebug.h:401
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)
create a new ste of two visual features
Definition: vpServo.cpp:444
void setLambda(double _lambda)
set the gain lambda
Definition: vpServo.h:250
vpRobot::vpRobotStateType setRobotState(vpRobot::vpRobotStateType newState)
void set_x(const double x)
Set the point x coordinate in the image plane.
Definition: vpPoint.h:183
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:168
This tracker is meant to track a blob (connex pixels with same gray level) on a vpImage.
Definition: vpDot2.h:114
Driver for the Kinect device.
Definition: vpKinect.h:112
void track(const vpImage< unsigned char > &I)
Definition: vpDot2.cpp:439
static void flush(const vpImage< unsigned char > &I)
Definition: vpDisplay.cpp:1964
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:254
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:358
void kill()
destruction (memory deallocation if required)
Definition: vpServo.cpp:177
Initialize the velocity controller.
Definition: vpRobot.h:70
vpColVector getError() const
Definition: vpServo.h:298
vpColVector computeControlLaw()
compute the desired control law
Definition: vpServo.cpp:883
static void display(const vpImage< unsigned char > &I)
Definition: vpDisplay.cpp:186
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:80
double computeResidual(vpHomogeneousMatrix &cMo)
Compute and return the residual expressed in meter for the pose matrix 'cMo'.
Definition: vpPose.cpp:255
Generic class defining intrinsic camera parameters.
void set_y(const double y)
Set the point y coordinate in the image plane.
Definition: vpPoint.h:185
static std::string getUserName()
Definition: vpIoTools.cpp:136
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)
Set the type of the interaction matrix (current, mean, desired, user).
Definition: vpServo.cpp:509
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 getCameraParameters(vpCameraParameters &cam, const unsigned int &image_width, const unsigned int &image_height)
Definition: vpViper850.cpp:576
void stop()
Definition: vpKinect.cpp:121
void initTracking(const vpImage< unsigned char > &I, unsigned int size=0)
Definition: vpDot2.cpp:240
void print(const vpServo::vpServoPrintType display_level=ALL, std::ostream &os=std::cout)
Definition: vpServo.cpp:258
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:298
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
Class required to compute the visual servoing control law.
Definition: vpServo.h:150
void addPoint(const vpPoint &P)
Add a new point in this array.
Definition: vpPose.cpp:148
void buildFrom(const double phi, const double theta, const double psi)
Definition: vpRxyzVector.h:188
Class that consider the case of a translation vector.
void setServo(vpServoType _servo_type)
Choice of the visual servoing control law.
Definition: vpServo.cpp:214
static const vpColor blue
Definition: vpColor.h:171
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