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