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