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