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