Visual Servoing Platform  version 3.6.1 under development (2024-11-15)
mbtGenericTrackingDepthOnly.cpp
1 /****************************************************************************
2  *
3  * ViSP, open source Visual Servoing Platform software.
4  * Copyright (C) 2005 - 2023 by Inria. All rights reserved.
5  *
6  * This software is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * See the file LICENSE.txt at the root directory of this source
11  * distribution for additional information about the GNU GPL.
12  *
13  * For using ViSP with software that can not be combined with the GNU
14  * GPL, please contact Inria about acquiring a ViSP Professional
15  * Edition License.
16  *
17  * See https://visp.inria.fr for more information.
18  *
19  * This software was developed at:
20  * Inria Rennes - Bretagne Atlantique
21  * Campus Universitaire de Beaulieu
22  * 35042 Rennes Cedex
23  * France
24  *
25  * If you have questions regarding the use of this file, please contact
26  * Inria at visp@inria.fr
27  *
28  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
29  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
30  *
31  * Description:
32  * Example of tracking with vpGenericTracker on Castel.
33  *
34 *****************************************************************************/
35 
42 #include <cstdlib>
43 #include <iostream>
44 #include <visp3/core/vpConfig.h>
45 
46 #if (defined(VISP_HAVE_MODULE_MBT) && defined(VISP_HAVE_DISPLAY)) && \
47  (defined(VISP_HAVE_LAPACK) || defined(VISP_HAVE_EIGEN3) || defined(VISP_HAVE_OPENCV))
48 
49 #include <visp3/core/vpDebug.h>
50 #include <visp3/core/vpHomogeneousMatrix.h>
51 #include <visp3/core/vpIoTools.h>
52 #include <visp3/core/vpMath.h>
53 #include <visp3/gui/vpDisplayD3D.h>
54 #include <visp3/gui/vpDisplayGDI.h>
55 #include <visp3/gui/vpDisplayGTK.h>
56 #include <visp3/gui/vpDisplayOpenCV.h>
57 #include <visp3/gui/vpDisplayX.h>
58 #include <visp3/io/vpImageIo.h>
59 #include <visp3/io/vpParseArgv.h>
60 #include <visp3/io/vpVideoReader.h>
61 #include <visp3/mbt/vpMbGenericTracker.h>
62 
63 #define GETOPTARGS "X:M:i:n:dchfolwvpT:e:u:"
64 
65 #define USE_SMALL_DATASET 1 // small depth dataset in ViSP-images
66 
67 #ifdef ENABLE_VISP_NAMESPACE
68 using namespace VISP_NAMESPACE_NAME;
69 #endif
70 
71 namespace
72 {
73 void usage(const char *name, const char *badparam)
74 {
75  fprintf(stdout, "\n\
76  Example of tracking with vpGenericTracker.\n\
77  \n\
78  SYNOPSIS\n\
79  %s [-i <test image path>] [-X <config file depth>]\n\
80  [-M <model name depth>] [-n <initialisation file base name>]\n\
81  [-f] [-c] [-d] [-h] [-o] [-w] [-l] [-v] [-p]\n\
82  [-T <tracker type>] [-e <last frame index>]\n\
83  [-u <disable face>]\n",
84  name);
85 
86  fprintf(stdout, "\n\
87  OPTIONS: \n\
88  -i <input image path> \n\
89  Set image input path.\n\
90  These images come from ViSP-images-x.y.z.tar.gz available \n\
91  on the ViSP website.\n\
92  Setting the VISP_INPUT_IMAGE_PATH environment\n\
93  variable produces the same behavior than using\n\
94  this option.\n\
95  \n\
96  -X <config file> \n\
97  Set the config file (the xml file) to use for the depth sensor.\n\
98  The config file is used to specify the parameters of the tracker.\n\
99  \n\
100  -M <model name> \n\
101  Specify the name of the file of the model for the depth sensor.\n\
102  The model can either be a vrml model (.wrl) or a .cao file.\n\
103  \n\
104  -n <initialisation file base name> \n\
105  Base name of the initialisation file. The file will be 'base_name'.init .\n\
106  This base name is also used for the optional picture specifying where to \n\
107  click (a .ppm picture).\n\
108  \n\
109  -f \n\
110  Turn off the display of the visual features. \n\
111  \n\
112  -d \n\
113  Turn off the display.\n\
114  \n\
115  -c\n\
116  Disable the mouse click. Useful to automate the \n\
117  execution of this program without human intervention.\n\
118  \n\
119  -o\n\
120  Use Ogre3D for visibility tests\n\
121  \n\
122  -w\n\
123  When Ogre3D is enable [-o] show Ogre3D configuration dialog that allows to set the renderer.\n\
124  \n\
125  -l\n\
126  Use the scanline for visibility tests.\n\
127  \n\
128  -v\n\
129  Compute covariance matrix.\n\
130  \n\
131  -p\n\
132  Compute gradient projection error.\n\
133  \n\
134  -T <tracker type>\n\
135  Set tracker type (<4 (Depth normal)>, <8 (Depth dense)>, <12 (both)>) for depth sensor.\n\
136  \n\
137  -e <last frame index>\n\
138  Specify the index of the last frame. Once reached, the tracking is stopped.\n\
139  \n\
140  -u <disable>\n\
141  Disable castle element (1=floor, 2=front_door, 4=slope, 8=tower_front, 16=tower_left, 32=tower_right, 64=tower_back).\n\
142  \n\
143  -h \n\
144  Print the help.\n\n");
145 
146  if (badparam)
147  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
148 }
149 
150 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &configFile_depth,
151  std::string &modelFile_depth, std::string &initFile, bool &displayFeatures, bool &click_allowed,
152  bool &display, bool &useOgre, bool &showOgreConfigDialog, bool &useScanline, bool &computeCovariance,
153  bool &projectionError, int &tracker_type_depth, int &lastFrame, int &disable_castle_faces)
154 {
155  const char *optarg_;
156  int c;
157  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
158 
159  switch (c) {
160  case 'i':
161  ipath = optarg_;
162  break;
163  case 'X':
164  configFile_depth = optarg_;
165  break;
166  case 'M':
167  modelFile_depth = optarg_;
168  break;
169  case 'n':
170  initFile = optarg_;
171  break;
172  case 'f':
173  displayFeatures = false;
174  break;
175  case 'c':
176  click_allowed = false;
177  break;
178  case 'd':
179  display = false;
180  break;
181  case 'o':
182  useOgre = true;
183  break;
184  case 'l':
185  useScanline = true;
186  break;
187  case 'w':
188  showOgreConfigDialog = true;
189  break;
190  case 'v':
191  computeCovariance = true;
192  break;
193  case 'p':
194  projectionError = true;
195  break;
196  case 'T':
197  tracker_type_depth = atoi(optarg_);
198  break;
199  case 'e':
200  lastFrame = atoi(optarg_);
201  break;
202  case 'u':
203  disable_castle_faces = atoi(optarg_);
204  break;
205 
206  case 'h':
207  usage(argv[0], nullptr);
208  return false;
209  break;
210  default:
211  usage(argv[0], optarg_);
212  return false;
213  break;
214  }
215  }
216 
217  if ((c == 1) || (c == -1)) {
218  // standalone param or error
219  usage(argv[0], nullptr);
220  std::cerr << "ERROR: " << std::endl;
221  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
222  return false;
223  }
224 
225  return true;
226 }
227 
228 struct vpRealsenseIntrinsics_t
229 {
230  float ppx;
232  float ppy;
234  float fx;
236  float fy;
238  float coeffs[5];
239 };
240 
241 void rs_deproject_pixel_to_point(float point[3], const vpRealsenseIntrinsics_t &intrin, const float pixel[2], float depth)
242 {
243  float x = (pixel[0] - intrin.ppx) / intrin.fx;
244  float y = (pixel[1] - intrin.ppy) / intrin.fy;
245 
246  float r2 = x * x + y * y;
247  float f = 1 + intrin.coeffs[0] * r2 + intrin.coeffs[1] * r2 * r2 + intrin.coeffs[4] * r2 * r2 * r2;
248  float ux = x * f + 2 * intrin.coeffs[2] * x * y + intrin.coeffs[3] * (r2 + 2 * x * x);
249  float uy = y * f + 2 * intrin.coeffs[3] * x * y + intrin.coeffs[2] * (r2 + 2 * y * y);
250 
251  x = ux;
252  y = uy;
253 
254  point[0] = depth * x;
255  point[1] = depth * y;
256  point[2] = depth;
257 }
258 
259 bool read_data(unsigned int cpt, const std::string &input_directory, vpImage<unsigned char> &I,
260  vpImage<uint16_t> &I_depth_raw, std::vector<vpColVector> &pointcloud, unsigned int &pointcloud_width,
261  unsigned int &pointcloud_height)
262 {
263 #if VISP_HAVE_DATASET_VERSION >= 0x030600
264  std::string ext("png");
265 #else
266  std::string ext("pgm");
267 #endif
268  // Read image
269  std::stringstream ss;
270  ss << input_directory << "/image_";
271  ss << std::setfill('0') << std::setw(4);
272  ss << cpt;
273  ss << ".";
274  ss << ext;
275  std::string filename_image = ss.str();
276 
277  if (!vpIoTools::checkFilename(filename_image)) {
278  std::cerr << "Cannot read: " << filename_image << std::endl;
279  return false;
280  }
281  vpImageIo::read(I, filename_image);
282 
283  // Read raw depth
284  ss.str("");
285  ss << input_directory << "/depth_image_";
286  ss << std::setfill('0') << std::setw(4);
287  ss << cpt;
288  ss << ".bin";
289  std::string filename_depth = ss.str();
290 
291  std::ifstream file_depth(filename_depth.c_str(), std::ios::in | std::ios::binary);
292  if (!file_depth.is_open()) {
293  return false;
294  }
295 
296  unsigned int height = 0, width = 0;
297  vpIoTools::readBinaryValueLE(file_depth, height);
298  vpIoTools::readBinaryValueLE(file_depth, width);
299 
300  I_depth_raw.resize(height, width);
301 
302  uint16_t depth_value = 0;
303  for (unsigned int i = 0; i < height; i++) {
304  for (unsigned int j = 0; j < width; j++) {
305  vpIoTools::readBinaryValueLE(file_depth, depth_value);
306  I_depth_raw[i][j] = depth_value;
307  }
308  }
309 
310  // Transform pointcloud
311  pointcloud_width = width;
312  pointcloud_height = height;
313  pointcloud.resize((size_t)width * height);
314 
315  // Only for Creative SR300
316  const float depth_scale = 0.000124986647f;
317  vpRealsenseIntrinsics_t depth_intrinsic;
318  depth_intrinsic.ppx = 311.484558f;
319  depth_intrinsic.ppy = 246.283234f;
320  depth_intrinsic.fx = 476.053619f;
321  depth_intrinsic.fy = 476.053497f;
322  depth_intrinsic.coeffs[0] = 0.165056542f;
323  depth_intrinsic.coeffs[1] = -0.0508309528f;
324  depth_intrinsic.coeffs[2] = 0.00435937941f;
325  depth_intrinsic.coeffs[3] = 0.00541406544f;
326  depth_intrinsic.coeffs[4] = 0.250085592f;
327 
328  for (unsigned int i = 0; i < height; i++) {
329  for (unsigned int j = 0; j < width; j++) {
330  float scaled_depth = I_depth_raw[i][j] * depth_scale;
331  float point[3];
332  float pixel[2] = { (float)j, (float)i };
333  rs_deproject_pixel_to_point(point, depth_intrinsic, pixel, scaled_depth);
334 
335  vpColVector data_3D(3);
336  data_3D[0] = point[0];
337  data_3D[1] = point[1];
338  data_3D[2] = point[2];
339 
340  pointcloud[(size_t)(i * width + j)] = data_3D;
341  }
342  }
343 
344  return true;
345 }
346 
347 void loadConfiguration(vpMbTracker *const tracker, const std::string &
348 #if defined(VISP_HAVE_PUGIXML)
349  configFile_depth
350 #endif
351 )
352 {
353 #if defined(VISP_HAVE_PUGIXML)
354  // From the xml file
355  dynamic_cast<vpMbGenericTracker *>(tracker)->loadConfigFile(configFile_depth);
356 #else
357  // Depth
358  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalFeatureEstimationMethod(
360  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalPclPlaneEstimationMethod(2);
361  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalPclPlaneEstimationRansacMaxIter(200);
362  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalPclPlaneEstimationRansacThreshold(0.001);
363  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalSamplingStep(2, 2);
364 
365  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthDenseSamplingStep(4, 4);
366 
367  vpCameraParameters cam;
368  cam.initPersProjWithoutDistortion(476.0536193848, 476.0534973145, 311.4845581055, 246.2832336426);
369 
370  dynamic_cast<vpMbGenericTracker *>(tracker)->setCameraParameters(cam);
371 
372  tracker->setAngleAppear(vpMath::rad(70));
373  tracker->setAngleDisappear(vpMath::rad(80));
374 
375  // Specify the clipping to
376  tracker->setNearClippingDistance(0.01);
377  tracker->setFarClippingDistance(2.0);
378  tracker->setClipping(tracker->getClipping() | vpMbtPolygon::FOV_CLIPPING);
379 // tracker->setClipping(tracker->getClipping() | vpMbtPolygon::LEFT_CLIPPING
380 // | vpMbtPolygon::RIGHT_CLIPPING | vpMbtPolygon::UP_CLIPPING |
381 // vpMbtPolygon::DOWN_CLIPPING); // Equivalent to FOV_CLIPPING
382 #endif
383 }
384 
385 std::vector<std::string> getCastleElementNames(const int element)
386 {
387  std::vector<std::string> element_names;
388 
389  if (element & 0x1)
390  element_names.push_back("floor");
391  if (element & 0x2)
392  element_names.push_back("front_door");
393  if (element & 0x4)
394  element_names.push_back("slope");
395  if (element & 0x8)
396  element_names.push_back("tower_front");
397  if (element & 0x10)
398  element_names.push_back("tower_left");
399  if (element & 0x20)
400  element_names.push_back("tower_right");
401  if (element & 0x40)
402  element_names.push_back("tower_back");
403 
404  return element_names;
405 }
406 } // namespace
407 
408 int main(int argc, const char **argv)
409 {
410  try {
411  std::string env_ipath;
412  std::string opt_ipath;
413  std::string ipath;
414  std::string opt_configFile_depth;
415  std::string opt_modelFile_depth;
416  std::string opt_initFile;
417  std::string initFile;
418  bool displayFeatures = true;
419  bool opt_click_allowed = true;
420  bool opt_display = true;
421  bool useOgre = false;
422  bool showOgreConfigDialog = false;
423  bool useScanline = false;
424  bool computeCovariance = false;
425  bool projectionError = false;
426  int trackerType_depth = vpMbGenericTracker::DEPTH_DENSE_TRACKER;
427 #if defined(__mips__) || defined(__mips) || defined(mips) || defined(__MIPS__)
428  // To avoid Debian test timeout
429  int opt_lastFrame = 5;
430 #else
431  int opt_lastFrame = -1;
432 #endif
433  int disable_castle_faces = 0;
434 
435  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
436  // environment variable value
437  env_ipath = vpIoTools::getViSPImagesDataPath();
438 
439  // Set the default input path
440  if (!env_ipath.empty())
441  ipath = env_ipath;
442 
443  // Read the command line options
444  if (!getOptions(argc, argv, opt_ipath, opt_configFile_depth, opt_modelFile_depth, opt_initFile, displayFeatures,
445  opt_click_allowed, opt_display, useOgre, showOgreConfigDialog, useScanline, computeCovariance,
446  projectionError, trackerType_depth, opt_lastFrame, disable_castle_faces)) {
447  return EXIT_FAILURE;
448  }
449 
450  // Test if an input path is set
451  if (opt_ipath.empty() && env_ipath.empty()) {
452  usage(argv[0], nullptr);
453  std::cerr << std::endl << "ERROR:" << std::endl;
454  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
455  << " environment variable to specify the location of the " << std::endl
456  << " image path where test images are located." << std::endl
457  << std::endl;
458 
459  return EXIT_FAILURE;
460  }
461 
462  // Get the option values
463  ipath = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/castel");
464 
465  std::string dir_path = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth");
466  if (!vpIoTools::checkDirectory(dir_path)) {
467  std::cerr << "ViSP-images does not contain the folder: " << dir_path << "!" << std::endl;
468  return EXIT_SUCCESS;
469  }
470 
471  std::string configFile_depth;
472  if (!opt_configFile_depth.empty())
473  configFile_depth = opt_configFile_depth;
474  else
475  configFile_depth =
476  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau_depth.xml");
477 
478  std::string modelFile_depth;
479  if (!opt_modelFile_depth.empty())
480  modelFile_depth = opt_modelFile_depth;
481  else
482  modelFile_depth =
483  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau.cao");
484 
485  std::string vrml_ext = ".wrl";
486  bool use_vrml =
487  (modelFile_depth.compare(modelFile_depth.length() - vrml_ext.length(), vrml_ext.length(), vrml_ext) == 0);
488 
489  if (use_vrml) {
490 #if defined(VISP_HAVE_COIN3D) && (COIN_MAJOR_VERSION == 2 || COIN_MAJOR_VERSION == 3 || COIN_MAJOR_VERSION == 4)
491  std::cout << "use_vrml: " << use_vrml << std::endl;
492 #else
493  std::cerr << "Error: vrml model file is only supported if ViSP is "
494  "build with Coin3D 3rd party"
495  << std::endl;
496  return EXIT_FAILURE;
497 #endif
498  }
499 
500  if (!opt_initFile.empty())
501  initFile = opt_initFile;
502  else
503  initFile = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau.init");
504 
505  vpImage<unsigned char> I, I_depth;
506  vpImage<uint16_t> I_depth_raw;
507  std::vector<vpColVector> pointcloud;
508  unsigned int pointcloud_width, pointcloud_height;
509  if (!read_data(0, ipath, I, I_depth_raw, pointcloud, pointcloud_width, pointcloud_height)) {
510  std::cerr << "Cannot open sequence: " << ipath << std::endl;
511  return EXIT_FAILURE;
512  }
513 
514  vpImageConvert::createDepthHistogram(I_depth_raw, I_depth);
515 
516 // initialise a display
517 #if defined(VISP_HAVE_X11)
518  vpDisplayX display, display2;
519 #elif defined(VISP_HAVE_GDI)
520  vpDisplayGDI display, display2;
521 #elif defined(HAVE_OPENCV_HIGHGUI)
522  vpDisplayOpenCV display, display2;
523 #elif defined(VISP_HAVE_D3D9)
524  vpDisplayD3D display, display2;
525 #elif defined(VISP_HAVE_GTK)
526  vpDisplayGTK display, display2;
527 #else
528  opt_display = false;
529 #endif
530  if (opt_display) {
531 #if defined(VISP_HAVE_DISPLAY)
532  display.setDownScalingFactor(vpDisplay::SCALE_AUTO);
533  display.init(I_depth, 100, 100, "Depth");
534  display2.setDownScalingFactor(vpDisplay::SCALE_AUTO);
535  display2.init(I, I_depth.getWidth() + 100, 100, "Image");
536 #endif
537  vpDisplay::display(I_depth);
539  vpDisplay::flush(I_depth);
540  vpDisplay::flush(I);
541  }
542 
543  // Object pointer to check that inheritance is ok
544  vpMbTracker *tracker = new vpMbGenericTracker(1, trackerType_depth);
546  vpCameraParameters cam;
547 
548  loadConfiguration(tracker, configFile_depth);
549 
550  // Display the moving edges, and the Klt points
551  tracker->setDisplayFeatures(displayFeatures);
552 
553  // Tells if the tracker has to use Ogre3D for visibility tests
554  tracker->setOgreVisibilityTest(useOgre);
555  if (useOgre)
556  tracker->setOgreShowConfigDialog(showOgreConfigDialog);
557 
558  // Tells if the tracker has to use the scanline visibility tests
559  tracker->setScanLineVisibilityTest(useScanline);
560 
561  // Tells if the tracker has to compute the covariance matrix
562  tracker->setCovarianceComputation(computeCovariance);
563 
564  // Tells if the tracker has to compute the projection error
565  tracker->setProjectionErrorComputation(projectionError);
566 
567  // For generic projection error computation
568  tracker->setProjectionErrorDisplay(true);
571 
572  // Retrieve the camera parameters from the tracker
573  dynamic_cast<vpMbGenericTracker *>(tracker)->getCameraParameters(cam);
574 
575  vpCameraParameters cam_color;
576  cam_color.initPersProjWithoutDistortion(615.1674804688, 615.1675415039, 312.1889953613, 243.4373779297);
577  vpHomogeneousMatrix depth_M_color;
578  std::string depth_M_color_filename =
579  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/depth_M_color.txt");
580  {
581  std::ifstream depth_M_color_file(depth_M_color_filename.c_str());
582  depth_M_color.load(depth_M_color_file);
583  }
584 
585  // Loop to position the object
586  if (opt_display && opt_click_allowed) {
587  while (!vpDisplay::getClick(I_depth, false)) {
588  vpDisplay::display(I_depth);
589  vpDisplay::displayText(I_depth, 15, 10, "click after positioning the object", vpColor::red);
590  vpDisplay::flush(I_depth);
591  }
592  }
593 
594  // Load the 3D model (either a vrml file or a .cao file)
595  dynamic_cast<vpMbGenericTracker *>(tracker)->loadModel(modelFile_depth);
596 
597  if (opt_display && opt_click_allowed) {
598  // Initialise the tracker by clicking on the image
599  dynamic_cast<vpMbGenericTracker *>(tracker)->initClick(I_depth, initFile, true);
600  dynamic_cast<vpMbGenericTracker *>(tracker)->getPose(cMo);
601  // display the 3D model at the given pose
602  dynamic_cast<vpMbGenericTracker *>(tracker)->display(I_depth, cMo, cam, vpColor::red);
603  }
604  else {
605  vpHomogeneousMatrix cMoi(0.04431452054, 0.09294637757, 0.3357760654, -2.677922443, 0.121297639, -0.6028463357);
606  dynamic_cast<vpMbGenericTracker *>(tracker)->initFromPose(I_depth, cMoi);
607  }
608 
609  // track the model
610  {
611  std::map<std::string, const vpImage<unsigned char> *> mapOfImages;
612  std::map<std::string, const std::vector<vpColVector> *> mapOfPointclouds;
613  mapOfPointclouds["Camera"] = &pointcloud;
614  std::map<std::string, unsigned int> mapOfWidths, mapOfHeights;
615  mapOfWidths["Camera"] = pointcloud_width;
616  mapOfHeights["Camera"] = pointcloud_height;
617 
618  dynamic_cast<vpMbGenericTracker *>(tracker)->track(mapOfImages, mapOfPointclouds, mapOfWidths, mapOfHeights);
619  }
620  dynamic_cast<vpMbGenericTracker *>(tracker)->getPose(cMo);
621 
622  if (opt_display) {
623  vpDisplay::flush(I_depth);
624  }
625 
626  bool quit = false, click = false;
627  unsigned int frame_index = 0;
628  std::vector<double> time_vec;
629  while (read_data(frame_index, ipath, I, I_depth_raw, pointcloud, pointcloud_width, pointcloud_height) && !quit &&
630  (opt_lastFrame > 0 ? (int)frame_index <= opt_lastFrame : true)) {
631  vpImageConvert::createDepthHistogram(I_depth_raw, I_depth);
632 
633  if (opt_display) {
634  vpDisplay::display(I_depth);
636 
637  std::stringstream ss;
638  ss << "Num frame: " << frame_index;
639  vpDisplay::displayText(I_depth, 40, 20, ss.str(), vpColor::red);
640  }
641 
642  // Test reset the tracker
643  if (frame_index == 10) {
644  std::cout << "----------Test reset tracker----------" << std::endl;
645  if (opt_display) {
646  vpDisplay::display(I_depth);
647  }
648 
649  tracker->resetTracker();
650 
651  loadConfiguration(tracker, configFile_depth);
652  dynamic_cast<vpMbGenericTracker *>(tracker)->loadModel(modelFile_depth);
653  dynamic_cast<vpMbGenericTracker *>(tracker)->setCameraParameters(cam);
654  tracker->setOgreVisibilityTest(useOgre);
655  tracker->setScanLineVisibilityTest(useScanline);
656  tracker->setCovarianceComputation(computeCovariance);
657  tracker->setProjectionErrorComputation(projectionError);
658  dynamic_cast<vpMbGenericTracker *>(tracker)->initFromPose(I_depth, cMo);
659  }
660 
661  // Test set an initial pose
662 #if USE_SMALL_DATASET
663  if (frame_index == 20) {
664  cMo.buildFrom(0.05319520317, 0.09223511976, 0.3380095812, -2.71438192, 0.07141055397, -0.3810081638);
665 #else
666  if (frame_index == 50) {
667  cMo.buildFrom(0.06865933578, 0.09494713501, 0.3260555142, -2.730027451, 0.03498390135, 0.01989831338);
668 #endif
669  std::cout << "Test set pose" << std::endl;
670  dynamic_cast<vpMbGenericTracker *>(tracker)->setPose(I_depth, cMo);
671  }
672 
673 #if USE_SMALL_DATASET
674  // track the object: stop tracking from frame 15 to 20
675  if (frame_index < 15 || frame_index >= 20) {
676 #else
677  // track the object: stop tracking from frame 30 to 50
678  if (frame_index < 30 || frame_index >= 50) {
679 #endif
680  std::map<std::string, const vpImage<unsigned char> *> mapOfImages;
681  std::map<std::string, const std::vector<vpColVector> *> mapOfPointclouds;
682  mapOfPointclouds["Camera"] = &pointcloud;
683  std::map<std::string, unsigned int> mapOfWidths, mapOfHeights;
684  mapOfWidths["Camera"] = pointcloud_width;
685  mapOfHeights["Camera"] = pointcloud_height;
686 
687  if (disable_castle_faces) {
688  std::vector<std::string> element_names = getCastleElementNames(disable_castle_faces);
689  std::cout << "Disable: ";
690  for (size_t idx = 0; idx < element_names.size(); idx++) {
691  std::cout << element_names[idx];
692  if (idx + 1 < element_names.size())
693  std::cout << ", ";
694 
695  if (trackerType_depth & vpMbGenericTracker::DEPTH_DENSE_TRACKER)
696  dynamic_cast<vpMbGenericTracker *>(tracker)->setUseDepthDenseTracking(element_names[idx], false);
697  if (trackerType_depth & vpMbGenericTracker::DEPTH_NORMAL_TRACKER)
698  dynamic_cast<vpMbGenericTracker *>(tracker)->setUseDepthNormalTracking(element_names[idx], false);
699  }
700  std::cout << std::endl;
701  }
702 
703  double t = vpTime::measureTimeMs();
704  dynamic_cast<vpMbGenericTracker *>(tracker)->track(mapOfImages, mapOfPointclouds, mapOfWidths, mapOfHeights);
705  t = vpTime::measureTimeMs() - t;
706  time_vec.push_back(t);
707 
708  dynamic_cast<vpMbGenericTracker *>(tracker)->getPose(cMo);
709 
710  if (opt_display) {
711  // display the 3D model
712  dynamic_cast<vpMbGenericTracker *>(tracker)->display(I_depth, cMo, cam, vpColor::darkRed);
713  // display the frame
714  vpDisplay::displayFrame(I_depth, cMo, cam, 0.05);
715  // computation time
716  std::stringstream ss;
717  ss << "Computation time: " << t << " ms";
718  vpDisplay::displayText(I_depth, 60, 20, ss.str(), vpColor::red);
719  // nb features
720  ss.str("");
721  ss << "nb features: " << tracker->getError().getRows();
722  vpDisplay::displayText(I_depth, 80, 20, ss.str(), vpColor::red);
723 
724  // generic projection error computed on image from the RGB camera
725  double projection_error = tracker->computeCurrentProjectionError(I, depth_M_color.inverse() * cMo, cam_color);
726  ss.str("");
727  ss << "Projection error: " << projection_error;
728  vpDisplay::displayText(I, 20, 20, ss.str(), vpColor::red);
729  }
730  }
731 
732  if (opt_click_allowed && opt_display) {
733  vpDisplay::displayText(I_depth, 10, 10, "Click to quit", vpColor::red);
735  if (vpDisplay::getClick(I_depth, button, click)) {
736  switch (button) {
738  quit = !click;
739  break;
740 
742  click = !click;
743  break;
744 
745  default:
746  break;
747  }
748  }
749  }
750 
751  if (computeCovariance) {
752  std::cout << "Covariance matrix: \n" << tracker->getCovarianceMatrix() << std::endl << std::endl;
753  }
754 
755  if (projectionError) {
756  std::cout << "Projection error: " << tracker->getProjectionError() << std::endl << std::endl;
757  }
758 
759  if (opt_display) {
760  vpDisplay::flush(I_depth);
761  vpDisplay::flush(I);
762  }
763 
764  frame_index++;
765  }
766 
767  std::cout << "\nFinal poses, cMo:\n" << cMo << std::endl;
768  std::cout << "\nComputation time, Mean: " << vpMath::getMean(time_vec)
769  << " ms ; Median: " << vpMath::getMedian(time_vec) << " ms ; Std: " << vpMath::getStdev(time_vec) << " ms"
770  << std::endl;
771 
772  if (opt_click_allowed && !quit) {
773  vpDisplay::getClick(I_depth);
774  }
775 
776  delete tracker;
777  tracker = nullptr;
778 
779  return EXIT_SUCCESS;
780  }
781  catch (const vpException &e) {
782  std::cout << "Catch an exception: " << e << std::endl;
783  return EXIT_FAILURE;
784  }
785  }
786 
787 #elif !(defined(VISP_HAVE_MODULE_MBT) && defined(VISP_HAVE_DISPLAY))
788 int main()
789 {
790  std::cout << "Cannot run this example: visp_mbt, visp_gui modules are required." << std::endl;
791  return EXIT_SUCCESS;
792 }
793 #else
794 int main()
795 {
796  std::cout << "Cannot run this example: install Lapack, Eigen3 or OpenCV" << std::endl;
797  return EXIT_SUCCESS;
798 }
799 #endif
unsigned int getRows() const
Definition: vpArray2D.h:347
Generic class defining intrinsic camera parameters.
void initPersProjWithoutDistortion(double px, double py, double u0, double v0)
Implementation of column vector and the associated operations.
Definition: vpColVector.h:191
static const vpColor red
Definition: vpColor.h:217
static const vpColor darkRed
Definition: vpColor.h:218
Display for windows using Direct3D 3rd party. Thus to enable this class Direct3D should be installed....
Definition: vpDisplayD3D.h:106
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:130
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:133
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
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)
@ SCALE_AUTO
Definition: vpDisplay.h:184
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
Implementation of an homogeneous matrix and operations on such kind of matrices.
void load(std::ifstream &f)
vpHomogeneousMatrix & buildFrom(const vpTranslationVector &t, const vpRotationMatrix &R)
vpHomogeneousMatrix inverse() const
static void createDepthHistogram(const vpImage< uint16_t > &src_depth, vpImage< vpRGBa > &dest_rgba)
static void read(vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Definition: vpImageIo.cpp:147
unsigned int getWidth() const
Definition: vpImage.h:242
void resize(unsigned int h, unsigned int w)
resize the image : Image initialization
Definition: vpImage.h:542
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1053
static bool checkFilename(const std::string &filename)
Definition: vpIoTools.cpp:786
static void readBinaryValueLE(std::ifstream &file, int16_t &short_value)
static bool checkDirectory(const std::string &dirname)
Definition: vpIoTools.cpp:396
static std::string createFilePath(const std::string &parent, const std::string &child)
Definition: vpIoTools.cpp:1427
static double rad(double deg)
Definition: vpMath.h:129
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 double getMean(const std::vector< double > &v)
Definition: vpMath.cpp:302
Real-time 6D object pose tracking using its CAD model.
Main methods for a model-based tracker.
Definition: vpMbTracker.h:107
virtual void setProjectionErrorDisplayArrowLength(unsigned int length)
Definition: vpMbTracker.h:597
virtual double computeCurrentProjectionError(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &_cMo, const vpCameraParameters &_cam)
virtual void resetTracker()=0
virtual void setOgreShowConfigDialog(bool showConfigDialog)
Definition: vpMbTracker.h:652
virtual void setDisplayFeatures(bool displayF)
Definition: vpMbTracker.h:520
virtual vpColVector getError() const =0
virtual void setAngleDisappear(const double &a)
Definition: vpMbTracker.h:483
virtual void setCovarianceComputation(const bool &flag)
Definition: vpMbTracker.h:502
virtual void setScanLineVisibilityTest(const bool &v)
Definition: vpMbTracker.h:610
virtual void setOgreVisibilityTest(const bool &v)
virtual vpMatrix getCovarianceMatrix() const
Definition: vpMbTracker.h:267
virtual void setProjectionErrorDisplay(bool display)
Definition: vpMbTracker.h:592
virtual void setNearClippingDistance(const double &dist)
virtual void setFarClippingDistance(const double &dist)
virtual double getProjectionError() const
Definition: vpMbTracker.h:312
virtual void setProjectionErrorComputation(const bool &flag)
Definition: vpMbTracker.h:587
virtual void setClipping(const unsigned int &flags)
virtual void setProjectionErrorDisplayArrowThickness(unsigned int thickness)
Definition: vpMbTracker.h:605
virtual void setAngleAppear(const double &a)
Definition: vpMbTracker.h:472
virtual unsigned int getClipping() const
Definition: vpMbTracker.h:258
@ ROBUST_FEATURE_ESTIMATION
Robust scheme to estimate the normal of the plane.
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:70
VISP_EXPORT double measureTimeMs()