Visual Servoing Platform  version 3.6.1 under development (2024-04-25)
tutorial-mb-generic-tracker-apriltag-webcam.cpp
1 #include <fstream>
3 #include <ios>
4 #include <iostream>
5 
6 #include <visp3/core/vpXmlParserCamera.h>
7 #include <visp3/detection/vpDetectorAprilTag.h>
8 #include <visp3/gui/vpDisplayGDI.h>
9 #include <visp3/gui/vpDisplayOpenCV.h>
10 #include <visp3/gui/vpDisplayX.h>
11 #include <visp3/mbt/vpMbGenericTracker.h>
12 #include <visp3/sensor/vpV4l2Grabber.h>
13 
14 #if defined(HAVE_OPENCV_VIDEOIO)
15 #include <opencv2/videoio.hpp>
16 #endif
17 
18 typedef enum { state_detection, state_tracking, state_quit } state_t;
19 
20 // Creates a cube.cao file in your current directory
21 // cubeEdgeSize : size of cube edges in meters
22 void createCaoFile(double cubeEdgeSize)
23 {
24  std::ofstream fileStream;
25  fileStream.open("cube.cao", std::ofstream::out | std::ofstream::trunc);
26  fileStream << "V1\n";
27  fileStream << "# 3D Points\n";
28  fileStream << "8 # Number of points\n";
29  fileStream << cubeEdgeSize / 2 << " " << cubeEdgeSize / 2 << " " << 0 << " # Point 0: (X, Y, Z)\n";
30  fileStream << cubeEdgeSize / 2 << " " << -cubeEdgeSize / 2 << " " << 0 << " # Point 1\n";
31  fileStream << -cubeEdgeSize / 2 << " " << -cubeEdgeSize / 2 << " " << 0 << " # Point 2\n";
32  fileStream << -cubeEdgeSize / 2 << " " << cubeEdgeSize / 2 << " " << 0 << " # Point 3\n";
33  fileStream << -cubeEdgeSize / 2 << " " << cubeEdgeSize / 2 << " " << -cubeEdgeSize << " # Point 4\n";
34  fileStream << -cubeEdgeSize / 2 << " " << -cubeEdgeSize / 2 << " " << -cubeEdgeSize << " # Point 5\n";
35  fileStream << cubeEdgeSize / 2 << " " << -cubeEdgeSize / 2 << " " << -cubeEdgeSize << " # Point 6\n";
36  fileStream << cubeEdgeSize / 2 << " " << cubeEdgeSize / 2 << " " << -cubeEdgeSize << " # Point 7\n";
37  fileStream << "# 3D Lines\n";
38  fileStream << "0 # Number of lines\n";
39  fileStream << "# Faces from 3D lines\n";
40  fileStream << "0 # Number of faces\n";
41  fileStream << "# Faces from 3D points\n";
42  fileStream << "6 # Number of faces\n";
43  fileStream << "4 0 3 2 1 # Face 0: [number of points] [index of the 3D points]...\n";
44  fileStream << "4 1 2 5 6\n";
45  fileStream << "4 4 7 6 5\n";
46  fileStream << "4 0 7 4 3\n";
47  fileStream << "4 5 2 3 4\n";
48  fileStream << "4 0 1 6 7 # Face 5\n";
49  fileStream << "# 3D cylinders\n";
50  fileStream << "0 # Number of cylinders\n";
51  fileStream << "# 3D circles\n";
52  fileStream << "0 # Number of circles\n";
53  fileStream.close();
54 }
55 
56 #if defined(VISP_HAVE_APRILTAG)
57 state_t detectAprilTag(const vpImage<unsigned char> &I, vpDetectorAprilTag &detector, double tagSize,
58  const vpCameraParameters &cam, vpHomogeneousMatrix &cMo)
59 {
60  std::vector<vpHomogeneousMatrix> cMo_vec;
61 
62  // Detection
63  bool ret = detector.detect(I, tagSize, cam, cMo_vec);
64 
65  // Display camera pose
66  for (size_t i = 0; i < cMo_vec.size(); i++) {
67  vpDisplay::displayFrame(I, cMo_vec[i], cam, tagSize / 2, vpColor::none, 3);
68  }
69 
70  vpDisplay::displayText(I, 40, 20, "State: waiting tag detection", vpColor::red);
71 
72  if (ret && detector.getNbObjects() > 0) { // if tag detected, we pick the first one
73  cMo = cMo_vec[0];
74  return state_tracking;
75  }
76 
77  return state_detection;
78 }
79 #endif // #if defined(VISP_HAVE_APRILTAG)
80 
81 state_t track(const vpImage<unsigned char> &I, vpMbGenericTracker &tracker, double projection_error_threshold,
83 {
85  tracker.getCameraParameters(cam);
86 
87  // Track the object
88  try {
89  tracker.track(I);
90  }
91  catch (...) {
92  return state_detection;
93  }
94 
95  tracker.getPose(cMo);
96 
97  // Detect tracking error
98  double projection_error = tracker.computeCurrentProjectionError(I, cMo, cam);
99  if (projection_error > projection_error_threshold) {
100  return state_detection;
101  }
102 
103  // Display
104  tracker.display(I, cMo, cam, vpColor::red, 2);
105  vpDisplay::displayFrame(I, cMo, cam, 0.025, vpColor::none, 3);
106  vpDisplay::displayText(I, 40, 20, "State: tracking in progress", vpColor::red);
107  {
108  std::stringstream ss;
109  ss << "Features: edges " << tracker.getNbFeaturesEdge() << ", klt " << tracker.getNbFeaturesKlt();
110  vpDisplay::displayText(I, 60, 20, ss.str(), vpColor::red);
111  }
112 
113  return state_tracking;
114 }
115 
116 int main(int argc, const char **argv)
117 {
119 #if defined(VISP_HAVE_APRILTAG) && (defined(VISP_HAVE_V4L2) || defined(HAVE_OPENCV_VIDEOIO)) && defined(VISP_HAVE_MODULE_MBT)
121 
122  int opt_device = 0;
124  double opt_tag_size = 0.08;
125  float opt_quad_decimate = 1.0;
126  int opt_nthreads = 1;
127  std::string opt_intrinsic_file = "";
128  std::string opt_camera_name = "";
129  double opt_cube_size = 0.125; // 12.5cm by default
130 #ifdef VISP_HAVE_OPENCV
131  bool opt_use_texture = false;
132 #endif
133  double opt_projection_error_threshold = 40.;
134 
135 #if !(defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI) || defined(VISP_HAVE_OPENCV))
136  bool display_off = true;
137 #else
138  bool display_off = false;
139 #endif
140 
141  for (int i = 1; i < argc; i++) {
142  if (std::string(argv[i]) == "--tag_size" && i + 1 < argc) {
143  opt_tag_size = atof(argv[i + 1]);
144  }
145  else if (std::string(argv[i]) == "--input" && i + 1 < argc) {
146  opt_device = atoi(argv[i + 1]);
147  }
148  else if (std::string(argv[i]) == "--quad_decimate" && i + 1 < argc) {
149  opt_quad_decimate = (float)atof(argv[i + 1]);
150  }
151  else if (std::string(argv[i]) == "--nthreads" && i + 1 < argc) {
152  opt_nthreads = atoi(argv[i + 1]);
153  }
154  else if (std::string(argv[i]) == "--intrinsic" && i + 1 < argc) {
155  opt_intrinsic_file = std::string(argv[i + 1]);
156  }
157  else if (std::string(argv[i]) == "--camera_name" && i + 1 < argc) {
158  opt_camera_name = std::string(argv[i + 1]);
159  }
160  else if (std::string(argv[i]) == "--display_off") {
161  display_off = true;
162  }
163  else if (std::string(argv[i]) == "--tag_family" && i + 1 < argc) {
164  opt_tag_family = (vpDetectorAprilTag::vpAprilTagFamily)atoi(argv[i + 1]);
165  }
166  else if (std::string(argv[i]) == "--cube_size" && i + 1 < argc) {
167  opt_cube_size = atof(argv[i + 1]);
168 #ifdef VISP_HAVE_OPENCV
169  }
170  else if (std::string(argv[i]) == "--texture") {
171  opt_use_texture = true;
172 #endif
173  }
174  else if (std::string(argv[i]) == "--projection_error" && i + 1 < argc) {
175  opt_projection_error_threshold = atof(argv[i + 1]);
176  }
177  else if (std::string(argv[i]) == "--help" || std::string(argv[i]) == "-h") {
178  std::cout << "Usage: " << argv[0]
179  << " [--input <camera id>] [--cube_size <size in m>] [--tag_size <size in m>]"
180  " [--quad_decimate <decimation>] [--nthreads <nb>]"
181  " [--intrinsic <xml intrinsic file>] [--camera_name <camera name in xml file>]"
182  " [--tag_family <0: TAG_36h11, 1: TAG_36h10, 2: TAG_36ARTOOLKIT, "
183  " 3: TAG_25h9, 4: TAG_25h7, 5: TAG_16h5>]";
184 #if (defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI) || defined(VISP_HAVE_OPENCV))
185  std::cout << " [--display_off]";
186 #endif
187  std::cout << " [--texture] [--projection_error <30 - 100>] [--help]" << std::endl;
188  return EXIT_SUCCESS;
189  }
190  }
191 
192  createCaoFile(opt_cube_size);
193 
194  vpCameraParameters cam;
195  bool camIsInit = false;
196 #if defined(VISP_HAVE_PUGIXML)
197  vpXmlParserCamera parser;
198  if (!opt_intrinsic_file.empty() && !opt_camera_name.empty()) {
199  parser.parse(cam, opt_intrinsic_file, opt_camera_name, vpCameraParameters::perspectiveProjWithoutDistortion);
200  camIsInit = true;
201  }
202 #endif
203 
204  try {
206 
208 #if defined(VISP_HAVE_V4L2)
209  vpV4l2Grabber g;
210  std::ostringstream device;
211  device << "/dev/video" << opt_device;
212  std::cout << "Use device " << device.str() << " (v4l2 grabber)" << std::endl;
213  g.setDevice(device.str());
214  g.setScale(1);
215  g.acquire(I);
216 #elif defined(HAVE_OPENCV_VIDEOIO)
217  std::cout << "Use device " << opt_device << " (OpenCV grabber)" << std::endl;
218  cv::VideoCapture cap(opt_device); // open the default camera
219  if (!cap.isOpened()) { // check if we succeeded
220  std::cout << "Failed to open the camera" << std::endl;
221  return EXIT_FAILURE;
222  }
223  cv::Mat frame;
224  cap >> frame; // get a new frame from camera
225  vpImageConvert::convert(frame, I);
226 #endif
227  if (!camIsInit) {
228  cam.initPersProjWithoutDistortion(600, 600, I.getWidth() / 2., I.getHeight() / 2.);
229  }
230 
231  std::cout << "Cube size: " << opt_cube_size << std::endl;
232  std::cout << "AprilTag size: " << opt_tag_size << std::endl;
233  std::cout << "AprilTag family: " << opt_tag_family << std::endl;
234  std::cout << "Camera parameters:\n" << cam << std::endl;
235  std::cout << "Detection: " << std::endl;
236  std::cout << " Quad decimate: " << opt_quad_decimate << std::endl;
237  std::cout << " Threads number: " << opt_nthreads << std::endl;
238  std::cout << "Tracker: " << std::endl;
239  std::cout << " Use edges : 1" << std::endl;
240  std::cout << " Use texture: "
241 #ifdef VISP_HAVE_OPENCV
242  << opt_use_texture << std::endl;
243 #else
244  << " na" << std::endl;
245 #endif
246  std::cout << " Projection error: " << opt_projection_error_threshold << std::endl;
247 
248  // Construct display
249  vpDisplay *d = nullptr;
250  if (!display_off) {
251 #ifdef VISP_HAVE_X11
252  d = new vpDisplayX(I);
253 #elif defined(VISP_HAVE_GDI)
254  d = new vpDisplayGDI(I);
255 #elif defined(HAVE_OPENCV_HIGHGUI)
256  d = new vpDisplayOpenCV(I);
257 #endif
258  }
259 
260  // Initialize AprilTag detector
261  vpDetectorAprilTag detector(opt_tag_family);
262  detector.setAprilTagQuadDecimate(opt_quad_decimate);
263  detector.setAprilTagNbThreads(opt_nthreads);
264 
265  // Prepare MBT
266  vpMbGenericTracker tracker;
267 #if defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_VIDEO)
268  if (opt_use_texture)
270  else
271 #endif
273  // edges
274  vpMe me;
275  me.setMaskSize(5);
276  me.setMaskNumber(180);
277  me.setRange(12);
279  me.setThreshold(20);
280  me.setMu1(0.5);
281  me.setMu2(0.5);
282  me.setSampleStep(4);
283  tracker.setMovingEdge(me);
284 
285 #if defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_VIDEO)
286  if (opt_use_texture) {
287  vpKltOpencv klt_settings;
288  klt_settings.setMaxFeatures(300);
289  klt_settings.setWindowSize(5);
290  klt_settings.setQuality(0.015);
291  klt_settings.setMinDistance(8);
292  klt_settings.setHarrisFreeParameter(0.01);
293  klt_settings.setBlockSize(3);
294  klt_settings.setPyramidLevels(3);
295  tracker.setKltOpencv(klt_settings);
296  tracker.setKltMaskBorder(5);
297  }
298 #endif
299 
300  // camera calibration params
301  tracker.setCameraParameters(cam);
302  // model definition
303  tracker.loadModel("cube.cao");
304  tracker.setDisplayFeatures(true);
305  tracker.setAngleAppear(vpMath::rad(70));
306  tracker.setAngleDisappear(vpMath::rad(80));
307 
309  state_t state = state_detection;
310 
311  // wait for a tag detection
312  while (state != state_quit) {
313 
314 #if defined(VISP_HAVE_V4L2)
315  g.acquire(I);
316 #elif defined(HAVE_OPENCV_VIDEOIO)
317  cap >> frame;
318  vpImageConvert::convert(frame, I);
319 #endif
320 
322 
323  if (state == state_detection) {
324  state = detectAprilTag(I, detector, opt_tag_size, cam, cMo);
325 
326  // Initialize the tracker with the result of the detection
327  if (state == state_tracking) {
329  tracker.initFromPose(I, cMo);
331  }
332  }
333 
334  if (state == state_tracking) {
335  state = track(I, tracker, opt_projection_error_threshold, cMo);
336  }
337 
338  vpDisplay::displayText(I, 20, 20, "Click to quit...", vpColor::red);
339  if (vpDisplay::getClick(I, false)) { // exit
340  state = state_quit;
341  }
342 
343  vpDisplay::flush(I);
344  }
345 
346  if (!display_off)
347  delete d;
348  }
349  catch (const vpException &e) {
350  std::cerr << "Catch an exception: " << e.getMessage() << std::endl;
351  }
352 
353  return EXIT_SUCCESS;
354 #else
355  (void)argc;
356  (void)argv;
357 #ifndef VISP_HAVE_APRILTAG
358  std::cout << "ViSP is not build with Apriltag support" << std::endl;
359 #endif
360 #if !(defined(VISP_HAVE_V4L2) || defined(VISP_HAVE_OPENCV))
361  std::cout << "ViSP is not build with v4l2 or OpenCV support" << std::endl;
362 #endif
363  std::cout << "Install missing 3rd parties, configure and build ViSP to run this tutorial" << std::endl;
364 #endif
365  return EXIT_SUCCESS;
366 }
Generic class defining intrinsic camera parameters.
void initPersProjWithoutDistortion(double px, double py, double u0, double v0)
@ perspectiveProjWithoutDistortion
Perspective projection without distortion model.
static const vpColor red
Definition: vpColor.h:211
static const vpColor none
Definition: vpColor.h:223
void setAprilTagQuadDecimate(float quadDecimate)
bool detect(const vpImage< unsigned char > &I) vp_override
@ TAG_36h11
AprilTag 36h11 pattern (recommended)
void setAprilTagNbThreads(int nThreads)
size_t getNbObjects() const
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:128
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:128
Class that defines generic functionalities for display.
Definition: vpDisplay.h:173
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 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:59
const char * getMessage() const
Definition: vpException.cpp:64
Implementation of an homogeneous matrix and operations on such kind of matrices.
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
unsigned int getWidth() const
Definition: vpImage.h:245
unsigned int getHeight() const
Definition: vpImage.h:184
Wrapper for the KLT (Kanade-Lucas-Tomasi) feature tracker implemented in OpenCV. Thus to enable this ...
Definition: vpKltOpencv.h:73
void setBlockSize(int blockSize)
Definition: vpKltOpencv.h:266
void setQuality(double qualityLevel)
Definition: vpKltOpencv.h:355
void setHarrisFreeParameter(double harris_k)
Definition: vpKltOpencv.h:274
void setMaxFeatures(int maxCount)
Definition: vpKltOpencv.h:314
void setMinDistance(double minDistance)
Definition: vpKltOpencv.h:323
void setWindowSize(int winSize)
Definition: vpKltOpencv.h:376
void setPyramidLevels(int pyrMaxLevel)
Definition: vpKltOpencv.h:342
static double rad(double deg)
Definition: vpMath.h:127
Real-time 6D object pose tracking using its CAD model.
virtual void initFromPose(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cMo) vp_override
virtual void setKltMaskBorder(const unsigned int &e)
virtual unsigned int getNbFeaturesEdge() const
virtual void setAngleDisappear(const double &a) vp_override
virtual void getPose(vpHomogeneousMatrix &cMo) const vp_override
virtual void display(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cMo, const vpCameraParameters &cam, const vpColor &col, unsigned int thickness=1, bool displayFullModel=false) vp_override
virtual void getCameraParameters(vpCameraParameters &camera) const vp_override
virtual unsigned int getNbFeaturesKlt() const
virtual void setMovingEdge(const vpMe &me)
virtual void setAngleAppear(const double &a) vp_override
virtual void loadModel(const std::string &modelFile, bool verbose=false, const vpHomogeneousMatrix &T=vpHomogeneousMatrix()) vp_override
virtual void setKltOpencv(const vpKltOpencv &t)
virtual void setCameraParameters(const vpCameraParameters &camera) vp_override
virtual void setTrackerType(int type)
virtual double computeCurrentProjectionError(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &_cMo, const vpCameraParameters &_cam) vp_override
virtual void setDisplayFeatures(bool displayF) vp_override
virtual void track(const vpImage< unsigned char > &I) vp_override
Definition: vpMe.h:124
void setMu1(const double &mu_1)
Definition: vpMe.h:399
void setRange(const unsigned int &range)
Definition: vpMe.h:429
void setLikelihoodThresholdType(const vpLikelihoodThresholdType likelihood_threshold_type)
Definition: vpMe.h:519
void setMaskNumber(const unsigned int &mask_number)
Definition: vpMe.cpp:488
void setThreshold(const double &threshold)
Definition: vpMe.h:480
void setSampleStep(const double &sample_step)
Definition: vpMe.h:436
void setMaskSize(const unsigned int &mask_size)
Definition: vpMe.cpp:496
void setMu2(const double &mu_2)
Definition: vpMe.h:406
@ NORMALIZED_THRESHOLD
Definition: vpMe.h:135
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)