Visual Servoing Platform  version 3.6.1 under development (2024-11-15)
mbtGenericTrackingDepth.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:X:m:M:i:n:dchfolwvpt:T:e:"
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>] [-X <config file depth>]\n\
80  [-m <model name>] [-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>] [-T <tracker type>] [-e <last frame index>]\n",
83  name);
84 
85  fprintf(stdout, "\n\
86  OPTIONS: \n\
87  -i <input image path> \n\
88  Set image input path.\n\
89  These images come from visp-images-x.y.z.tar.gz available \n\
90  on the ViSP website.\n\
91  Setting the VISP_INPUT_IMAGE_PATH environment\n\
92  variable produces the same behavior than using\n\
93  this option.\n\
94  \n\
95  -x <config file> \n\
96  Set the config file (the xml file) to use.\n\
97  The config file is used to specify the parameters of the tracker.\n\
98  \n\
99  -X <config file> \n\
100  Set the config file (the xml file) to use for the depth sensor.\n\
101  The config file is used to specify the parameters of the tracker.\n\
102  \n\
103  -m <model name> \n\
104  Specify the name of the file of the model.\n\
105  The model can either be a vrml model (.wrl) or a .cao file.\n\
106  \n\
107  -M <model name> \n\
108  Specify the name of the file of the model for the depth sensor.\n\
109  The model can either be a vrml model (.wrl) or a .cao file.\n\
110  \n\
111  -n <initialisation file base name> \n\
112  Base name of the initialisation file. The file will be 'base_name'.init .\n\
113  This base name is also used for the optional picture specifying where to \n\
114  click (a .ppm picture).\n\
115  \n\
116  -f \n\
117  Turn off the display of the the moving edges and Klt points. \n\
118  \n\
119  -d \n\
120  Turn off the display.\n\
121  \n\
122  -c\n\
123  Disable the mouse click. Useful to automate the \n\
124  execution of this program without human intervention.\n\
125  \n\
126  -o\n\
127  Use Ogre3D for visibility tests\n\
128  \n\
129  -w\n\
130  When Ogre3D is enable [-o] show Ogre3D configuration dialog that allows to set the renderer.\n\
131  \n\
132  -l\n\
133  Use the scanline for visibility tests.\n\
134  \n\
135  -v\n\
136  Compute covariance matrix.\n\
137  \n\
138  -p\n\
139  Compute gradient projection error.\n\
140  \n\
141  -t <tracker type>\n\
142  Set tracker type (<1 (Edge)>, <2 (KLT)>, <3 (both)>) for color sensor.\n\
143  \n\
144  -T <tracker type>\n\
145  Set tracker type (<4 (Depth normal)>, <8 (Depth dense)>, <12 (both)>) for depth sensor.\n\
146  \n\
147  -e <last frame index>\n\
148  Specify the index of the last frame. Once reached, the tracking is stopped.\n\
149  \n\
150  -h \n\
151  Print the help.\n\n");
152 
153  if (badparam)
154  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
155 }
156 
157 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &configFile, std::string &configFile_depth,
158  std::string &modelFile, std::string &modelFile_depth, std::string &initFile, bool &displayFeatures,
159  bool &click_allowed, bool &display, bool &useOgre, bool &showOgreConfigDialog, bool &useScanline,
160  bool &computeCovariance, bool &projectionError, int &trackerType, int &tracker_type_depth,
161  int &lastFrame)
162 {
163  const char *optarg_;
164  int c;
165  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
166 
167  switch (c) {
168  case 'i':
169  ipath = optarg_;
170  break;
171  case 'x':
172  configFile = optarg_;
173  break;
174  case 'X':
175  configFile_depth = optarg_;
176  break;
177  case 'm':
178  modelFile = optarg_;
179  break;
180  case 'M':
181  modelFile_depth = optarg_;
182  break;
183  case 'n':
184  initFile = optarg_;
185  break;
186  case 'f':
187  displayFeatures = false;
188  break;
189  case 'c':
190  click_allowed = false;
191  break;
192  case 'd':
193  display = false;
194  break;
195  case 'o':
196  useOgre = true;
197  break;
198  case 'l':
199  useScanline = true;
200  break;
201  case 'w':
202  showOgreConfigDialog = true;
203  break;
204  case 'v':
205  computeCovariance = true;
206  break;
207  case 'p':
208  projectionError = true;
209  break;
210  case 't':
211  trackerType = atoi(optarg_);
212  break;
213  case 'T':
214  tracker_type_depth = atoi(optarg_);
215  break;
216  case 'e':
217  lastFrame = atoi(optarg_);
218  break;
219  case 'h':
220  usage(argv[0], nullptr);
221  return false;
222  break;
223 
224  default:
225  usage(argv[0], optarg_);
226  return false;
227  break;
228  }
229  }
230 
231  if ((c == 1) || (c == -1)) {
232  // standalone param or error
233  usage(argv[0], nullptr);
234  std::cerr << "ERROR: " << std::endl;
235  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
236  return false;
237  }
238 
239  return true;
240 }
241 
242 struct vpRealsenseIntrinsics_t
243 {
244  float ppx;
246  float ppy;
248  float fx;
250  float fy;
252  float coeffs[5];
253 };
254 
255 void rs_deproject_pixel_to_point(float point[3], const vpRealsenseIntrinsics_t &intrin, const float pixel[2], float depth)
256 {
257  float x = (pixel[0] - intrin.ppx) / intrin.fx;
258  float y = (pixel[1] - intrin.ppy) / intrin.fy;
259 
260  float r2 = x * x + y * y;
261  float f = 1 + intrin.coeffs[0] * r2 + intrin.coeffs[1] * r2 * r2 + intrin.coeffs[4] * r2 * r2 * r2;
262  float ux = x * f + 2 * intrin.coeffs[2] * x * y + intrin.coeffs[3] * (r2 + 2 * x * x);
263  float uy = y * f + 2 * intrin.coeffs[3] * x * y + intrin.coeffs[2] * (r2 + 2 * y * y);
264 
265  x = ux;
266  y = uy;
267 
268  point[0] = depth * x;
269  point[1] = depth * y;
270  point[2] = depth;
271 }
272 
273 bool read_data(unsigned int cpt, const std::string &input_directory, vpImage<unsigned char> &I,
274  vpImage<uint16_t> &I_depth_raw, std::vector<vpColVector> &pointcloud, unsigned int &pointcloud_width,
275  unsigned int &pointcloud_height)
276 {
277 #if VISP_HAVE_DATASET_VERSION >= 0x030600
278  std::string ext("png");
279 #else
280  std::string ext("pgm");
281 #endif
282  // Read image
283  std::stringstream ss;
284  ss << input_directory << "/image_";
285  ss << std::setfill('0') << std::setw(4);
286  ss << cpt;
287  ss << ".";
288  ss << ext;
289  std::string filename_image = ss.str();
290  if (!vpIoTools::checkFilename(filename_image)) {
291  std::cerr << "Cannot read: " << filename_image << std::endl;
292  return false;
293  }
294  vpImageIo::read(I, filename_image);
295 
296  // Read raw depth
297  ss.str("");
298  ss << input_directory << "/depth_image_";
299  ss << std::setfill('0') << std::setw(4);
300  ss << cpt;
301  ss << ".bin";
302  std::string filename_depth = ss.str();
303 
304  std::ifstream file_depth(filename_depth.c_str(), std::ios::in | std::ios::binary);
305  if (!file_depth.is_open()) {
306  return false;
307  }
308 
309  unsigned int height = 0, width = 0;
310  vpIoTools::readBinaryValueLE(file_depth, height);
311  vpIoTools::readBinaryValueLE(file_depth, width);
312 
313  I_depth_raw.resize(height, width);
314 
315  uint16_t depth_value = 0;
316  for (unsigned int i = 0; i < height; i++) {
317  for (unsigned int j = 0; j < width; j++) {
318  vpIoTools::readBinaryValueLE(file_depth, depth_value);
319  I_depth_raw[i][j] = depth_value;
320  }
321  }
322 
323  // Transform pointcloud
324  pointcloud_width = width;
325  pointcloud_height = height;
326  pointcloud.resize((size_t)width * height);
327 
328  // Only for Creative SR300
329  const float depth_scale = 0.000124986647f;
330  vpRealsenseIntrinsics_t depth_intrinsic;
331  depth_intrinsic.ppx = 311.484558f;
332  depth_intrinsic.ppy = 246.283234f;
333  depth_intrinsic.fx = 476.053619f;
334  depth_intrinsic.fy = 476.053497f;
335  depth_intrinsic.coeffs[0] = 0.165056542f;
336  depth_intrinsic.coeffs[1] = -0.0508309528f;
337  depth_intrinsic.coeffs[2] = 0.00435937941f;
338  depth_intrinsic.coeffs[3] = 0.00541406544f;
339  depth_intrinsic.coeffs[4] = 0.250085592f;
340 
341  for (unsigned int i = 0; i < height; i++) {
342  for (unsigned int j = 0; j < width; j++) {
343  float scaled_depth = I_depth_raw[i][j] * depth_scale;
344  float point[3];
345  float pixel[2] = { (float)j, (float)i };
346  rs_deproject_pixel_to_point(point, depth_intrinsic, pixel, scaled_depth);
347 
348  vpColVector data_3D(3);
349  data_3D[0] = point[0];
350  data_3D[1] = point[1];
351  data_3D[2] = point[2];
352 
353  pointcloud[(size_t)(i * width + j)] = data_3D;
354  }
355  }
356 
357  return true;
358 }
359 
360 void loadConfiguration(vpMbTracker *const tracker,
361  const std::string &
362 #if defined(VISP_HAVE_PUGIXML)
363  configFile
364 #endif
365  ,
366  const std::string &
367 #if defined(VISP_HAVE_PUGIXML)
368  configFile_depth
369 #endif
370 )
371 {
372 #if defined(VISP_HAVE_PUGIXML)
373  // From the xml file
374  dynamic_cast<vpMbGenericTracker *>(tracker)->loadConfigFile(configFile, configFile_depth);
375 #else
376  // Edge
377  vpMe me;
378  me.setMaskSize(5);
379  me.setMaskNumber(180);
380  me.setRange(8);
382  me.setThreshold(10);
383  me.setMu1(0.5);
384  me.setMu2(0.5);
385  me.setSampleStep(4);
386  dynamic_cast<vpMbGenericTracker *>(tracker)->setMovingEdge(me);
387 
388  // Klt
389 #if defined(VISP_HAVE_MODULE_KLT) && defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_VIDEO)
390  vpKltOpencv klt;
391  klt.setMaxFeatures(10000);
392  klt.setWindowSize(5);
393  klt.setQuality(0.01);
394  klt.setMinDistance(5);
395  klt.setHarrisFreeParameter(0.02);
396  klt.setBlockSize(3);
397  klt.setPyramidLevels(3);
398 
399  dynamic_cast<vpMbGenericTracker *>(tracker)->setKltOpencv(klt);
400  dynamic_cast<vpMbGenericTracker *>(tracker)->setKltMaskBorder(5);
401 #endif
402 
403  // Depth
404  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalFeatureEstimationMethod(
406  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalPclPlaneEstimationMethod(2);
407  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalPclPlaneEstimationRansacMaxIter(200);
408  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalPclPlaneEstimationRansacThreshold(0.001);
409  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthNormalSamplingStep(2, 2);
410 
411  dynamic_cast<vpMbGenericTracker *>(tracker)->setDepthDenseSamplingStep(4, 4);
412 
413  vpCameraParameters cam1, cam2;
414  cam1.initPersProjWithoutDistortion(615.1674804688, 615.1675415039, 312.1889953613, 243.4373779297);
415  cam2.initPersProjWithoutDistortion(476.0536193848, 476.0534973145, 311.4845581055, 246.2832336426);
416 
417  dynamic_cast<vpMbGenericTracker *>(tracker)->setCameraParameters(cam1, cam2);
418 
419  tracker->setAngleAppear(vpMath::rad(70));
420  tracker->setAngleDisappear(vpMath::rad(80));
421 
422  // Specify the clipping to
423  tracker->setNearClippingDistance(0.01);
424  tracker->setFarClippingDistance(2.0);
425  tracker->setClipping(tracker->getClipping() | vpMbtPolygon::FOV_CLIPPING);
426  // tracker->setClipping(tracker->getClipping() | vpMbtPolygon::LEFT_CLIPPING
427  // | vpMbtPolygon::RIGHT_CLIPPING | vpMbtPolygon::UP_CLIPPING |
428  // vpMbtPolygon::DOWN_CLIPPING); // Equivalent to FOV_CLIPPING
429 #endif
430 }
431 } // namespace
432 
433 int main(int argc, const char **argv)
434 {
435  try {
436  std::string env_ipath;
437  std::string opt_ipath;
438  std::string ipath;
439  std::string opt_configFile;
440  std::string opt_configFile_depth;
441  std::string opt_modelFile;
442  std::string opt_modelFile_depth;
443  std::string opt_initFile;
444  std::string initFile;
445  bool displayFeatures = true;
446  bool opt_click_allowed = true;
447  bool opt_display = true;
448  bool useOgre = false;
449  bool showOgreConfigDialog = false;
450  bool useScanline = false;
451  bool computeCovariance = false;
452  bool projectionError = false;
453  int trackerType_image = vpMbGenericTracker::EDGE_TRACKER;
454  int trackerType_depth = vpMbGenericTracker::DEPTH_DENSE_TRACKER;
455 #if defined(__mips__) || defined(__mips) || defined(mips) || defined(__MIPS__)
456  // To avoid Debian test timeout
457  int opt_lastFrame = 5;
458 #else
459  int opt_lastFrame = -1;
460 #endif
461 
462  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
463  // environment variable value
464  env_ipath = vpIoTools::getViSPImagesDataPath();
465 
466  // Set the default input path
467  if (!env_ipath.empty())
468  ipath = env_ipath;
469 
470  // Read the command line options
471  if (!getOptions(argc, argv, opt_ipath, opt_configFile, opt_configFile_depth, opt_modelFile, opt_modelFile_depth,
472  opt_initFile, displayFeatures, opt_click_allowed, opt_display, useOgre, showOgreConfigDialog,
473  useScanline, computeCovariance, projectionError, trackerType_image, trackerType_depth,
474  opt_lastFrame)) {
475  return EXIT_FAILURE;
476  }
477 
478 #if !(defined(VISP_HAVE_MODULE_KLT) && defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_VIDEO))
479  if (trackerType_image == 2 || trackerType_image == 3) { // Use vpMbGenericTracker::KLT_TRACKER
480  std::cout << "KLT features cannot be used: ViSP is not built with "
481  "KLT module or OpenCV imgproc and video modules are not available."
482  << std::endl;
483  return EXIT_SUCCESS;
484  }
485 #endif
486 
487  // Test if an input path is set
488  if (opt_ipath.empty() && env_ipath.empty()) {
489  usage(argv[0], nullptr);
490  std::cerr << std::endl << "ERROR:" << std::endl;
491  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
492  << " environment variable to specify the location of the " << std::endl
493  << " image path where test images are located." << std::endl
494  << std::endl;
495 
496  return EXIT_FAILURE;
497  }
498 
499  // Get the option values
500  ipath = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/castel");
501 
502  std::string dir_path = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth");
503  if (!vpIoTools::checkDirectory(dir_path)) {
504  std::cerr << "ViSP-images does not contain the folder: " << dir_path << "!" << std::endl;
505  return EXIT_SUCCESS;
506  }
507 
508  std::string configFile, configFile_depth;
509  if (!opt_configFile.empty())
510  configFile = opt_configFile;
511  else
512  configFile =
513  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau.xml");
514 
515  if (!opt_configFile_depth.empty())
516  configFile_depth = opt_configFile_depth;
517  else
518  configFile_depth =
519  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau_depth.xml");
520 
521  std::string modelFile, modelFile_depth;
522  if (!opt_modelFile.empty())
523  modelFile = opt_modelFile;
524  else {
525 #if defined(VISP_HAVE_COIN3D) && (COIN_MAJOR_VERSION == 2 || COIN_MAJOR_VERSION == 3 || COIN_MAJOR_VERSION == 4)
526  modelFile =
527  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau_gantry.wrl");
528 #else
529  modelFile = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau.cao");
530 #endif
531  }
532 
533  if (!opt_modelFile_depth.empty())
534  modelFile_depth = opt_modelFile_depth;
535  else
536  modelFile_depth =
537  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau.cao");
538 
539  std::string vrml_ext = ".wrl";
540  bool use_vrml =
541  (modelFile.compare(modelFile.length() - vrml_ext.length(), vrml_ext.length(), vrml_ext) == 0) ||
542  (modelFile_depth.compare(modelFile_depth.length() - vrml_ext.length(), vrml_ext.length(), vrml_ext) == 0);
543 
544  if (use_vrml) {
545 #if defined(VISP_HAVE_COIN3D) && (COIN_MAJOR_VERSION == 2 || COIN_MAJOR_VERSION == 3 || COIN_MAJOR_VERSION == 4)
546  std::cout << "use_vrml: " << use_vrml << std::endl;
547 #else
548  std::cerr << "Error: vrml model file is only supported if ViSP is "
549  "build with Coin3D 3rd party"
550  << std::endl;
551  return EXIT_FAILURE;
552 #endif
553  }
554 
555  if (!opt_initFile.empty())
556  initFile = opt_initFile;
557  else
558  initFile = vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/chateau.init");
559 
560  vpImage<unsigned char> I, I_depth;
561  vpImage<uint16_t> I_depth_raw;
562  std::vector<vpColVector> pointcloud;
563  unsigned int pointcloud_width, pointcloud_height;
564  if (!read_data(0, ipath, I, I_depth_raw, pointcloud, pointcloud_width, pointcloud_height)) {
565  std::cerr << "Cannot open sequence: " << ipath << std::endl;
566  return EXIT_FAILURE;
567  }
568 
569  vpImageConvert::createDepthHistogram(I_depth_raw, I_depth);
570 
571  // initialise a display
572 #if defined(VISP_HAVE_X11)
573  vpDisplayX display1, display2;
574 #elif defined(VISP_HAVE_GDI)
575  vpDisplayGDI display1, display2;
576 #elif defined(HAVE_OPENCV_HIGHGUI)
577  vpDisplayOpenCV display1, display2;
578 #elif defined(VISP_HAVE_D3D9)
579  vpDisplayD3D display1, display2;
580 #elif defined(VISP_HAVE_GTK)
581  vpDisplayGTK display1, display2;
582 #else
583  opt_display = false;
584 #endif
585  if (opt_display) {
586 #if defined(VISP_HAVE_DISPLAY)
588  display2.setDownScalingFactor(vpDisplay::SCALE_AUTO);
589  display1.init(I, 100, 100, "Test tracking (Left)");
590  display2.init(I_depth, (int)(I.getWidth() / vpDisplay::getDownScalingFactor(I)) + 110, 100,
591  "Test tracking (Right)");
592 #endif
594  vpDisplay::display(I_depth);
595  vpDisplay::flush(I);
596  vpDisplay::flush(I_depth);
597  }
598 
599  std::vector<int> trackerTypes(2);
600  trackerTypes[0] = trackerType_image;
601  trackerTypes[1] = trackerType_depth;
602  // Object pointer to check that inheritance is ok
603  vpMbTracker *tracker = new vpMbGenericTracker(trackerTypes);
604  vpHomogeneousMatrix c1Mo, c2Mo;
605  vpCameraParameters cam1, cam2;
606 
607  loadConfiguration(tracker, configFile, configFile_depth);
608 
609  vpHomogeneousMatrix depth_M_color;
610  std::string depth_M_color_filename =
611  vpIoTools::createFilePath(!opt_ipath.empty() ? opt_ipath : env_ipath, "mbt-depth/castel/depth_M_color.txt");
612  {
613  std::ifstream depth_M_color_file(depth_M_color_filename.c_str());
614  depth_M_color.load(depth_M_color_file);
615  std::map<std::string, vpHomogeneousMatrix> mapOfCameraTransformationMatrices;
616  mapOfCameraTransformationMatrices["Camera2"] = depth_M_color;
617  dynamic_cast<vpMbGenericTracker *>(tracker)->setCameraTransformationMatrix(mapOfCameraTransformationMatrices);
618  }
619 
620  // Display the moving edges, and the Klt points
621  tracker->setDisplayFeatures(displayFeatures);
622 
623  // Tells if the tracker has to use Ogre3D for visibility tests
624  tracker->setOgreVisibilityTest(useOgre);
625  if (useOgre)
626  tracker->setOgreShowConfigDialog(showOgreConfigDialog);
627 
628  // Tells if the tracker has to use the scanline visibility tests
629  tracker->setScanLineVisibilityTest(useScanline);
630 
631  // Tells if the tracker has to compute the covariance matrix
632  tracker->setCovarianceComputation(computeCovariance);
633 
634  // Tells if the tracker has to compute the projection error
635  tracker->setProjectionErrorComputation(projectionError);
636 
637  // Retrieve the camera parameters from the tracker
638  dynamic_cast<vpMbGenericTracker *>(tracker)->getCameraParameters(cam1, cam2);
639 
640  // Loop to position the cube
641  if (opt_display && opt_click_allowed) {
642  while (!vpDisplay::getClick(I, false)) {
644  vpDisplay::displayText(I, 15, 10, "click after positioning the object", vpColor::red);
645  vpDisplay::flush(I);
646  }
647  }
648 
649  // Load the 3D model (either a vrml file or a .cao file)
650  dynamic_cast<vpMbGenericTracker *>(tracker)->loadModel(modelFile, modelFile_depth);
651 
652  if (opt_display && opt_click_allowed) {
653  std::map<std::string, const vpImage<unsigned char> *> mapOfImages;
654  mapOfImages["Camera1"] = &I;
655  mapOfImages["Camera2"] = &I_depth;
656  std::map<std::string, std::string> mapOfInitFiles;
657  mapOfInitFiles["Camera1"] = initFile;
658 
659  // Initialise the tracker by clicking on the image
660  dynamic_cast<vpMbGenericTracker *>(tracker)->initClick(mapOfImages, mapOfInitFiles, true);
661  dynamic_cast<vpMbGenericTracker *>(tracker)->getPose(c1Mo, c2Mo);
662  // display the 3D model at the given pose
663  dynamic_cast<vpMbGenericTracker *>(tracker)->display(I, I_depth, c1Mo, c2Mo, cam1, cam2, vpColor::red);
664  }
665  else {
666  vpHomogeneousMatrix c1Moi(0.06846423368, 0.09062570884, 0.3401096693, -2.671882598, 0.1174275908, -0.6011935263);
667  vpHomogeneousMatrix c2Moi(0.04431452054, 0.09294637757, 0.3357760654, -2.677922443, 0.121297639, -0.6028463357);
668  dynamic_cast<vpMbGenericTracker *>(tracker)->initFromPose(I, I_depth, c1Moi, c2Moi);
669  }
670 
671  // track the model
672  {
673  std::map<std::string, const vpImage<unsigned char> *> mapOfImages;
674  mapOfImages["Camera1"] = &I;
675  std::map<std::string, const std::vector<vpColVector> *> mapOfPointclouds;
676  mapOfPointclouds["Camera2"] = &pointcloud;
677  std::map<std::string, unsigned int> mapOfWidths, mapOfHeights;
678  mapOfWidths["Camera2"] = pointcloud_width;
679  mapOfHeights["Camera2"] = pointcloud_height;
680 
681  dynamic_cast<vpMbGenericTracker *>(tracker)->track(mapOfImages, mapOfPointclouds, mapOfWidths, mapOfHeights);
682  }
683  dynamic_cast<vpMbGenericTracker *>(tracker)->getPose(c1Mo, c2Mo);
684 
685  if (opt_display) {
686  vpDisplay::flush(I);
687  vpDisplay::flush(I_depth);
688  }
689 
690  bool quit = false, click = false;
691  unsigned int frame_index = 0;
692  std::vector<double> time_vec;
693  while (read_data(frame_index, ipath, I, I_depth_raw, pointcloud, pointcloud_width, pointcloud_height) && !quit &&
694  (opt_lastFrame > 0 ? (int)frame_index <= opt_lastFrame : true)) {
695  vpImageConvert::createDepthHistogram(I_depth_raw, I_depth);
696 
697  if (opt_display) {
699  vpDisplay::display(I_depth);
700 
701  std::stringstream ss;
702  ss << "Num frame: " << frame_index;
703  vpDisplay::displayText(I, 40, 20, ss.str(), vpColor::red);
704  }
705 
706  // Test reset the tracker
707  if (frame_index == 10) {
708  std::cout << "----------Test reset tracker----------" << std::endl;
709  if (opt_display) {
711  vpDisplay::display(I_depth);
712  }
713 
714  tracker->resetTracker();
715 
716  loadConfiguration(tracker, configFile, configFile_depth);
717  dynamic_cast<vpMbGenericTracker *>(tracker)->loadModel(modelFile, modelFile_depth);
718  dynamic_cast<vpMbGenericTracker *>(tracker)->setCameraParameters(cam1, cam2);
719  tracker->setOgreVisibilityTest(useOgre);
720  tracker->setScanLineVisibilityTest(useScanline);
721  tracker->setCovarianceComputation(computeCovariance);
722  tracker->setProjectionErrorComputation(projectionError);
723  dynamic_cast<vpMbGenericTracker *>(tracker)->initFromPose(I, I_depth, c1Mo, c2Mo);
724  }
725 
726  // Test to set an initial pose
727 #if USE_SMALL_DATASET
728  if (frame_index == 20) {
729  c1Mo.buildFrom(0.07734634051, 0.08993639906, 0.342344402, -2.708409543, 0.0669276477, -0.3798958303);
730  c2Mo.buildFrom(0.05319520317, 0.09223511976, 0.3380095812, -2.71438192, 0.07141055397, -0.3810081638);
731 #else
732  if (frame_index == 50) {
733  c1Mo.buildFrom(0.09280663035, 0.09277655672, 0.330415149, -2.724431817, 0.0293932671, 0.02027966377);
734  c2Mo.buildFrom(0.06865933578, 0.09494713501, 0.3260555142, -2.730027451, 0.03498390135, 0.01989831338);
735 #endif
736  std::cout << "Test set pose" << std::endl;
737  dynamic_cast<vpMbGenericTracker *>(tracker)->setPose(I, I_depth, c1Mo, c2Mo);
738  }
739 
740 #if USE_SMALL_DATASET
741  // track the object: stop tracking from frame 15 to 20
742  if (frame_index < 15 || frame_index >= 20) {
743 #else
744  // track the object: stop tracking from frame 30 to 50
745  if (frame_index < 30 || frame_index >= 50) {
746 #endif
747  std::map<std::string, const vpImage<unsigned char> *> mapOfImages;
748  mapOfImages["Camera1"] = &I;
749  std::map<std::string, const std::vector<vpColVector> *> mapOfPointclouds;
750  mapOfPointclouds["Camera2"] = &pointcloud;
751  std::map<std::string, unsigned int> mapOfWidths, mapOfHeights;
752  mapOfWidths["Camera2"] = pointcloud_width;
753  mapOfHeights["Camera2"] = pointcloud_height;
754 
755  double t = vpTime::measureTimeMs();
756  dynamic_cast<vpMbGenericTracker *>(tracker)->track(mapOfImages, mapOfPointclouds, mapOfWidths, mapOfHeights);
757  t = vpTime::measureTimeMs() - t;
758  time_vec.push_back(t);
759 
760  dynamic_cast<vpMbGenericTracker *>(tracker)->getPose(c1Mo, c2Mo);
761 
762  if (opt_display) {
763  // display the 3D model
764  dynamic_cast<vpMbGenericTracker *>(tracker)->display(I, I_depth, c1Mo, c2Mo, cam1, cam2, vpColor::darkRed);
765  // display the frame
766  vpDisplay::displayFrame(I, c1Mo, cam1, 0.05);
767  vpDisplay::displayFrame(I_depth, c2Mo, cam2, 0.05);
768  // computation time
769  std::stringstream ss;
770  ss << "Computation time: " << t << " ms";
771  vpDisplay::displayText(I, 60, 20, ss.str(), vpColor::red);
772  // nb features
773  ss.str("");
774  ss << "nb features: " << tracker->getError().getRows();
775  vpDisplay::displayText(I_depth, 80, 20, ss.str(), vpColor::red);
776  {
777  std::stringstream ss;
778  ss << "Features: edges " << dynamic_cast<vpMbGenericTracker *>(tracker)->getNbFeaturesEdge() << ", klt "
779  << dynamic_cast<vpMbGenericTracker *>(tracker)->getNbFeaturesKlt() << ", depth "
780  << dynamic_cast<vpMbGenericTracker *>(tracker)->getNbFeaturesDepthDense();
781  vpDisplay::displayText(I, I.getHeight() - 30, 20, ss.str(), vpColor::red);
782  }
783  }
784  }
785 
786  if (opt_click_allowed && opt_display) {
787  vpDisplay::displayText(I, 10, 10, "Click to quit", vpColor::red);
789  if (vpDisplay::getClick(I, button, click)) {
790  switch (button) {
792  quit = !click;
793  break;
794 
796  click = !click;
797  break;
798 
799  default:
800  break;
801  }
802  }
803  }
804 
805  if (computeCovariance) {
806  std::cout << "Covariance matrix: \n" << tracker->getCovarianceMatrix() << std::endl << std::endl;
807  }
808 
809  if (projectionError) {
810  std::cout << "Projection error: " << tracker->getProjectionError() << std::endl << std::endl;
811  }
812 
813  if (opt_display) {
814  vpDisplay::flush(I);
815  vpDisplay::flush(I_depth);
816  }
817 
818  frame_index++;
819  }
820 
821  std::cout << "\nFinal poses, c1Mo:\n" << c1Mo << "\nc2Mo:\n" << c2Mo << std::endl;
822  std::cout << "\nComputation time, Mean: " << vpMath::getMean(time_vec)
823  << " ms ; Median: " << vpMath::getMedian(time_vec) << " ms ; Std: " << vpMath::getStdev(time_vec) << " ms"
824  << std::endl;
825 
826  if (opt_click_allowed && !quit) {
828  }
829 
830  delete tracker;
831  tracker = nullptr;
832 
833  return EXIT_SUCCESS;
834  }
835  catch (const vpException &e) {
836  std::cout << "Catch an exception: " << e << std::endl;
837  return EXIT_FAILURE;
838  }
839  }
840 
841 #elif !(defined(VISP_HAVE_MODULE_MBT) && defined(VISP_HAVE_DISPLAY))
842 int main()
843 {
844  std::cout << "Cannot run this example: visp_mbt, visp_gui modules are required." << std::endl;
845  return EXIT_SUCCESS;
846 }
847 #else
848 int main()
849 {
850  std::cout << "Cannot run this example: install Lapack, Eigen3 or OpenCV" << std::endl;
851  return EXIT_SUCCESS;
852 }
853 #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)
virtual void setDownScalingFactor(unsigned int scale)
Definition: vpDisplay.cpp:233
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
unsigned int getDownScalingFactor()
Definition: vpDisplay.h:221
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)
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
unsigned int getHeight() const
Definition: vpImage.h:181
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
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
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 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 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 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.
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
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:70
VISP_EXPORT double measureTimeMs()