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