Visual Servoing Platform  version 3.6.1 under development (2024-11-15)
mbot-apriltag-pbvs.cpp
1 #include <visp3/core/vpConfig.h>
3 #include <visp3/core/vpSerial.h>
4 #include <visp3/core/vpXmlParserCamera.h>
5 #include <visp3/detection/vpDetectorAprilTag.h>
6 #include <visp3/gui/vpDisplayFactory.h>
7 #include <visp3/io/vpImageIo.h>
8 #include <visp3/robot/vpUnicycle.h>
9 #include <visp3/sensor/vpV4l2Grabber.h>
10 #include <visp3/visual_features/vpFeaturePoint3D.h>
11 #include <visp3/vs/vpServo.h>
12 
13 int main(int argc, const char **argv)
14 {
15 #if defined(VISP_HAVE_APRILTAG) && defined(VISP_HAVE_V4L2)
16 #ifdef ENABLE_VISP_NAMESPACE
17  using namespace VISP_NAMESPACE_NAME;
18 #endif
19 
20  int device = 0;
23  double tagSize = 0.065;
24  float quad_decimate = 4.0;
25  int nThreads = 2;
26  std::string intrinsic_file = "";
27  std::string camera_name = "";
28  bool display_tag = false;
29  bool display_on = false;
30  bool serial_off = false;
31  bool save_image = false; // Only possible if display_on = true
32 
33  for (int i = 1; i < argc; i++) {
34  if (std::string(argv[i]) == "--tag-size" && i + 1 < argc) {
35  tagSize = std::atof(argv[i + 1]);
36  }
37  else if (std::string(argv[i]) == "--input" && i + 1 < argc) {
38  device = std::atoi(argv[i + 1]);
39  }
40  else if (std::string(argv[i]) == "--quad-decimate" && i + 1 < argc) {
41  quad_decimate = (float)atof(argv[i + 1]);
42  }
43  else if (std::string(argv[i]) == "--nthreads" && i + 1 < argc) {
44  nThreads = std::atoi(argv[i + 1]);
45  }
46  else if (std::string(argv[i]) == "--intrinsic" && i + 1 < argc) {
47  intrinsic_file = std::string(argv[i + 1]);
48  }
49  else if (std::string(argv[i]) == "--camera-name" && i + 1 < argc) {
50  camera_name = std::string(argv[i + 1]);
51  }
52  else if (std::string(argv[i]) == "--display-tag") {
53  display_tag = true;
54 #if defined(VISP_HAVE_DISPLAY)
55  }
56  else if (std::string(argv[i]) == "--display-on") {
57  display_on = true;
58  }
59  else if (std::string(argv[i]) == "--save-image") {
60  save_image = true;
61 #endif
62  }
63  else if (std::string(argv[i]) == "--serial-off") {
64  serial_off = true;
65  }
66  else if (std::string(argv[i]) == "--tag-family" && i + 1 < argc) {
67  tagFamily = (vpDetectorAprilTag::vpAprilTagFamily)atoi(argv[i + 1]);
68  }
69  else if (std::string(argv[i]) == "--help" || std::string(argv[i]) == "-h") {
70  std::cout << "Usage: " << argv[0]
71  << " [--input <camera input>] [--tag-size <tag size in m>]"
72  " [--quad-decimate <quad decimate>] [--nthreads <nb>]"
73  " [--intrinsic <intrinsic file>] [--camera-name <camera name>]"
74  " [--tag-family <family> (0: TAG_36h11, 1: TAG_36h10, 2: TAG_36ARTOOLKIT, 3: TAG_25h9, 4: TAG_25h7, 5: TAG_16h5)]"
75  " [--display-tag]";
76 #if defined(VISP_HAVE_DISPLAY)
77  std::cout << " [--display-on] [--save-image]";
78 #endif
79  std::cout << " [--serial-off] [--help]" << std::endl;
80  return EXIT_SUCCESS;
81  }
82  }
83 
84  // Me Auriga led ring
85  // if serial com ok: led 1 green
86  // if exception: led 1 red
87  // if tag detected: led 2 green, else led 2 red
88  // if motor left: led 3 blue
89  // if motor right: led 4 blue
90 
91  vpSerial *serial = nullptr;
92  if (!serial_off) {
93  serial = new vpSerial("/dev/ttyAMA0", 115200);
94 
95  serial->write("LED_RING=0,0,0,0\n"); // Switch off all led
96  serial->write("LED_RING=1,0,10,0\n"); // Switch on led 1 to green: serial ok
97  }
98 
99  try {
101 
102  vpV4l2Grabber g;
103  std::ostringstream device_name;
104  device_name << "/dev/video" << device;
105  g.setDevice(device_name.str());
106  g.setScale(1);
107  g.acquire(I);
108 
109  vpDisplay *d = nullptr;
110  vpImage<vpRGBa> O;
111 #ifdef VISP_HAVE_DISPLAY
112  if (display_on) {
114  }
115 #endif
116 
117  vpCameraParameters cam;
118  cam.initPersProjWithoutDistortion(615.1674805, 615.1675415, I.getWidth() / 2., I.getHeight() / 2.);
119 
120 #if defined(VISP_HAVE_PUGIXML)
121  vpXmlParserCamera parser;
122  if (!intrinsic_file.empty() && !camera_name.empty()) {
123  parser.parse(cam, intrinsic_file, camera_name, vpCameraParameters::perspectiveProjWithoutDistortion);
124  }
125 #endif
126 
127  std::cout << "cam:\n" << cam << std::endl;
128  std::cout << "tagFamily: " << tagFamily << std::endl;
129 
130  vpDetectorAprilTag detector(tagFamily);
131 
132  detector.setAprilTagQuadDecimate(quad_decimate);
133  detector.setAprilTagPoseEstimationMethod(poseEstimationMethod);
134  detector.setAprilTagNbThreads(nThreads);
135  detector.setDisplayTag(display_tag);
136 
137  vpServo task;
138  vpAdaptiveGain lambda;
139  if (display_on)
140  lambda.initStandard(2.5, 0.4, 30); // lambda(0)=2.5, lambda(oo)=0.4 and lambda'(0)=30
141  else
142  lambda.initStandard(4, 0.4, 30); // lambda(0)=4, lambda(oo)=0.4 and lambda'(0)=30
143 
144  vpUnicycle robot;
147  task.setLambda(lambda);
148  vpRotationMatrix cRe;
149  cRe[0][0] = 0;
150  cRe[0][1] = -1;
151  cRe[0][2] = 0;
152  cRe[1][0] = 0;
153  cRe[1][1] = 0;
154  cRe[1][2] = -1;
155  cRe[2][0] = 1;
156  cRe[2][1] = 0;
157  cRe[2][2] = 0;
158 
160  vpVelocityTwistMatrix cVe(cMe);
161  task.set_cVe(cVe);
162 
163  vpMatrix eJe(6, 2, 0);
164  eJe[0][0] = eJe[5][1] = 1.0;
165 
166  std::cout << "eJe: \n" << eJe << std::endl;
167 
168  // Desired distance to the target
169  double Z_d = 0.4;
170  double X = 0, Y = 0, Z = Z_d;
171 
172  // Create X_3D visual features
173  vpFeaturePoint3D s_XZ, s_XZ_d;
174  s_XZ.buildFrom(0, 0, Z_d);
175  s_XZ_d.buildFrom(0, 0, Z_d);
176 
177  // Create Point 3D X, Z coordinates visual features
178  s_XZ.buildFrom(X, Y, Z);
179  s_XZ_d.buildFrom(0, 0, Z_d); // The value of s* is X=Y=0 and Z=Z_d meter
180 
181  // Add the features
183 
184  std::vector<double> time_vec;
185  for (;;) {
186  g.acquire(I);
187 
189 
190  double t = vpTime::measureTimeMs();
191  std::vector<vpHomogeneousMatrix> cMo_vec;
192  detector.detect(I, tagSize, cam, cMo_vec);
193 
194  t = vpTime::measureTimeMs() - t;
195  time_vec.push_back(t);
196 
197  {
198  std::stringstream ss;
199  ss << "Detection time: " << t << " ms";
200  vpDisplay::displayText(I, 40, 20, ss.str(), vpColor::red);
201  }
202 
203  if (detector.getNbObjects() == 1) {
204  // Display visual features
205  vpHomogeneousMatrix cdMo(0, 0, Z_d, 0, 0, 0);
206  vpDisplay::displayFrame(I, cMo_vec[0], cam, tagSize / 2, vpColor::none, 3);
207  vpDisplay::displayFrame(I, cdMo, cam, tagSize / 3, vpColor::red, 3);
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  X = cMo_vec[0][0][3];
214  Y = cMo_vec[0][1][3];
215  Z = cMo_vec[0][2][3];
216 
217  // Update Point 3D feature
218  s_XZ.set_XYZ(X, Y, Z);
219 
220  std::cout << "X: " << X << " Z: " << Z << std::endl;
221 
222  task.set_cVe(cVe);
223  task.set_eJe(eJe);
224 
225  // Compute the control law. Velocities are computed in the mobile robot reference frame
226  vpColVector v = task.computeControlLaw();
227 
228  std::cout << "Send velocity to the mbot: " << v[0] << " m/s " << vpMath::deg(v[1]) << " deg/s" << std::endl;
229 
230  task.print();
231  double radius = 0.0325;
232  double L = 0.0725;
233  double motor_left = (-v[0] - L * v[1]) / radius;
234  double motor_right = (v[0] - L * v[1]) / radius;
235  std::cout << "motor left vel: " << motor_left << " motor right vel: " << motor_right << std::endl;
236  if (!serial_off) {
237  // serial->write("LED_RING=3,0,0,10\n"); // Switch on led 3 to blue: motor left servoed
238  // serial->write("LED_RING=4,0,0,10\n"); // Switch on led 4 to blue: motor right servoed
239  }
240  std::stringstream ss;
241  double rpm_left = motor_left * 30. / M_PI;
242  double rpm_right = motor_right * 30. / M_PI;
243  ss << "MOTOR_RPM=" << vpMath::round(rpm_left) << "," << vpMath::round(rpm_right) << "\n";
244  std::cout << "Send: " << ss.str() << std::endl;
245  if (!serial_off) {
246  serial->write(ss.str());
247  }
248  }
249  else {
250  // stop the robot
251  if (!serial_off) {
252  serial->write("LED_RING=2,10,0,0\n"); // Switch on led 2 to red: tag not detected
253  // serial->write("LED_RING=3,0,0,0\n"); // Switch on led 3 to blue: motor left not servoed
254  // serial->write("LED_RING=4,0,0,0\n"); // Switch on led 4 to blue: motor right not servoed
255  serial->write("MOTOR_RPM=0,-0\n"); // Stop the robot
256  }
257  }
258 
259  vpDisplay::displayText(I, 20, 20, "Click to quit.", vpColor::red);
260  vpDisplay::flush(I);
261  if (display_on && save_image) {
262  vpDisplay::getImage(I, O);
263  vpImageIo::write(O, "image.png");
264  }
265  if (vpDisplay::getClick(I, false)) {
266  break;
267  }
268  }
269 
270  if (!serial_off) {
271  serial->write("LED_RING=0,0,0,0\n"); // Switch off all led
272  }
273 
274  std::cout << "Benchmark computation time" << std::endl;
275  std::cout << "Mean / Median / Std: " << vpMath::getMean(time_vec) << " ms"
276  << " ; " << vpMath::getMedian(time_vec) << " ms"
277  << " ; " << vpMath::getStdev(time_vec) << " ms" << std::endl;
278 
279  if (display_on) {
280  delete d;
281  }
282  if (!serial_off) {
283  delete serial;
284  }
285  }
286  catch (const vpException &e) {
287  std::cerr << "Catch an exception: " << e.getMessage() << std::endl;
288  if (!serial_off) {
289  serial->write("LED_RING=1,10,0,0\n"); // Switch on led 1 to red
290  }
291  }
292 
293  return EXIT_SUCCESS;
294 #else
295  (void)argc;
296  (void)argv;
297 #ifndef VISP_HAVE_APRILTAG
298  std::cout << "ViSP is not build with Apriltag support" << std::endl;
299 #endif
300 #ifndef VISP_HAVE_V4L2
301  std::cout << "ViSP is not build with v4l2 support" << std::endl;
302 #endif
303  std::cout << "Install missing 3rd parties, configure and build ViSP to run this tutorial" << std::endl;
304  return EXIT_SUCCESS;
305 #endif
306 }
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
@ 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 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 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
Class that defines the 3D point visual feature.
static unsigned int selectX()
void set_XYZ(double X, double Y, double Z)
static unsigned int selectZ()
vpFeaturePoint3D & buildFrom(const vpPoint &p)
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
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
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)
vpDisplay * allocateDisplay()
Return a newly allocated vpDisplay specialization if a GUI library is available or nullptr otherwise.
VISP_EXPORT double measureTimeMs()