Visual Servoing Platform  version 3.5.0 under development (2022-02-15)
mbot-apriltag-2D-half-vs.cpp
1 #include <visp3/core/vpXmlParserCamera.h>
3 #include <visp3/core/vpSerial.h>
4 #include <visp3/detection/vpDetectorAprilTag.h>
5 #include <visp3/gui/vpDisplayX.h>
6 #include <visp3/sensor/vpV4l2Grabber.h>
7 #include <visp3/io/vpImageIo.h>
8 #include <visp3/visual_features/vpFeatureBuilder.h>
9 #include <visp3/visual_features/vpFeatureDepth.h>
10 #include <visp3/visual_features/vpFeaturePoint.h>
11 #include <visp3/vs/vpServo.h>
12 #include <visp3/robot/vpUnicycle.h>
13 #include <visp3/core/vpPolygon.h>
14 
15 int main(int argc, const char **argv)
16 {
17 #if defined(VISP_HAVE_APRILTAG) && defined(VISP_HAVE_V4L2)
18  int device = 0;
21  double tagSize = 0.065;
22  float quad_decimate = 4.0;
23  int nThreads = 2;
24  std::string intrinsic_file = "";
25  std::string camera_name = "";
26  bool display_tag = false;
27  bool display_on = false;
28  bool serial_off = false;
29  bool use_pose = true;
30  bool save_image = false; // Only possible if display_on = true
31 
32  for (int i = 1; i < argc; i++) {
33  if (std::string(argv[i]) == "--without_pose_computation") {
34  use_pose = false;
35  } else if (std::string(argv[i]) == "--tag_size" && i + 1 < argc) {
36  tagSize = std::atof(argv[i + 1]);
37  } else if (std::string(argv[i]) == "--input" && i + 1 < argc) {
38  device = std::atoi(argv[i + 1]);
39  } else if (std::string(argv[i]) == "--quad_decimate" && i + 1 < argc) {
40  quad_decimate = (float)atof(argv[i + 1]);
41  } else if (std::string(argv[i]) == "--nthreads" && i + 1 < argc) {
42  nThreads = std::atoi(argv[i + 1]);
43  } else if (std::string(argv[i]) == "--intrinsic" && i + 1 < argc) {
44  intrinsic_file = std::string(argv[i + 1]);
45  } else if (std::string(argv[i]) == "--camera_name" && i + 1 < argc) {
46  camera_name = std::string(argv[i + 1]);
47  } else if (std::string(argv[i]) == "--display_tag") {
48  display_tag = true;
49 #if defined(VISP_HAVE_X11)
50  } else if (std::string(argv[i]) == "--display_on") {
51  display_on = true;
52  } else if (std::string(argv[i]) == "--save_image") {
53  save_image = true;
54 #endif
55  } else if (std::string(argv[i]) == "--serial_off") {
56  serial_off = true;
57  } else if (std::string(argv[i]) == "--tag_family" && i + 1 < argc) {
58  tagFamily = (vpDetectorAprilTag::vpAprilTagFamily)atoi(argv[i + 1]);
59  } else if (std::string(argv[i]) == "--help" || std::string(argv[i]) == "-h") {
60  std::cout << "Usage: " << argv[0]
61  << " [--input <camera input>] [--tag_size <tag_size in m>]"
62  " [--quad_decimate <quad_decimate>] [--nthreads <nb>]"
63  " [--intrinsic <intrinsic file>] [--camera_name <camera name>] [--without_pose_computation]"
64  " [--tag_family <family> (0: TAG_36h11, 1: TAG_36h10, 2: TAG_36ARTOOLKIT,"
65  " 3: TAG_25h9, 4: TAG_25h7, 5: TAG_16h5)]"
66  " [--display_tag]";
67 #if defined(VISP_HAVE_X11)
68  std::cout << " [--display_on] [--save_image]";
69 #endif
70  std::cout << " [--serial_off] [--help]" << std::endl;
71  return EXIT_SUCCESS;
72  }
73  }
74 
75  // Me Auriga led ring
76  // if serial com ok: led 1 green
77  // if exception: led 1 red
78  // if tag detected: led 2 green, else led 2 red
79  // if motor left: led 3 blue
80  // if motor right: led 4 blue
81 
82  vpSerial *serial = NULL;
83  if (! serial_off) {
84  serial = new vpSerial("/dev/ttyAMA0", 115200);
85 
86  serial->write("LED_RING=0,0,0,0\n"); // Switch off all led
87  serial->write("LED_RING=1,0,10,0\n"); // Switch on led 1 to green: serial ok
88  }
89 
90  try {
92 
93  vpV4l2Grabber g;
94  std::ostringstream device_name;
95  device_name << "/dev/video" << device;
96  g.setDevice(device_name.str());
97  g.setScale(1);
98  g.acquire(I);
99 
100  vpDisplay *d = NULL;
101  vpImage<vpRGBa> O;
102 #ifdef VISP_HAVE_X11
103  if (display_on) {
104  d = new vpDisplayX(I);
105  }
106 #endif
107 
108  vpCameraParameters cam;
109  cam.initPersProjWithoutDistortion(615.1674805, 615.1675415, I.getWidth() / 2., I.getHeight() / 2.);
110  vpXmlParserCamera parser;
111  if (!intrinsic_file.empty() && !camera_name.empty())
112  parser.parse(cam, intrinsic_file, camera_name, vpCameraParameters::perspectiveProjWithoutDistortion);
113 
114  std::cout << "cam:\n" << cam << std::endl;
115  std::cout << "use pose: " << use_pose << std::endl;
116  std::cout << "tagFamily: " << tagFamily << std::endl;
117 
118  vpDetectorAprilTag detector(tagFamily);
119 
120  detector.setAprilTagQuadDecimate(quad_decimate);
121  if (use_pose)
122  detector.setAprilTagPoseEstimationMethod(poseEstimationMethod);
123  detector.setAprilTagNbThreads(nThreads);
124  detector.setDisplayTag(display_tag);
125 
126  vpServo task;
127  vpAdaptiveGain lambda;
128  if (display_on)
129  lambda.initStandard(2.5, 0.4, 30); // lambda(0)=2.5, lambda(oo)=0.4 and lambda'(0)=30
130  else
131  lambda.initStandard(4, 0.4, 30); // lambda(0)=4, lambda(oo)=0.4 and lambda'(0)=30
132 
133  vpUnicycle robot;
136  task.setLambda(lambda);
137  vpRotationMatrix cRe;
138  cRe[0][0] = 0; cRe[0][1] = -1; cRe[0][2] = 0;
139  cRe[1][0] = 0; cRe[1][1] = 0; cRe[1][2] = -1;
140  cRe[2][0] = 1; cRe[2][1] = 0; cRe[2][2] = 0;
141 
143  vpVelocityTwistMatrix cVe(cMe);
144  task.set_cVe(cVe);
145 
146  vpMatrix eJe(6, 2, 0);
147  eJe[0][0] = eJe[5][1] = 1.0;
148 
149  std::cout << "eJe: \n" << eJe << std::endl;
150 
151  // Current and desired visual feature associated to the x coordinate of the point
152  vpFeaturePoint s_x, s_xd;
153  vpImagePoint cog;
154  double Z, Z_d;
155  Z = Z_d = 0.4;
156 
157  // Create the current x visual feature
158  vpFeatureBuilder::create(s_x, cam, cog);
159 
160  // Create the desired x* visual feature
161  s_xd.buildFrom(0, 0, Z_d);
162 
163  // Add the point feature
164  task.addFeature(s_x, s_xd, vpFeaturePoint::selectX());
165 
166  // Create the log(Z/Z*) visual feature
167  vpFeatureDepth s_Z, s_Z_d;
168 
169  std::cout << "Z " << Z << std::endl;
170  s_Z.buildFrom(s_x.get_x(), s_x.get_y(), Z, 0); // log(Z/Z*) = 0 that's why the last parameter is 0
171  s_Z_d.buildFrom(0, 0, Z_d, 0); // The value of s* is 0 with Z=1 meter
172 
173  // Add the feature
174  task.addFeature(s_Z, s_Z_d);
175 
176  std::vector<double> time_vec;
177  for (;;) {
178  g.acquire(I);
179 
181 
182  double t = vpTime::measureTimeMs();
183  std::vector<vpHomogeneousMatrix> cMo_vec;
184  if (use_pose)
185  detector.detect(I, tagSize, cam, cMo_vec);
186  else
187  detector.detect(I);
188 
189  t = vpTime::measureTimeMs() - t;
190  time_vec.push_back(t);
191 
192  {
193  std::stringstream ss;
194  ss << "Detection time: " << t << " ms";
195  vpDisplay::displayText(I, 40, 20, ss.str(), vpColor::red);
196  }
197 
198  if (detector.getNbObjects() == 1) {
199  // Display visual features
200  vpHomogeneousMatrix cdMo(0, 0, Z_d, 0, 0, 0);
201  vpDisplay::displayFrame(I, cdMo, cam, tagSize / 3, vpColor::red, 3);
202  vpDisplay::displayCross(I, detector.getCog(0), 15, vpColor::green, 3); // Current polygon used to compure an moment
203  vpDisplay::displayLine(I, 0, cam.get_u0(), I.getHeight()-1, cam.get_u0(), vpColor::red, 3); // Vertical line as desired x position
204  if (use_pose) {
205  // Display visual features
206  vpDisplay::displayFrame(I, cMo_vec[0], cam, tagSize / 2, vpColor::none, 3);
207  }
208 
209  if (! serial_off) {
210  serial->write("LED_RING=2,0,10,0\n"); // Switch on led 2 to green: tag detected
211  }
212 
213  if (use_pose) {
214  Z = cMo_vec[0][2][3];
215  }
216  else {
217  vpPolygon polygon(detector.getPolygon(0));
218  double surface = polygon.getArea();
219  std::cout << "Surface: " << surface << std::endl;
220 
221  // Compute the distance from target surface and 3D size
222  Z = tagSize * cam.get_px() / sqrt(surface);
223  }
224 
225  vpFeatureBuilder::create(s_x, cam, detector.getCog(0));
226  s_x.set_Z(Z);
227 
228  // Update log(Z/Z*) feature
229  s_Z.buildFrom(s_x.get_x(), s_x.get_y(), Z, log(Z / Z_d));
230 
231  std::cout << "cog: " << detector.getCog(0) << " Z: " << Z << std::endl;
232 
233  task.set_cVe(cVe);
234  task.set_eJe(eJe);
235 
236  // Compute the control law. Velocities are computed in the mobile robot reference frame
237  vpColVector v = task.computeControlLaw();
238 
239  std::cout << "Send velocity to the mbot: " << v[0] << " m/s " << vpMath::deg(v[1]) << " deg/s" << std::endl;
240 
241  task.print();
242  double radius = 0.0325;
243  double L = 0.0725;
244  double motor_left = (-v[0] - L * v[1]) / radius;
245  double motor_right = ( v[0] - L * v[1]) / radius;
246  std::cout << "motor left vel: " << motor_left << " motor right vel: " << motor_right << std::endl;
247  if (! serial_off) {
248 // serial->write("LED_RING=3,0,0,10\n"); // Switch on led 3 to blue: motor left servoed
249 // serial->write("LED_RING=4,0,0,10\n"); // Switch on led 4 to blue: motor right servoed
250  }
251  std::stringstream ss;
252  double rpm_left = motor_left * 30. / M_PI;
253  double rpm_right = motor_right * 30. / M_PI;
254  ss << "MOTOR_RPM=" << vpMath::round(rpm_left) << "," << vpMath::round(rpm_right) << "\n";
255  std::cout << "Send: " << ss.str() << std::endl;
256  if (! serial_off) {
257  serial->write(ss.str());
258  }
259  }
260  else {
261  // stop the robot
262  if (! serial_off) {
263  serial->write("LED_RING=2,10,0,0\n"); // Switch on led 2 to red: tag not detected
264 // serial->write("LED_RING=3,0,0,0\n"); // Switch on led 3 to blue: motor left not servoed
265 // serial->write("LED_RING=4,0,0,0\n"); // Switch on led 4 to blue: motor right not servoed
266  serial->write("MOTOR_RPM=0,-0\n"); // Stop the robot
267  }
268  }
269 
270  vpDisplay::displayText(I, 20, 20, "Click to quit.", vpColor::red);
271  vpDisplay::flush(I);
272  if (display_on && save_image) {
273  vpDisplay::getImage(I, O);
274  vpImageIo::write(O, "image.png");
275  }
276  if (vpDisplay::getClick(I, false))
277  break;
278  }
279 
280  if (! serial_off) {
281  serial->write("LED_RING=0,0,0,0\n"); // Switch off all led
282  }
283 
284  std::cout << "Benchmark computation time" << std::endl;
285  std::cout << "Mean / Median / Std: " << vpMath::getMean(time_vec) << " ms"
286  << " ; " << vpMath::getMedian(time_vec) << " ms"
287  << " ; " << vpMath::getStdev(time_vec) << " ms" << std::endl;
288 
289  if (display_on)
290  delete d;
291  if (! serial_off) {
292  delete serial;
293  }
294  } catch (const vpException &e) {
295  std::cerr << "Catch an exception: " << e.getMessage() << std::endl;
296  if (! serial_off) {
297  serial->write("LED_RING=1,10,0,0\n"); // Switch on led 1 to red
298  }
299  }
300 
301  return EXIT_SUCCESS;
302 #else
303  (void)argc;
304  (void)argv;
305 #ifndef VISP_HAVE_APRILTAG
306  std::cout << "ViSP is not build with Apriltag support" << std::endl;
307 #endif
308 #ifndef VISP_HAVE_V4L2
309  std::cout << "ViSP is not build with v4l2 support" << std::endl;
310 #endif
311  std::cout << "Install missing 3rd parties, configure and build ViSP to run this tutorial" << std::endl;
312  return EXIT_SUCCESS;
313 #endif
314 }
Implementation of a matrix and operations on matrices.
Definition: vpMatrix.h:153
void acquire(vpImage< unsigned char > &I)
Adaptive gain computation.
Class that defines generic functionnalities for display.
Definition: vpDisplay.h:177
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
void buildFrom(double x, double y, double Z)
void setAprilTagPoseEstimationMethod(const vpPoseEstimationMethod &poseEstimationMethod)
Implementation of an homogeneous matrix and operations on such kind of matrices.
AprilTag 36h11 pattern (recommended)
void addFeature(vpBasicFeature &s, vpBasicFeature &s_star, unsigned int select=vpBasicFeature::FEATURE_ALL)
Definition: vpServo.cpp:490
static double getMedian(const std::vector< double > &v)
Definition: vpMath.cpp:261
void set_eJe(const vpMatrix &eJe_)
Definition: vpServo.h:506
static double getStdev(const std::vector< double > &v, bool useBesselCorrection=false)
Definition: vpMath.cpp:291
static void displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:134
void setDevice(const std::string &devname)
void buildFrom(double x, double y, double Z, double LogZoverZstar)
static const vpColor none
Definition: vpColor.h:229
Class that defines a 3D point visual feature which is composed by one parameters that is that defin...
error that can be emited by ViSP classes.
Definition: vpException.h:71
Class that defines a 2D point visual feature which is composed by two parameters that are the cartes...
size_t getNbObjects() const
const char * getMessage() const
Definition: vpException.cpp:90
XML parser to load and save intrinsic camera parameters.
static const vpColor green
Definition: vpColor.h:220
static void flush(const vpImage< unsigned char > &I)
void write(const std::string &s)
Definition: vpSerial.cpp:343
static void write(const vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Definition: vpImageIo.cpp:293
VISP_EXPORT double measureTimeMs()
Definition: vpTime.cpp:126
static const vpColor red
Definition: vpColor.h:217
Implementation of a rotation matrix and operations on such kind of matrices.
void setAprilTagQuadDecimate(float quadDecimate)
Generic functions for unicycle mobile robots.
Definition: vpUnicycle.h:56
static double getMean(const std::vector< double > &v)
Definition: vpMath.cpp:241
Defines a generic 2D polygon.
Definition: vpPolygon.h:103
void initStandard(double gain_at_zero, double gain_at_infinity, double slope_at_zero)
vpColVector computeControlLaw()
Definition: vpServo.cpp:929
static unsigned int selectX()
void set_Z(double Z)
static void display(const vpImage< unsigned char > &I)
Generic class defining intrinsic camera parameters.
void setAprilTagNbThreads(int nThreads)
void setLambda(double c)
Definition: vpServo.h:404
double get_x() const
void setScale(unsigned scale=vpV4l2Grabber::DEFAULT_SCALE)
vpImagePoint getCog(size_t i) const
static void getImage(const vpImage< unsigned char > &Is, vpImage< vpRGBa > &Id)
Definition: vpDisplay.cpp:144
void setInteractionMatrixType(const vpServoIteractionMatrixType &interactionMatrixType, const vpServoInversionType &interactionMatrixInversion=PSEUDO_INVERSE)
Definition: vpServo.cpp:567
int parse(vpCameraParameters &cam, const std::string &filename, const std::string &camera_name, const vpCameraParameters::vpCameraParametersProjType &projModel, unsigned int image_width=0, unsigned int image_height=0)
void initPersProjWithoutDistortion(double px, double py, double u0, double v0)
static int round(double x)
Definition: vpMath.h:247
static void displayCross(const vpImage< unsigned char > &I, const vpImagePoint &ip, unsigned int size, const vpColor &color, unsigned int thickness=1)
Class that is a wrapper over the Video4Linux2 (V4L2) driver.
static double deg(double rad)
Definition: vpMath.h:103
unsigned int getHeight() const
Definition: vpImage.h:188
Implementation of column vector and the associated operations.
Definition: vpColVector.h:130
static void displayFrame(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cMo, const vpCameraParameters &cam, double size, const vpColor &color=vpColor::none, unsigned int thickness=1, const vpImagePoint &offset=vpImagePoint(0, 0))
void setDisplayTag(bool display, const vpColor &color=vpColor::none, unsigned int thickness=2)
void set_cVe(const vpVelocityTwistMatrix &cVe_)
Definition: vpServo.h:448
double get_y() const
void print(const vpServo::vpServoPrintType display_level=ALL, std::ostream &os=std::cout)
Definition: vpServo.cpp:306
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:87
static void create(vpFeaturePoint &s, const vpCameraParameters &cam, const vpDot &d)
unsigned int getWidth() const
Definition: vpImage.h:246
void setServo(const vpServoType &servo_type)
Definition: vpServo.cpp:218
static void displayLine(const vpImage< unsigned char > &I, const vpImagePoint &ip1, const vpImagePoint &ip2, const vpColor &color, unsigned int thickness=1, bool segment=true)
Class that consider the case of a translation vector.
std::vector< std::vector< vpImagePoint > > & getPolygon()
bool detect(const vpImage< unsigned char > &I)