Visual Servoing Platform  version 3.0.0
mbtKltTracking.cpp
1 /****************************************************************************
2  *
3  * This file is part of the ViSP software.
4  * Copyright (C) 2005 - 2015 by Inria. All rights reserved.
5  *
6  * This software is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * ("GPL") version 2 as published by the Free Software Foundation.
9  * See the file LICENSE.txt at the root directory of this source
10  * distribution for additional information about the GNU GPL.
11  *
12  * For using ViSP with software that can not be combined with the GNU
13  * GPL, please contact Inria about acquiring a ViSP Professional
14  * Edition License.
15  *
16  * See http://visp.inria.fr for more information.
17  *
18  * This software was developed at:
19  * Inria Rennes - Bretagne Atlantique
20  * Campus Universitaire de Beaulieu
21  * 35042 Rennes Cedex
22  * France
23  *
24  * If you have questions regarding the use of this file, please contact
25  * Inria at visp@inria.fr
26  *
27  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
28  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29  *
30  * Description:
31  * Example of MBT KLT Tracking.
32  *
33  * Authors:
34  * Aurelien Yol
35  *
36  *****************************************************************************/
37 
44 #include <iostream>
45 #include <visp3/core/vpConfig.h>
46 
47 #if defined(VISP_HAVE_MODULE_MBT) && defined(VISP_HAVE_MODULE_KLT) && defined(VISP_HAVE_OPENCV) && defined(VISP_HAVE_DISPLAY) && (VISP_HAVE_OPENCV_VERSION >= 0x020100)
48 
49 #include <visp3/core/vpDebug.h>
50 #include <visp3/gui/vpDisplayD3D.h>
51 #include <visp3/gui/vpDisplayGTK.h>
52 #include <visp3/gui/vpDisplayGDI.h>
53 #include <visp3/gui/vpDisplayOpenCV.h>
54 #include <visp3/gui/vpDisplayX.h>
55 #include <visp3/core/vpHomogeneousMatrix.h>
56 #include <visp3/io/vpImageIo.h>
57 #include <visp3/core/vpIoTools.h>
58 #include <visp3/core/vpMath.h>
59 #include <visp3/io/vpVideoReader.h>
60 #include <visp3/io/vpParseArgv.h>
61 #include <visp3/mbt/vpMbKltTracker.h>
62 
63 #define GETOPTARGS "x:m:i:n:dchtfolw"
64 
65 void usage(const char *name, const char *badparam);
66 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &configFile, std::string &modelFile,
67  std::string &initFile, bool &displayKltPoints, bool &click_allowed, bool &display,
68  bool& cao3DModel, bool &useOgre);
69 
70 void usage(const char *name, const char *badparam)
71 {
72  fprintf(stdout, "\n\
73 Example of tracking based on the 3D model.\n\
74 \n\
75 SYNOPSIS\n\
76  %s [-i <test image path>] [-x <config file>]\n\
77  [-m <model name>] [-n <initialisation file base name>]\n\
78  [-t] [-c] [-d] [-h] [-f] [-o] [-w] [-l]",
79  name );
80 
81  fprintf(stdout, "\n\
82 OPTIONS: \n\
83  -i <input image path> \n\
84  Set image input path.\n\
85  From this path read images \n\
86  \"ViSP-images/mbt/cube/image%%04d.ppm\". These \n\
87  images come from ViSP-images-x.y.z.tar.gz available \n\
88  on the ViSP website.\n\
89  Setting the VISP_INPUT_IMAGE_PATH environment\n\
90  variable produces the same behaviour than using\n\
91  this option.\n\
92 \n\
93  -x <config file> \n\
94  Set the config file (the xml file) to use.\n\
95  The config file is used to specify the parameters of the tracker.\n\
96 \n\
97  -m <model name> \n\
98  Specify the name of the file of the model\n\
99  The model can either be a vrml model (.wrl) or a .cao file.\n\
100 \n\
101  -f \n\
102  Do not use the vrml model, use the .cao one. These two models are \n\
103  equivalent and comes from ViSP-images-x.y.z.tar.gz available on the ViSP\n\
104  website. However, the .cao model allows to use the 3d model based tracker \n\
105  without Coin.\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 optionnal picture specifying where to \n\
110  click (a .ppm picture).\
111 \n\
112  -t \n\
113  Turn off the display of the the 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 automaze the \n\
120  execution of this program without humain 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 thatallows to set the renderer.\n\
127 \n\
128  -l\n\
129  Use the scanline for visibility tests\n\
130 \n\
131  -h \n\
132  Print the help.\n\n");
133 
134  if (badparam)
135  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
136 }
137 
138 
139 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &configFile, std::string &modelFile,
140  std::string &initFile, bool &displayKltPoints, bool &click_allowed, bool &display,
141  bool& cao3DModel, bool &useOgre, bool &showOgreConfigDialog, bool &useScanline)
142 {
143  const char *optarg_;
144  int c;
145  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
146 
147  switch (c) {
148  case 'i': ipath = optarg_; break;
149  case 'x': configFile = optarg_; break;
150  case 'm': modelFile = optarg_; break;
151  case 'n': initFile = optarg_; break;
152  case 't': displayKltPoints = false; break;
153  case 'f': cao3DModel = true; break;
154  case 'c': click_allowed = false; break;
155  case 'd': display = false; break;
156  case 'o': useOgre = true; break;
157  case 'l': useScanline = true; break;
158  case 'w': showOgreConfigDialog = true; break;
159  case 'h': usage(argv[0], NULL); return false; break;
160 
161  default:
162  usage(argv[0], optarg_);
163  return false; break;
164  }
165  }
166 
167  if ((c == 1) || (c == -1)) {
168  // standalone param or error
169  usage(argv[0], NULL);
170  std::cerr << "ERROR: " << std::endl;
171  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
172  return false;
173  }
174 
175  return true;
176 }
177 
178 int
179 main(int argc, const char ** argv)
180 {
181  try {
182  std::string env_ipath;
183  std::string opt_ipath;
184  std::string ipath;
185  std::string opt_configFile;
186  std::string configFile;
187  std::string opt_modelFile;
188  std::string modelFile;
189  std::string opt_initFile;
190  std::string initFile;
191  bool displayKltPoints = true;
192  bool opt_click_allowed = true;
193  bool opt_display = true;
194  bool cao3DModel = false;
195  bool useOgre = false;
196  bool showOgreConfigDialog = false;
197  bool useScanline = false;
198  bool quit = false;
199 
200  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH environment variable value
201  env_ipath = vpIoTools::getViSPImagesDataPath();
202 
203  // Set the default input path
204  if (! env_ipath.empty())
205  ipath = env_ipath;
206 
207  // Read the command line options
208  if (!getOptions(argc, argv, opt_ipath, opt_configFile, opt_modelFile, opt_initFile, displayKltPoints,
209  opt_click_allowed, opt_display, cao3DModel, useOgre, showOgreConfigDialog, useScanline)) {
210  return (-1);
211  }
212 
213  // Test if an input path is set
214  if (opt_ipath.empty() && env_ipath.empty() ){
215  usage(argv[0], NULL);
216  std::cerr << std::endl
217  << "ERROR:" << std::endl;
218  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH "
219  << std::endl
220  << " environment variable to specify the location of the " << std::endl
221  << " image path where test images are located." << std::endl
222  << std::endl;
223 
224  return (-1);
225  }
226 
227  // Get the option values
228  if (!opt_ipath.empty())
229  ipath = vpIoTools::createFilePath(opt_ipath, "ViSP-images/mbt/cube/image%04d.pgm");
230  else
231  ipath = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube/image%04d.pgm");
232 
233  if (!opt_configFile.empty())
234  configFile = opt_configFile;
235  else if (!opt_ipath.empty())
236  configFile = vpIoTools::createFilePath(opt_ipath, "ViSP-images/mbt/cube.xml");
237  else
238  configFile = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube.xml");
239 
240  if (!opt_modelFile.empty()){
241  modelFile = opt_modelFile;
242  }else{
243  std::string modelFileCao = "ViSP-images/mbt/cube.cao";
244  std::string modelFileWrl = "ViSP-images/mbt/cube.wrl";
245 
246  if(!opt_ipath.empty()){
247  if(cao3DModel){
248  modelFile = vpIoTools::createFilePath(opt_ipath, modelFileCao);
249  }
250  else{
251 #ifdef VISP_HAVE_COIN3D
252  modelFile = vpIoTools::createFilePath(opt_ipath, modelFileWrl);
253 #else
254  std::cerr << "Coin is not detected in ViSP. Use the .cao model instead." << std::endl;
255  modelFile = vpIoTools::createFilePath(opt_ipath, modelFileCao);
256 #endif
257  }
258  }
259  else{
260  if(cao3DModel){
261  modelFile = vpIoTools::createFilePath(env_ipath, modelFileCao);
262  }
263  else{
264 #ifdef VISP_HAVE_COIN3D
265  modelFile = vpIoTools::createFilePath(env_ipath, modelFileWrl);
266 #else
267  std::cerr << "Coin is not detected in ViSP. Use the .cao model instead." << std::endl;
268  modelFile = vpIoTools::createFilePath(env_ipath, modelFileCao);
269 #endif
270  }
271  }
272  }
273 
274  if (!opt_initFile.empty())
275  initFile = opt_initFile;
276  else if (!opt_ipath.empty())
277  initFile = vpIoTools::createFilePath(opt_ipath, "ViSP-images/mbt/cube");
278  else
279  initFile = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube");
280 
282  vpVideoReader reader;
283 
284  reader.setFileName(ipath);
285  try{
286  reader.open(I);
287  }catch(...){
288  std::cout << "Cannot open sequence: " << ipath << std::endl;
289  return -1;
290  }
291 
292  reader.acquire(I);
293 
294  // initialise a display
295 #if defined VISP_HAVE_X11
296  vpDisplayX display;
297 #elif defined VISP_HAVE_GDI
298  vpDisplayGDI display;
299 #elif defined VISP_HAVE_OPENCV
300  vpDisplayOpenCV display;
301 #elif defined VISP_HAVE_D3D9
302  vpDisplayD3D display;
303 #elif defined VISP_HAVE_GTK
304  vpDisplayGTK display;
305 #else
306  opt_display = false;
307 #endif
308  if (opt_display)
309  {
310 #if (defined VISP_HAVE_DISPLAY)
311  display.init(I, 100, 100, "Test tracking") ;
312 #endif
313  vpDisplay::display(I) ;
314  vpDisplay::flush(I);
315  }
316 
317  vpMbKltTracker tracker;
319 
320  // Load tracker config file (camera parameters and moving edge settings)
321  vpCameraParameters cam;
322 #if defined (VISP_HAVE_XML2)
323  // From the xml file
324  tracker.loadConfigFile(configFile);
325 #else
326  // By setting the parameters:
327  cam.initPersProjWithoutDistortion(547, 542, 338, 234);
328 
329  vpKltOpencv klt;
330  klt.setMaxFeatures(10000);
331  klt.setWindowSize(5);
332  klt.setQuality(0.01);
333  klt.setMinDistance(5);
334  klt.setHarrisFreeParameter(0.01);
335  klt.setBlockSize(3);
336  klt.setPyramidLevels(3);
337 
338  tracker.setCameraParameters(cam);
339  tracker.setKltOpencv(klt);
340  tracker.setAngleAppear( vpMath::rad(65) );
341  tracker.setAngleDisappear( vpMath::rad(75) );
342  tracker.setMaskBorder(5);
343 
344  // Specify the clipping to use
345  tracker.setNearClippingDistance(0.01);
346  tracker.setFarClippingDistance(0.90);
348  // tracker.setClipping(tracker.getClipping() | vpMbtPolygon::LEFT_CLIPPING | vpMbtPolygon::RIGHT_CLIPPING | vpMbtPolygon::UP_CLIPPING | vpMbtPolygon::DOWN_CLIPPING); // Equivalent to FOV_CLIPPING
349 #endif
350 
351  // Display the klt points
352  tracker.setDisplayFeatures(displayKltPoints);
353 
354  // Tells if the tracker has to use Ogre3D for visibility tests
355  tracker.setOgreVisibilityTest(useOgre);
356  if (useOgre)
357  tracker.setOgreShowConfigDialog(showOgreConfigDialog);
358 
359  // Tells if the tracker has to use the scanline visibility tests
360  tracker.setScanLineVisibilityTest(useScanline);
361 
362  // Retrieve the camera parameters from the tracker
363  tracker.getCameraParameters(cam);
364 
365  // Loop to position the cube
366  if (opt_display && opt_click_allowed)
367  {
368  while(!vpDisplay::getClick(I,false)){
370  vpDisplay::displayText(I, 15, 10, "click after positioning the object", vpColor::red);
371  vpDisplay::flush(I) ;
372  }
373  }
374 
375  // Load the 3D model (either a vrml file or a .cao file)
376  tracker.loadModel(modelFile);
377 
378  // Initialise the tracker by clicking on the image
379  // This function looks for
380  // - a ./cube/cube.init file that defines the 3d coordinates (in meter, in the object basis) of the points used for the initialisation
381  // - a ./cube/cube.ppm file to display where the user have to click (optionnal, set by the third parameter)
382  if (opt_display && opt_click_allowed)
383  {
384  tracker.initClick(I, initFile, true);
385  tracker.getPose(cMo);
386  // display the 3D model at the given pose
387  tracker.display(I,cMo, cam, vpColor::red);
388  }
389  else
390  {
391  vpHomogeneousMatrix cMoi(0.02044769891, 0.1101505452, 0.5078963719, 2.063603907, 1.110231561, -0.4392789872);
392  tracker.initFromPose(I, cMoi);
393  }
394 
395  //track the model
396  tracker.track(I);
397  tracker.getPose(cMo);
398 
399  if (opt_display)
400  vpDisplay::flush(I);
401 
402  // Uncomment if you want to compute the covariance matrix.
403  // tracker.setCovarianceComputation(true); //Important if you want tracker.getCovarianceMatrix() to work.
404 
405  while (!reader.end())
406  {
407  // acquire a new image
408  reader.acquire(I);
409  // display the image
410  if (opt_display)
412 
413  // Test to reset the tracker
414  if (reader.getFrameIndex() == reader.getFirstFrameIndex() + 10) {
415  vpTRACE("Test reset tracker");
416  if (opt_display)
418  tracker.resetTracker();
419 #if defined (VISP_HAVE_XML2)
420  tracker.loadConfigFile(configFile);
421 #else
422  // By setting the parameters:
423  cam.initPersProjWithoutDistortion(547, 542, 338, 234);
424 
425  vpKltOpencv klt;
426  klt.setMaxFeatures(10000);
427  klt.setWindowSize(5);
428  klt.setQuality(0.01);
429  klt.setMinDistance(5);
430  klt.setHarrisFreeParameter(0.01);
431  klt.setBlockSize(3);
432  klt.setPyramidLevels(3);
433 
434  tracker.setCameraParameters(cam);
435  tracker.setKltOpencv(klt);
436  tracker.setAngleAppear( vpMath::rad(65) );
437  tracker.setAngleDisappear( vpMath::rad(75) );
438  tracker.setMaskBorder(5);
439 
440  // Specify the clipping to use
441  tracker.setNearClippingDistance(0.01);
442  tracker.setFarClippingDistance(0.90);
444  // tracker.setClipping(tracker.getClipping() | vpMbtPolygon::LEFT_CLIPPING | vpMbtPolygon::RIGHT_CLIPPING | vpMbtPolygon::UP_CLIPPING | vpMbtPolygon::DOWN_CLIPPING); // Equivalent to FOV_CLIPPING
445 #endif
446  tracker.loadModel(modelFile);
447  tracker.setCameraParameters(cam);
448  tracker.setOgreVisibilityTest(useOgre);
449  tracker.setScanLineVisibilityTest(useScanline);
450  tracker.initFromPose(I, cMo);
451  }
452 
453  // Test to set an initial pose
454  if (reader.getFrameIndex() == reader.getFirstFrameIndex() + 50) {
455  cMo.buildFrom(0.0439540832, 0.0845870108, 0.5477322481, 2.179498458, 0.8611798108, -0.3491961946);
456  vpTRACE("Test set pose");
457  tracker.setPose(I, cMo);
458 // if (opt_display) {
459 // // display the 3D model
460 // tracker.display(I, cMo, cam, vpColor::darkRed);
461 // // display the frame
462 // vpDisplay::displayFrame (I, cMo, cam, 0.05);
467 // }
468  }
469 
470  // track the object: stop tracking from frame 40 to 50
471  if (reader.getFrameIndex() - reader.getFirstFrameIndex() < 40 || reader.getFrameIndex() - reader.getFirstFrameIndex() >= 50) {
472  tracker.track(I);
473  tracker.getPose(cMo);
474  if (opt_display) {
475  // display the 3D model
476  tracker.display(I, cMo, cam, vpColor::darkRed);
477  // display the frame
478  vpDisplay::displayFrame (I, cMo, cam, 0.05);
479  }
480  }
481 
482  if (opt_click_allowed) {
483  vpDisplay::displayText(I, 10, 10, "Click to quit", vpColor::red);
484  if (vpDisplay::getClick(I, false)) {
485  quit = true;
486  break;
487  }
488  }
489 
490  // Uncomment if you want to print the covariance matrix.
491  // Make sure tracker.setCovarianceComputation(true) has been called (uncomment below).
492  // std::cout << tracker.getCovarianceMatrix() << std::endl << std::endl;
493 
494  vpDisplay::flush(I) ;
495  }
496  if (opt_click_allowed && !quit) {
498  }
499 
500  reader.close();
501 
502 #if defined (VISP_HAVE_XML2)
503  // Cleanup memory allocated by xml library used to parse the xml config file in vpMbKltTracker::loadConfigFile()
505 #endif
506 
507 #if defined(VISP_HAVE_COIN3D) && (COIN_MAJOR_VERSION == 3)
508  // Cleanup memory allocated by Coin library used to load a vrml model in vpMbKltTracker::loadModel()
509  // We clean only if Coin was used.
510  if(! cao3DModel)
511  SoDB::finish();
512 #endif
513 
514  return 0;
515  }
516  catch(vpException e) {
517  std::cout << "Catch an exception: " << e << std::endl;
518  return 1;
519  }
520 }
521 
522 #else
523 
524 int main()
525 {
526  std::cout << "visp_mbt, visp_gui modules and OpenCV are required to run this example." << std::endl;
527  return 0;
528 
529 }
530 
531 #endif
void setKltOpencv(const vpKltOpencv &t)
virtual void track(const vpImage< unsigned char > &I)
long getFrameIndex() const
virtual void setScanLineVisibilityTest(const bool &v)
long getFirstFrameIndex() const
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1091
void setHarrisFreeParameter(double harris_k)
virtual unsigned int getClipping() const
Definition: vpMbTracker.h:232
virtual void setAngleDisappear(const double &a)
Definition: vpMbTracker.h:430
Implementation of an homogeneous matrix and operations on such kind of matrices.
static const vpColor darkRed
Definition: vpColor.h:164
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:128
void setMaxFeatures(const int maxCount)
static void displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
Definition: vpDisplay.cpp:888
Define the X11 console to display images.
Definition: vpDisplayX.h:148
Class that enables to manipulate easily a video file or a sequence of images. As it inherits from the...
void setMinDistance(double minDistance)
error that can be emited by ViSP classes.
Definition: vpException.h:73
void init(vpImage< unsigned char > &I, int winx=-1, int winy=-1, const char *title=NULL)
virtual void initFromPose(const vpImage< unsigned char > &I, const std::string &initFile)
static void flush(const vpImage< unsigned char > &I)
Definition: vpDisplay.cpp:2233
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:76
static const vpColor red
Definition: vpColor.h:163
virtual void loadConfigFile(const std::string &configFile)
void setQuality(double qualityLevel)
void initPersProjWithoutDistortion(const double px, const double py, const double u0, const double v0)
void setOgreShowConfigDialog(const bool showConfigDialog)
Definition: vpMbTracker.h:523
void open(vpImage< vpRGBa > &I)
Display for windows using Direct3D.
Definition: vpDisplayD3D.h:105
void getPose(vpHomogeneousMatrix &cMo_) const
Definition: vpMbTracker.h:356
#define vpTRACE
Definition: vpDebug.h:414
static std::string createFilePath(const std::string &parent, const std::string child)
Definition: vpIoTools.cpp:1265
static void display(const vpImage< unsigned char > &I)
Definition: vpDisplay.cpp:206
The vpDisplayOpenCV allows to display image using the opencv library.
virtual void getCameraParameters(vpCameraParameters &camera) const
Definition: vpMbTracker.h:225
Generic class defining intrinsic camera parameters.
The vpDisplayGTK allows to display image using the GTK+ library version 1.2.
Definition: vpDisplayGTK.h:141
void acquire(vpImage< vpRGBa > &I)
void setFileName(const char *filename)
virtual void setAngleAppear(const double &a)
Definition: vpMbTracker.h:419
Model based tracker using only KLT.
virtual void initClick(const vpImage< unsigned char > &I, const std::string &initFile, const bool displayHelp=false)
void setPyramidLevels(const int pyrMaxLevel)
void buildFrom(const vpTranslationVector &t, const vpRotationMatrix &R)
static double rad(double deg)
Definition: vpMath.h:104
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, vpImagePoint offset=vpImagePoint(0, 0))
Definition: vpDisplay.cpp:373
static void cleanup()
Definition: vpXmlParser.h:216
void setWindowSize(const int winSize)
void setMaskBorder(const unsigned int &e)
virtual void loadModel(const char *modelFile, const bool verbose=false)
void setCameraParameters(const vpCameraParameters &cam)
virtual void setOgreVisibilityTest(const bool &v)
Wrapper for the KLT (Kanade-Lucas-Tomasi) feature tracker implemented in OpenCV.
Definition: vpKltOpencv.h:75
void setBlockSize(const int blockSize)
virtual void setClipping(const unsigned int &flags)
virtual bool getClick(bool blocking=true)=0
void setDisplayFeatures(const bool displayF)
Definition: vpMbTracker.h:459
virtual void setFarClippingDistance(const double &dist)
virtual void display(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cMo, const vpCameraParameters &cam, const vpColor &col, const unsigned int thickness=1, const bool displayFullModel=false)
virtual void setPose(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cdMo)
virtual void setNearClippingDistance(const double &dist)