Visual Servoing Platform  version 3.2.0 under development (2019-01-22)
fernClassifier.cpp
1 /****************************************************************************
2  *
3  * ViSP, open source Visual Servoing Platform software.
4  * Copyright (C) 2005 - 2019 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  * Detection of points of interests and matching using the Ferns classifier.
33  *
34  * Authors:
35  * Romain Tallonneau
36  *
37  *****************************************************************************/
51 #include <visp3/core/vpConfig.h>
52 #include <visp3/core/vpDebug.h>
53 
54 #if ((defined(VISP_HAVE_X11) || defined(VISP_HAVE_GTK) || defined(VISP_HAVE_GDI)) && \
55  (VISP_HAVE_OPENCV_VERSION >= 0x020000) && (VISP_HAVE_OPENCV_VERSION < 0x030000))
56 
57 #include <iomanip>
58 #include <iostream>
59 #include <stdlib.h>
60 #include <visp3/core/vpConfig.h>
61 #include <visp3/core/vpImage.h>
62 #include <visp3/core/vpIoTools.h>
63 #include <visp3/core/vpTime.h>
64 #include <visp3/gui/vpDisplayGDI.h>
65 #include <visp3/gui/vpDisplayGTK.h>
66 #include <visp3/gui/vpDisplayX.h>
67 #include <visp3/io/vpImageIo.h>
68 #include <visp3/io/vpParseArgv.h>
69 #include <visp3/vision/vpFernClassifier.h>
70 #include <visp3/vision/vpHomography.h>
71 
72 #define GETOPTARGS "hlcdb:i:p"
73 
74 void usage(const char *name, const char *badparam);
75 bool getOptions(int argc, const char **argv, bool &isLearning, std::string &dataFile, bool &click_allowed,
76  bool &display, bool &displayPoints, std::string &ipath);
77 
86 void usage(const char *name, const char *badparam)
87 {
88  fprintf(stdout, "\n\
89 Detection of points of interests and matching using the Ferns classifier. The \
90 object needs first to be learned (-l option). This learning process will create\
91 a file used to detect the object.\n\
92 \n\
93 SYNOPSIS\n\
94  %s [-l] [-h] [-b] [-c] [-d] [-p] [-i]\n", name);
95 
96  fprintf(stdout, "\n\
97 OPTIONS: \n\
98  -l\n\
99  learn an object.\n\
100 \n\
101  -i <input image path> \n\
102  Set image input path.\n\
103  From this path read \"line/image.%%04d.pgm\"\n\
104  images. \n\
105  Setting the VISP_INPUT_IMAGE_PATH environment\n\
106  variable produces the same behaviour than using\n\
107  this option.\n\
108 \n\
109  -b\n\
110  database filename to use (default is ./dataFern).\n\
111 \n\
112  -c\n\
113  Disable the mouse click. Useful to automaze the \n\
114  execution of this program without humain intervention.\n\
115 \n\
116  -d \n\
117  Turn off the display.\n\
118 \n\
119  -p \n\
120  display points of interest.\n\
121 \n\
122  -h\n\
123  Print this help.\n");
124 
125  if (badparam)
126  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
127 }
128 
145 bool getOptions(int argc, const char **argv, bool &isLearning, std::string &dataFile, bool &click_allowed,
146  bool &display, bool &displayPoints, std::string &ipath)
147 {
148  const char *optarg_;
149  int c;
150  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
151 
152  switch (c) {
153  case 'c':
154  click_allowed = false;
155  break;
156  case 'd':
157  display = false;
158  break;
159  case 'l':
160  isLearning = true;
161  break;
162  case 'h':
163  usage(argv[0], NULL);
164  return false;
165  break;
166  case 'b':
167  dataFile = optarg_;
168  break;
169  case 'p':
170  displayPoints = true;
171  break;
172  case 'i':
173  ipath = optarg_;
174  break;
175  default:
176  usage(argv[0], optarg_);
177  return false;
178  break;
179  }
180  }
181 
182  if ((c == 1) || (c == -1)) {
183  // standalone param or error
184  usage(argv[0], NULL);
185  std::cerr << "ERROR: " << std::endl;
186  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
187  return false;
188  }
189 
190  return true;
191 }
192 
193 int main(int argc, const char **argv)
194 {
195  try {
196  bool isLearning = false;
197  std::string dataFile("./dataFern");
198  bool opt_click_allowed = true;
199  bool opt_display = true;
200  std::string objectName("object");
201  bool displayPoints = false;
202  std::string opt_ipath;
203  std::string ipath;
204  std::string env_ipath;
205  std::string dirname;
206  std::string filename;
207 
208  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
209  // environment variable value
210  env_ipath = vpIoTools::getViSPImagesDataPath();
211 
212  // Set the default input path
213  if (!env_ipath.empty()) {
214  ipath = env_ipath;
215  }
216 
217  // Read the command line options
218  if (getOptions(argc, argv, isLearning, dataFile, opt_click_allowed, opt_display, displayPoints, opt_ipath) ==
219  false) {
220  exit(-1);
221  }
222 
223  // Get the option values
224  if (!opt_ipath.empty()) {
225  ipath = opt_ipath;
226  }
227 
228  // Compare ipath and env_ipath. If they differ, we take into account
229  // the input path comming from the command line option
230  if (!opt_ipath.empty() && !env_ipath.empty()) {
231  if (ipath != env_ipath) {
232  std::cout << std::endl << "WARNING: " << std::endl;
233  std::cout << " Since -i <visp image path=" << ipath << "> "
234  << " is different from VISP_IMAGE_PATH=" << env_ipath << std::endl
235  << " we skip the environment variable." << std::endl;
236  }
237  }
238 
239  // Test if an input path is set
240  if (opt_ipath.empty() && env_ipath.empty()) {
241  usage(argv[0], NULL);
242  std::cerr << std::endl << "ERROR:" << std::endl;
243  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
244  << " environment variable to specify the location of the " << std::endl
245  << " image path where test images are located." << std::endl
246  << std::endl;
247  exit(-1);
248  }
249 
250  // Declare two images, these are gray level images (unsigned char)
253 
254  // Set the path location of the image sequence
255  dirname = vpIoTools::createFilePath(ipath, "cube");
256 
257  // Build the name of the image file
258  unsigned iter = 0; // Image number
259  std::ostringstream s;
260  s.setf(std::ios::right, std::ios::adjustfield);
261  s << "image." << std::setw(4) << std::setfill('0') << iter << ".pgm";
262  filename = vpIoTools::createFilePath(dirname, s.str());
263 
264  // Read the PGM image named "filename" on the disk, and put the
265  // bitmap into the image structure I. I is initialized to the
266  // correct size
267  //
268  // exception readPGM may throw various exception if, for example,
269  // the file does not exist, or if the memory cannot be allocated
270  try {
271  std::cout << "Load: " << filename << std::endl;
272  vpImageIo::read(Iref, filename);
273  I = Iref;
274  } catch (...) {
275  // an exception is throwned if an exception from readPGM has been
276  // catched here this will result in the end of the program Note that
277  // another error message has been printed from readPGM to give more
278  // information about the error
279  std::cerr << std::endl << "ERROR:" << std::endl;
280  std::cerr << " Cannot read " << filename << std::endl;
281  std::cerr << " Check your -i " << ipath << " option " << std::endl
282  << " or VISP_INPUT_IMAGE_PATH environment variable." << std::endl;
283  exit(-1);
284  }
285 
286 #if defined VISP_HAVE_X11
287  vpDisplayX display;
288 #elif defined VISP_HAVE_GTK
289  vpDisplayGTK display;
290 #elif defined VISP_HAVE_GDI
291  vpDisplayGDI display;
292 #endif
293 
294 #if defined VISP_HAVE_X11
295  vpDisplayX displayRef;
296 #elif defined VISP_HAVE_GTK
297  vpDisplayGTK displayRef;
298 #elif defined VISP_HAVE_GDI
299  vpDisplayGDI displayRef;
300 #endif
301 
302  // declare a planar object detector
303  vpFernClassifier fern;
304 
305  if (isLearning) {
306  if (opt_display) {
307  displayRef.init(Iref, 100, 100, "Reference image");
308  vpDisplay::display(Iref);
309  vpDisplay::flush(Iref);
310  }
311  vpImagePoint corners[2];
312  if (opt_display && opt_click_allowed) {
313  std::cout << "Click on the top left and the bottom right corners to "
314  "define the reference plane"
315  << std::endl;
316  for (int i = 0; i < 2; i++) {
317  vpDisplay::getClick(Iref, corners[i]);
318  std::cout << corners[i] << std::endl;
319  }
320  } else {
321  corners[0].set_ij(1, 1);
322  corners[1].set_ij(I.getHeight() - 2, I.getWidth() - 2);
323  }
324 
325  if (opt_display) {
326  // Display the rectangle which defines the part of the image where the
327  // reference points are computed.
328  vpDisplay::displayRectangle(Iref, corners[0], corners[1], vpColor::green);
329  vpDisplay::flush(Iref);
330  }
331 
332  if (opt_click_allowed) {
333  std::cout << "Click on the image to continue" << std::endl;
334  vpDisplay::getClick(Iref);
335  }
336 
337  vpRect roi(corners[0], corners[1]);
338 
339  std::cout << "> train the classifier on the selected plane. (may take "
340  "up to several minutes)."
341  << std::endl;
342  if (opt_display) {
343  vpDisplay::display(Iref);
344  vpDisplay::flush(Iref);
345  }
346 
347  try {
348  fern.buildReference(Iref, roi);
349  } catch (const vpException &e) {
350  std::cout << e.getMessage() << std::endl;
351  } catch (...) {
352  std::cout << "unknown error, line " << __LINE__ << std::endl;
353  }
354  try {
355  fern.record(objectName, dataFile);
356  } catch (const vpException &e) {
357  std::cout << e.getMessage() << std::endl;
358  } catch (...) {
359  std::cout << "unknown error, line " << __LINE__ << std::endl;
360  }
361  std::cout << __LINE__ << std::endl;
362  } else {
363  if (!vpIoTools::checkFilename(dataFile)) {
364  vpERROR_TRACE("cannot load the database with the specified name. Has "
365  "the object been learned with the -l option? ");
366  exit(-1);
367  }
368  try {
369  // load a previously recorded file
370  fern.load(dataFile, objectName);
371  } catch (...) {
372  vpERROR_TRACE("cannot load the database with the specified name. Has "
373  "the object been learned with the -l option? ");
374  exit(-1);
375  }
376  }
377 
378  if (opt_display) {
379  display.init(I, 110 + (int)Iref.getWidth(), 100, "Current image");
381  vpDisplay::flush(I);
382  }
383 
384  if (opt_display && opt_click_allowed) {
385  std::cout << "Click on the current image to continue" << std::endl;
386  vpDisplay::displayText(I, vpImagePoint(15, 15), "Click on the current image to continue", vpColor::red);
387  vpDisplay::flush(I);
389  }
390 
391  for (;;) {
392  // acquire a new image
393  iter++;
394  if (iter >= 80) {
395  break;
396  }
397  s.str("");
398  s << "image." << std::setw(4) << std::setfill('0') << iter << ".pgm";
399  filename = vpIoTools::createFilePath(dirname, s.str());
400  // read the image
401  vpImageIo::read(I, filename);
402 
403  if (opt_display) {
405  if (isLearning)
406  vpDisplay::display(Iref);
407  }
408 
409  double t0 = vpTime::measureTimeMs();
410  // detection of the reference image
411  unsigned int nbpts;
412  try {
413  nbpts = fern.matchPoint(I);
414  } catch (const vpException &e) {
415  std::cout << e.getMessage() << std::endl;
416  return -1;
417  } catch (...) {
418  std::cout << "unknown error line " << __LINE__ << std::endl;
419  return -1;
420  }
421  std::cout << "matching " << nbpts << " points : " << vpTime::measureTimeMs() - t0 << " ms" << std::endl;
422 
423  if (opt_display) {
424  fern.display(Iref, I, 7);
425  vpDisplay::flush(I);
426  if (isLearning)
427  vpDisplay::flush(Iref);
428  if (vpDisplay::getClick(I, false)) {
429  break;
430  }
431  }
432  }
433 
434  return EXIT_SUCCESS;
435  } catch (const vpException &e) {
436  std::cout << "Catch an exception: " << e << std::endl;
437  return EXIT_SUCCESS;
438  }
439 }
440 
441 #else
442 int main()
443 {
444 #if (!(defined(VISP_HAVE_X11) || defined(VISP_HAVE_GTK) || defined(VISP_HAVE_GDI)))
445  std::cout << "You do not have X11, or GTK, or GDI (Graphical Device Interface) functionalities to display images..." << std::endl;
446  std::cout << "Tip if you are on a unix-like system:" << std::endl;
447  std::cout << "- Install X11, configure again ViSP using cmake and build again this example" << std::endl;
448  std::cout << "Tip if you are on a windows-like system:" << std::endl;
449  std::cout << "- Install GDI, configure again ViSP using cmake and build again this example" << std::endl;
450 #else
451  std::cout << "You do not have OpenCV functionalities" << std::endl;
452  std::cout << "Tip:" << std::endl;
453  std::cout << "- Install OpenCV, configure again ViSP using cmake and build again this example" << std::endl;
454 #endif
455  return EXIT_SUCCESS;
456 }
457 
458 #endif
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1316
unsigned int getWidth() const
Definition: vpImage.h:239
#define vpERROR_TRACE
Definition: vpDebug.h:393
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:129
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
error that can be emited by ViSP classes.
Definition: vpException.h:71
static const vpColor green
Definition: vpColor.h:183
static void flush(const vpImage< unsigned char > &I)
VISP_EXPORT double measureTimeMs()
Definition: vpTime.cpp:88
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:69
static const vpColor red
Definition: vpColor.h:180
static bool checkFilename(const char *filename)
Definition: vpIoTools.cpp:675
static std::string createFilePath(const std::string &parent, const std::string &child)
Definition: vpIoTools.cpp:1541
static void display(const vpImage< unsigned char > &I)
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:138
const char * getMessage(void) const
Definition: vpException.cpp:90
static void displayRectangle(const vpImage< unsigned char > &I, const vpImagePoint &topLeft, unsigned int width, unsigned int height, const vpColor &color, bool fill=false, unsigned int thickness=1)
static void read(vpImage< unsigned char > &I, const std::string &filename)
Definition: vpImageIo.cpp:207
unsigned int getHeight() const
Definition: vpImage.h:178
void init(vpImage< unsigned char > &I, int winx=-1, int winy=-1, const std::string &title="")
Defines a rectangle in the plane.
Definition: vpRect.h:78
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:88
void set_ij(const double ii, const double jj)
Definition: vpImagePoint.h:189