Visual Servoing Platform  version 3.6.1 under development (2024-11-15)
trackKltOpencv.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 dot tracking.
33  *
34 *****************************************************************************/
41 #include <visp3/core/vpConfig.h>
42 #include <visp3/core/vpDebug.h>
43 
44 #include <iomanip>
45 #include <sstream>
46 #include <stdio.h>
47 #include <vector>
48 
49 #if defined(VISP_HAVE_MODULE_KLT) && (defined(VISP_HAVE_X11) || defined(VISP_HAVE_GTK) || defined(VISP_HAVE_GDI) || defined(VISP_HAVE_OPENCV))
50 
51 #if defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_VIDEO)
52 
53 #include <visp3/core/vpImage.h>
54 #include <visp3/core/vpIoTools.h>
55 #include <visp3/gui/vpDisplayGDI.h>
56 #include <visp3/gui/vpDisplayGTK.h>
57 #include <visp3/gui/vpDisplayOpenCV.h>
58 #include <visp3/gui/vpDisplayX.h>
59 #include <visp3/io/vpImageIo.h>
60 #include <visp3/io/vpParseArgv.h>
61 #include <visp3/klt/vpKltOpencv.h>
62 
63 // List of allowed command line options
64 #define GETOPTARGS "cdf:i:l:p:s:h"
65 
66 #ifdef ENABLE_VISP_NAMESPACE
67 using namespace VISP_NAMESPACE_NAME;
68 #endif
69 
70 void usage(const char *name, const char *badparam, std::string ipath, std::string ppath, unsigned first,
71  unsigned last, unsigned step);
72 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &ppath, unsigned &first, unsigned &last,
73  unsigned &step, bool &click_allowed, bool &display);
95 void usage(const char *name, const char *badparam, std::string ipath, std::string ppath, unsigned first,
96  unsigned last, unsigned step)
97 {
98 #if VISP_HAVE_DATASET_VERSION >= 0x030600
99  std::string ext("png");
100 #else
101  std::string ext("pgm");
102 #endif
103  fprintf(stdout, "\n\
104 Example of KLT tracking using OpenCV library.\n\
105 \n\
106 SYNOPSIS\n\
107  %s [-i <test image path>] [-p <personal image path>]\n\
108  [-f <first image>] [-l <last image>] [-s <step>]\n\
109  [-c] [-d] [-h]\n",
110  name);
111 
112  fprintf(stdout, "\n\
113 OPTIONS: Default\n\
114  -i <input image path> %s\n\
115  Set image input path.\n\
116  From this path read images \n\
117  \"mire-2/image.%%04d.%s\". These \n\
118  images come from visp-images-x.y.z.tar.gz available \n\
119  on the ViSP website.\n\
120  Setting the VISP_INPUT_IMAGE_PATH environment\n\
121  variable produces the same behaviour than using\n\
122  this option.\n\
123  \n\
124  -p <personal image path> %s\n\
125  Specify a personal sequence containing images \n\
126  to process.\n\
127  By image sequence, we mean one file per image.\n\
128  Example : \"/Temp/visp-images/mire-2/image.%%04d.%s\"\n\
129  %%04d is for the image numbering.\n\
130  \n\
131  -f <first image> %u\n\
132  First image number of the sequence.\n\
133  \n\
134  -l <last image> %u\n\
135  Last image number of the sequence.\n\
136  \n\
137  -s <step> %u\n\
138  Step between two images.\n\
139 \n\
140  -c\n\
141  Disable the mouse click. Useful to automate the \n\
142  execution of this program without human intervention.\n\
143 \n\
144  -d \n\
145  Turn off the display.\n\
146 \n\
147  -h\n\
148  Print the help.\n",
149  ipath.c_str(), ext.c_str(), ppath.c_str(), ext.c_str(), first, last, step);
150 
151  if (badparam)
152  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
153 }
154 
172 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &ppath, unsigned &first, unsigned &last,
173  unsigned &step, bool &click_allowed, bool &display)
174 {
175  const char *optarg_;
176  int c;
177  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
178 
179  switch (c) {
180  case 'c':
181  click_allowed = false;
182  break;
183  case 'd':
184  display = false;
185  break;
186  case 'i':
187  ipath = optarg_;
188  break;
189  case 'p':
190  ppath = optarg_;
191  break;
192  case 'f':
193  first = (unsigned)atoi(optarg_);
194  break;
195  case 'l':
196  last = (unsigned)atoi(optarg_);
197  break;
198  case 's':
199  step = (unsigned)atoi(optarg_);
200  break;
201  case 'h':
202  usage(argv[0], nullptr, ipath, ppath, first, last, step);
203  return false;
204  break;
205 
206  default:
207  usage(argv[0], optarg_, ipath, ppath, first, last, step);
208  return false;
209  break;
210  }
211  }
212 
213  if ((c == 1) || (c == -1)) {
214  // standalone param or error
215  usage(argv[0], nullptr, ipath, ppath, first, last, step);
216  std::cerr << "ERROR: " << std::endl;
217  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
218  return false;
219  }
220 
221  return true;
222 }
223 
224 int main(int argc, const char **argv)
225 {
226  try {
227  std::string env_ipath;
228  std::string opt_ipath;
229  std::string ipath;
230  std::string opt_ppath;
231  std::string dirname;
232  std::string filename;
233  unsigned opt_first = 1;
234  unsigned opt_last = 500;
235  unsigned opt_step = 1;
236  bool opt_click_allowed = true;
237  bool opt_display = true;
238 
239 #if VISP_HAVE_DATASET_VERSION >= 0x030600
240  std::string ext("png");
241 #else
242  std::string ext("pgm");
243 #endif
244 
245  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
246  // environment variable value
247  env_ipath = vpIoTools::getViSPImagesDataPath();
248 
249  // Set the default input path
250  if (!env_ipath.empty())
251  ipath = env_ipath;
252 
253  // Read the command line options
254  if (getOptions(argc, argv, opt_ipath, opt_ppath, opt_first, opt_last, opt_step, opt_click_allowed,
255  opt_display) == false) {
256  return EXIT_FAILURE;
257  }
258 
259  // Get the option values
260  if (!opt_ipath.empty())
261  ipath = opt_ipath;
262 
263  // Compare ipath and env_ipath. If they differ, we take into account
264  // the input path coming from the command line option
265  if (!opt_ipath.empty() && !env_ipath.empty() && opt_ppath.empty()) {
266  if (ipath != env_ipath) {
267  std::cout << std::endl << "WARNING: " << std::endl;
268  std::cout << " Since -i <visp image path=" << ipath << "> "
269  << " is different from VISP_IMAGE_PATH=" << env_ipath << std::endl
270  << " we skip the environment variable." << std::endl;
271  }
272  }
273 
274  // Test if an input path is set
275  if (opt_ipath.empty() && env_ipath.empty() && opt_ppath.empty()) {
276  usage(argv[0], nullptr, ipath, opt_ppath, opt_first, opt_last, opt_step);
277  std::cerr << std::endl << "ERROR:" << std::endl;
278  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
279  << " environment variable to specify the location of the " << std::endl
280  << " image path where test images are located." << std::endl
281  << " Use -p <personal image path> option if you want to " << std::endl
282  << " use personal images." << std::endl
283  << std::endl;
284 
285  return EXIT_FAILURE;
286  }
287 
288  // Declare an image, this is a gray level image (unsigned char)
289  // it size is not defined yet, it will be defined when the image will
290  // read on the disk
291  vpImage<unsigned char> vpI; // This is a ViSP image used for display only
292  cv::Mat cvI;
293 
294  unsigned iter = opt_first;
295  std::ostringstream s;
296  char cfilename[FILENAME_MAX];
297 
298  if (opt_ppath.empty()) {
299 
300  // Warning :
301  // The image sequence is not provided with the ViSP package
302  // therefore the program will return an error :
303  // !! couldn't read file visp-images/mire-2/image.0001.png
304  //
305  // ViSP dataset is available on the visp www site
306  // https://visp.inria.fr/download/.
307 
308  // Set the path location of the image sequence
309  dirname = vpIoTools::createFilePath(ipath, "mire-2");
310 
311  // Build the name of the image file
312 
313  s.setf(std::ios::right, std::ios::adjustfield);
314  s << "image." << std::setw(4) << std::setfill('0') << iter << "." << ext;
315  filename = vpIoTools::createFilePath(dirname, s.str());
316  }
317  else {
318  snprintf(cfilename, FILENAME_MAX, opt_ppath.c_str(), iter);
319  filename = cfilename;
320  }
321 
322  // Read the image named "filename", and put the bitmap into the image structure I.
323  // I is initialized to the correct size
324  //
325  // vpImageIo::read() may throw various exception if, for example,
326  // the file does not exist, or if the memory cannot be allocated
327  try {
328  std::cout << "Load: " << filename << std::endl;
329 
330  // Load a ViSP image used for the display
331  vpImageIo::read(vpI, filename);
332  vpImageConvert::convert(vpI, cvI);
333  }
334  catch (...) {
335  // If an exception is thrown by vpImageIo::read() it will result in the end of the program.
336  std::cerr << std::endl << "ERROR:" << std::endl;
337  std::cerr << " Cannot read " << filename << std::endl;
338  if (opt_ppath.empty()) {
339  std::cerr << " Check your -i " << ipath << " option " << std::endl
340  << " or VISP_INPUT_IMAGE_PATH environment variable." << std::endl;
341  }
342  else {
343  std::cerr << " Check your -p " << opt_ppath << " option " << std::endl;
344  }
345  return EXIT_FAILURE;
346  }
347 
348 // We open a window using either X11, GTK or GDI.
349 #if defined(VISP_HAVE_X11)
350  vpDisplayX display;
351 #elif defined(VISP_HAVE_GTK)
352  vpDisplayGTK display;
353 #elif defined(VISP_HAVE_GDI)
354  vpDisplayGDI display;
355 #elif defined(HAVE_OPENCV_HIGHGUI)
356  vpDisplayOpenCV display;
357 #endif
358 
359  if (opt_display) {
360  // Display size is automatically defined by the image (I) size
361  display.init(vpI, 100, 100, "Display...");
362  // Display the image
363  // The image class has a member that specify a pointer toward
364  // the display that has been initialized in the display declaration
365  // therefore is is no longer necessary to make a reference to the
366  // display variable.
367  vpDisplay::display(vpI);
368  vpDisplay::flush(vpI);
369  }
370 
371  // KLT tracker
372  vpKltOpencv tracker;
373 
374  // Event manager
375  // tracker.setOnNewFeature(&newFeature);
376  // tracker.setOnFeatureLost(&lostFeature);
377  // tracker.setIsFeatureValid(&isValid);
378 
379  // Tracker parameters
380  tracker.setTrackerId(1);
381  // tracker.setOnMeasureFeature(&modifyFeature);
382  tracker.setMaxFeatures(200);
383  tracker.setWindowSize(10);
384  tracker.setQuality(0.01);
385  tracker.setMinDistance(15);
386  tracker.setHarrisFreeParameter(0.04);
387  tracker.setBlockSize(9);
388  tracker.setUseHarris(1);
389  tracker.setPyramidLevels(3);
390 
391  // Point detection using Harris. In input we have an OpenCV IPL image
392  tracker.initTracking(cvI);
393 
394  if (opt_display) {
395  // Plot the Harris points on ViSP image
396  tracker.display(vpI, vpColor::red);
397  }
398 
399  // tracking is now initialized. We can start the tracker.
400  while (iter < opt_last) {
401  // set the new image name
402  if (opt_ppath.empty()) {
403  s.str("");
404  s << "image." << std::setw(4) << std::setfill('0') << iter << "." << ext;
405  filename = vpIoTools::createFilePath(dirname, s.str());
406  }
407  else {
408  snprintf(cfilename, FILENAME_MAX, opt_ppath.c_str(), iter);
409  filename = cfilename;
410  }
411  // read the image
412  vpImageIo::read(vpI, filename);
413  vpImageConvert::convert(vpI, cvI);
414 
415  // track the dot and returns its coordinates in the image
416  // results are given in float since many many are usually considered
417  //
418  // an exception is thrown by the track method if
419  // - dot is lost
420 
421  if (opt_display) {
422  // Display the image
423  vpDisplay::display(vpI);
424  }
425 
426  std::cout << "Tracking on image: " << filename << std::endl;
427  double time = vpTime::measureTimeMs();
428  // Tracking of the detected points
429  tracker.track(cvI);
430  std::cout << "Tracking performed in " << vpTime::measureTimeMs() - time << " ms" << std::endl;
431 
432  if (opt_display) {
433  // Display the tracked points
434  tracker.display(vpI, vpColor::red);
435 
436  vpDisplay::flush(vpI);
437  }
438  iter += opt_step;
439  }
440  if (opt_display && opt_click_allowed) {
441  std::cout << "\nA click to exit..." << std::endl;
442  // Wait for a blocking mouse click
443  vpDisplay::getClick(vpI);
444  }
445  return EXIT_SUCCESS;
446  }
447  catch (const vpException &e) {
448  std::cout << "Catch an exception: " << e << std::endl;
449  return EXIT_FAILURE;
450  }
451 }
452 #else
453 int main()
454 {
455  std::cout << "You do not have OpenCV functionalities to display images..." << std::endl;
456  std::cout << "Tip:" << std::endl;
457  std::cout << "- Install OpenCV, configure again ViSP using cmake and build again this example" << std::endl;
458  return EXIT_SUCCESS;
459 }
460 #endif
461 #else
462 #include <iostream>
463 
464 int main()
465 {
466  std::cout << "visp_klt module or X11, GTK, GDI or OpenCV display "
467  "functionalities are required..."
468  << std::endl;
469  }
470 
471 #endif
static const vpColor red
Definition: vpColor.h:217
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:130
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:133
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
static void display(const vpImage< unsigned char > &I)
static void flush(const vpImage< unsigned char > &I)
error that can be emitted by ViSP classes.
Definition: vpException.h:60
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
static void read(vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Definition: vpImageIo.cpp:147
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1053
static std::string createFilePath(const std::string &parent, const std::string &child)
Definition: vpIoTools.cpp:1427
Wrapper for the KLT (Kanade-Lucas-Tomasi) feature tracker implemented in OpenCV. Thus to enable this ...
Definition: vpKltOpencv.h:74
void display(const vpImage< unsigned char > &I, const vpColor &color=vpColor::red, unsigned int thickness=1) const
void setBlockSize(int blockSize)
Definition: vpKltOpencv.h:267
void setQuality(double qualityLevel)
Definition: vpKltOpencv.h:356
void track(const cv::Mat &I)
void setTrackerId(int tid)
Definition: vpKltOpencv.h:360
void setHarrisFreeParameter(double harris_k)
Definition: vpKltOpencv.h:275
void setMaxFeatures(int maxCount)
Definition: vpKltOpencv.h:315
void initTracking(const cv::Mat &I, const cv::Mat &mask=cv::Mat())
Definition: vpKltOpencv.cpp:94
void setMinDistance(double minDistance)
Definition: vpKltOpencv.h:324
void setUseHarris(int useHarrisDetector)
Definition: vpKltOpencv.h:368
void setWindowSize(int winSize)
Definition: vpKltOpencv.h:377
void setPyramidLevels(int pyrMaxLevel)
Definition: vpKltOpencv.h:343
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:70
VISP_EXPORT double measureTimeMs()