Visual Servoing Platform  version 3.6.1 under development (2024-12-17)
testKeyPoint-2.cpp
1 /*
2  * ViSP, open source Visual Servoing Platform software.
3  * Copyright (C) 2005 - 2024 by Inria. All rights reserved.
4  *
5  * This software is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
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 https://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  * Test keypoint matching and pose estimation.
32  */
33 
40 #include <iostream>
41 
42 #include <visp3/core/vpConfig.h>
43 
44 #if defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_FEATURES2D) && defined(HAVE_OPENCV_VIDEO)
45 
46 #include <visp3/core/vpImage.h>
47 #include <visp3/core/vpIoTools.h>
48 #include <visp3/gui/vpDisplayGDI.h>
49 #include <visp3/gui/vpDisplayGTK.h>
50 #include <visp3/gui/vpDisplayOpenCV.h>
51 #include <visp3/gui/vpDisplayX.h>
52 #include <visp3/io/vpImageIo.h>
53 #include <visp3/io/vpParseArgv.h>
54 #include <visp3/io/vpVideoReader.h>
55 #include <visp3/mbt/vpMbEdgeTracker.h>
56 #include <visp3/vision/vpKeyPoint.h>
57 
58 // List of allowed command line options
59 #define GETOPTARGS "cdph"
60 
61 #ifdef ENABLE_VISP_NAMESPACE
62 using namespace VISP_NAMESPACE_NAME;
63 #endif
64 
65 void usage(const char *name, const char *badparam);
66 bool getOptions(int argc, const char **argv, bool &click_allowed, bool &display);
67 
76 void usage(const char *name, const char *badparam)
77 {
78  fprintf(stdout, "\n\
79 Test keypoints matching.\n\
80 \n\
81 SYNOPSIS\n\
82  %s [-c] [-d] [-p] [-h]\n",
83  name);
84 
85  fprintf(stdout, "\n\
86 OPTIONS: \n\
87 \n\
88  -c\n\
89  Disable the mouse click. Useful to automate the \n\
90  execution of this program without human intervention.\n\
91 \n\
92  -d \n\
93  Turn off the display.\n\
94 \n\
95  -p \n\
96  Use parallel RANSAC.\n\
97 \n\
98  -h\n\
99  Print the help.\n");
100 
101  if (badparam)
102  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
103 }
104 
116 bool getOptions(int argc, const char **argv, bool &click_allowed, bool &display, bool &use_parallel_ransac)
117 {
118  const char *optarg_;
119  int c;
120  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
121 
122  switch (c) {
123  case 'c':
124  click_allowed = false;
125  break;
126  case 'd':
127  display = false;
128  break;
129  case 'p':
130  use_parallel_ransac = true;
131  break;
132  case 'h':
133  usage(argv[0], nullptr);
134  return false;
135  break;
136 
137  default:
138  usage(argv[0], optarg_);
139  return false;
140  break;
141  }
142  }
143 
144  if ((c == 1) || (c == -1)) {
145  // standalone param or error
146  usage(argv[0], nullptr);
147  std::cerr << "ERROR: " << std::endl;
148  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
149  return false;
150  }
151 
152  return true;
153 }
154 
155 template <typename Type>
156 void run_test(const std::string &env_ipath, bool opt_click_allowed, bool opt_display, bool use_parallel_ransac,
157  vpImage<Type> &I, vpImage<Type> &IMatching)
158 {
159 #if VISP_HAVE_DATASET_VERSION >= 0x030600
160  std::string ext("png");
161 #else
162  std::string ext("pgm");
163 #endif
164  // Set the path location of the image sequence
165  std::string dirname = vpIoTools::createFilePath(env_ipath, "mbt/cube");
166 
167  // Build the name of the image files
168  std::string filenameRef = vpIoTools::createFilePath(dirname, "image0000." + ext);
169  vpImageIo::read(I, filenameRef);
170  std::string filenameCur = vpIoTools::createFilePath(dirname, "image%04d." + ext);
171 
172 #if defined(VISP_HAVE_X11)
173  vpDisplayX display;
174 #elif defined(VISP_HAVE_GTK)
175  vpDisplayGTK display;
176 #elif defined(VISP_HAVE_GDI)
177  vpDisplayGDI display;
178 #elif defined(HAVE_OPENCV_HIGHGUI)
179  vpDisplayOpenCV display;
180 #endif
181 
182  if (opt_display) {
183  display.setDownScalingFactor(vpDisplay::SCALE_AUTO);
184  display.init(I, 0, 0, "ORB keypoints matching and pose estimation");
185  }
186 
187  vpCameraParameters cam;
188  vpMbEdgeTracker tracker;
189  // Load config for tracker
190  std::string tracker_config_file = vpIoTools::createFilePath(env_ipath, "mbt/cube.xml");
191 
192 #if defined(VISP_HAVE_PUGIXML)
193  tracker.loadConfigFile(tracker_config_file);
194  tracker.getCameraParameters(cam);
195 #else
196  // Corresponding parameters manually set to have an example code
197  vpMe me;
198  me.setMaskSize(5);
199  me.setMaskNumber(180);
200  me.setRange(8);
202  me.setThreshold(20);
203  me.setMu1(0.5);
204  me.setMu2(0.5);
205  me.setSampleStep(4);
206  me.setNbTotalSample(250);
207  tracker.setMovingEdge(me);
208  cam.initPersProjWithoutDistortion(547.7367575, 542.0744058, 338.7036994, 234.5083345);
209  tracker.setCameraParameters(cam);
210  tracker.setNearClippingDistance(0.01);
211  tracker.setFarClippingDistance(100.0);
213 #endif
214 
215  tracker.setAngleAppear(vpMath::rad(89));
216  tracker.setAngleDisappear(vpMath::rad(89));
217 
218  // Load CAO model
219  std::string cao_model_file = vpIoTools::createFilePath(env_ipath, "mbt/cube.cao");
220  tracker.loadModel(cao_model_file);
221 
222  // Initialize the pose
223  std::string init_file = vpIoTools::createFilePath(env_ipath, "mbt/cube.init");
224  if (opt_display && opt_click_allowed) {
225  tracker.initClick(I, init_file);
226  }
227  else {
228  vpHomogeneousMatrix cMoi(0.02044769891, 0.1101505452, 0.5078963719, 2.063603907, 1.110231561, -0.4392789872);
229  tracker.initFromPose(I, cMoi);
230  }
231 
232  // Get the init pose
234  tracker.getPose(cMo);
235 
236  // Init keypoints
237  vpKeyPoint keypoints("ORB", "ORB", "BruteForce-Hamming");
238  keypoints.setRansacParallel(use_parallel_ransac);
239 #if (VISP_HAVE_OPENCV_VERSION >= 0x020400)
240  // Bug when using LSH index with FLANN and OpenCV 2.3.1.
241  // see http://code.opencv.org/issues/1741 (Bug #1741)
242  keypoints.setMatcher("FlannBased");
243 #if (VISP_HAVE_OPENCV_VERSION < 0x030000)
244  keypoints.setDetectorParameter("ORB", "nLevels", 1);
245 #else
246  cv::Ptr<cv::ORB> orb_detector = keypoints.getDetector("ORB").dynamicCast<cv::ORB>();
247  if (orb_detector) {
248  orb_detector->setNLevels(1);
249  }
250 #endif
251 #endif
252 
253  // Detect keypoints on the current image
254  std::vector<cv::KeyPoint> trainKeyPoints;
255  double elapsedTime;
256  keypoints.detect(I, trainKeyPoints, elapsedTime);
257 
258  // Keep only keypoints on the cube
259  std::vector<vpPolygon> polygons;
260  std::vector<std::vector<vpPoint> > roisPt;
261  std::pair<std::vector<vpPolygon>, std::vector<std::vector<vpPoint> > > pair =
262  tracker.getPolygonFaces(true); // To detect an issue with CI
263  polygons = pair.first;
264  roisPt = pair.second;
265 
266  // Compute the 3D coordinates
267  std::vector<cv::Point3f> points3f;
268  vpKeyPoint::compute3DForPointsInPolygons(cMo, cam, trainKeyPoints, polygons, roisPt, points3f);
269 
270  // Build the reference keypoints
271  keypoints.buildReference(I, trainKeyPoints, points3f, false, 1);
272 
273  // Read image 150
274  filenameRef = vpIoTools::createFilePath(dirname, "image0150." + ext);
275  vpImageIo::read(I, filenameRef);
276 
277  // Init pose at image 150
278  cMo.buildFrom(0.02651282185, -0.03713587374, 0.6873765919, 2.314744454, 0.3492296488, -0.1226054828);
279  tracker.initFromPose(I, cMo);
280 
281  // Detect keypoints on the image 150
282  keypoints.detect(I, trainKeyPoints, elapsedTime);
283 
284  // Keep only keypoints on the cube
285  pair = tracker.getPolygonFaces(true, true,
286  true); // To detect an issue with CI
287  polygons = pair.first;
288  roisPt = pair.second;
289 
290  // Compute the 3D coordinates
291  vpKeyPoint::compute3DForPointsInPolygons(cMo, cam, trainKeyPoints, polygons, roisPt, points3f);
292 
293  // Build the reference keypoints
294  keypoints.buildReference(I, trainKeyPoints, points3f, true, 2);
295 
296  // Read image 200
297  filenameRef = vpIoTools::createFilePath(dirname, "image0200." + ext);
298  vpImageIo::read(I, filenameRef);
299 
300  // Init pose at image 200
301  cMo.buildFrom(0.02965448956, -0.07283091786, 0.7253526051, 2.300529617, -0.4286674806, 0.1788761025);
302  tracker.initFromPose(I, cMo);
303 
304  // Detect keypoints on the image 200
305  keypoints.detect(I, trainKeyPoints, elapsedTime);
306 
307  // Keep only keypoints on the cube
308  pair = tracker.getPolygonFaces(false); // To detect an issue with CI
309  polygons = pair.first;
310  roisPt = pair.second;
311 
312  // Compute the 3D coordinates
313  vpKeyPoint::compute3DForPointsInPolygons(cMo, cam, trainKeyPoints, polygons, roisPt, points3f);
314 
315  // Build the reference keypoints
316  keypoints.buildReference(I, trainKeyPoints, points3f, true, 3);
317 
318  // Init reader for getting the input image sequence
319  vpVideoReader g;
320  g.setFileName(filenameCur);
321  g.open(I);
322  g.acquire(I);
323 
324 #if defined(VISP_HAVE_X11)
325  vpDisplayX display2;
326 #elif defined(VISP_HAVE_GTK)
327  vpDisplayGTK display2;
328 #elif defined(VISP_HAVE_GDI)
329  vpDisplayGDI display2;
330 #elif defined(HAVE_OPENCV_HIGHGUI)
331  vpDisplayOpenCV display2;
332 #endif
333 
334  keypoints.createImageMatching(I, IMatching);
335 
336  if (opt_display) {
338  display2.init(IMatching, 0, (int)I.getHeight() / vpDisplay::getDownScalingFactor(I) + 80, "IMatching");
339  }
340 
341  bool opt_click = false;
342  double error;
344  std::vector<double> times_vec;
345  while ((opt_display && !g.end()) || (!opt_display && g.getFrameIndex() < 30)) {
346  g.acquire(I);
347 
348  if (opt_display) {
350 
351  // Display image matching
352  keypoints.insertImageMatching(I, IMatching);
353 
354  vpDisplay::display(IMatching);
355  }
356 
357  // Match keypoints and estimate the pose
358  if (keypoints.matchPoint(I, cam, cMo, error, elapsedTime)) {
359  times_vec.push_back(elapsedTime);
360 
361  tracker.setCameraParameters(cam);
362  tracker.setPose(I, cMo);
363 
364  if (opt_display) {
365  tracker.display(I, cMo, cam, vpColor::red, 2);
366  vpDisplay::displayFrame(I, cMo, cam, 0.025, vpColor::none, 3);
367 
368  std::vector<vpImagePoint> ransacInliers = keypoints.getRansacInliers();
369  std::vector<vpImagePoint> ransacOutliers = keypoints.getRansacOutliers();
370 
371  for (std::vector<vpImagePoint>::const_iterator it = ransacInliers.begin(); it != ransacInliers.end(); ++it) {
373  vpImagePoint imPt(*it);
374  imPt.set_u(imPt.get_u() + I.getWidth());
375  imPt.set_v(imPt.get_v() + I.getHeight());
376  vpDisplay::displayCircle(IMatching, imPt, 4, vpColor::green);
377  }
378 
379  for (std::vector<vpImagePoint>::const_iterator it = ransacOutliers.begin(); it != ransacOutliers.end(); ++it) {
381  vpImagePoint imPt(*it);
382  imPt.set_u(imPt.get_u() + I.getWidth());
383  imPt.set_v(imPt.get_v() + I.getHeight());
384  vpDisplay::displayCircle(IMatching, imPt, 4, vpColor::red);
385  }
386 
387  keypoints.displayMatching(I, IMatching);
388 
389  // Display model in the correct sub-image in IMatching
390  vpCameraParameters cam2;
391  cam2.initPersProjWithoutDistortion(cam.get_px(), cam.get_py(), cam.get_u0() + I.getWidth(),
392  cam.get_v0() + I.getHeight());
393  tracker.setCameraParameters(cam2);
394  tracker.setPose(IMatching, cMo);
395  tracker.display(IMatching, cMo, cam2, vpColor::red, 2);
396  vpDisplay::displayFrame(IMatching, cMo, cam2, 0.025, vpColor::none, 3);
397  }
398  }
399 
400  if (opt_display) {
401  vpDisplay::flush(I);
402  vpDisplay::flush(IMatching);
403  }
404 
405  if (opt_click_allowed && opt_display) {
406  // Click requested to process next image
407  if (opt_click) {
408  vpDisplay::getClick(I, button, true);
409  if (button == vpMouseButton::button3) {
410  opt_click = false;
411  }
412  }
413  else {
414  // Use right click to enable/disable step by step tracking
415  if (vpDisplay::getClick(I, button, false)) {
416  if (button == vpMouseButton::button3) {
417  opt_click = true;
418  }
419  else if (button == vpMouseButton::button1) {
420  break;
421  }
422  }
423  }
424  }
425  }
426 
427  if (!times_vec.empty()) {
428  std::cout << "Computation time, Mean: " << vpMath::getMean(times_vec)
429  << " ms ; Median: " << vpMath::getMedian(times_vec) << " ms ; Std: " << vpMath::getStdev(times_vec)
430  << std::endl;
431  }
432 }
433 
434 int main(int argc, const char **argv)
435 {
436  try {
437  std::string env_ipath;
438  bool opt_click_allowed = true;
439  bool opt_display = true;
440  bool use_parallel_ransac = false;
441 
442  // Read the command line options
443  if (getOptions(argc, argv, opt_click_allowed, opt_display, use_parallel_ransac) == false) {
444  return EXIT_FAILURE;
445  }
446 
447  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
448  // environment variable value
449  env_ipath = vpIoTools::getViSPImagesDataPath();
450 
451  if (env_ipath.empty()) {
452  std::cerr << "Please set the VISP_INPUT_IMAGE_PATH environment "
453  "variable value."
454  << std::endl;
455  return EXIT_FAILURE;
456  }
457 
458  {
459  vpImage<unsigned char> I, IMatching;
460 
461  std::cout << "-- Test on gray level images" << std::endl;
462 
463  run_test(env_ipath, opt_click_allowed, opt_display, use_parallel_ransac, I, IMatching);
464  }
465  {
466  vpImage<vpRGBa> I, IMatching;
467 
468  std::cout << "-- Test on color images" << std::endl;
469 
470  run_test(env_ipath, opt_click_allowed, opt_display, use_parallel_ransac, I, IMatching);
471  }
472 
473  }
474  catch (const vpException &e) {
475  std::cerr << e.what() << std::endl;
476  return EXIT_FAILURE;
477  }
478 
479  std::cout << "testKeyPoint-2 is ok !" << std::endl;
480  return EXIT_SUCCESS;
481 }
482 #else
483 int main()
484 {
485  std::cerr << "You need OpenCV library." << std::endl;
486 
487  return EXIT_SUCCESS;
488 }
489 
490 #endif
Generic class defining intrinsic camera parameters.
void initPersProjWithoutDistortion(double px, double py, double u0, double v0)
static const vpColor red
Definition: vpColor.h:217
static const vpColor none
Definition: vpColor.h:229
static const vpColor green
Definition: vpColor.h:220
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 displayCircle(const vpImage< unsigned char > &I, const vpImageCircle &circle, const vpColor &color, bool fill=false, unsigned int thickness=1)
virtual void setDownScalingFactor(unsigned int scale)
Definition: vpDisplay.cpp:233
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:184
unsigned int getDownScalingFactor()
Definition: vpDisplay.h:221
error that can be emitted by ViSP classes.
Definition: vpException.h:60
const char * what() const
Definition: vpException.cpp:71
Implementation of an homogeneous matrix and operations on such kind of matrices.
vpHomogeneousMatrix & buildFrom(const vpTranslationVector &t, const vpRotationMatrix &R)
static void read(vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Definition: vpImageIo.cpp:147
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:82
Definition of the vpImage class member functions.
Definition: vpImage.h:131
unsigned int getWidth() const
Definition: vpImage.h:242
unsigned int getHeight() const
Definition: vpImage.h:181
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1053
static std::string createFilePath(const std::string &parent, const std::string &child)
Definition: vpIoTools.cpp:1427
Class that allows keypoints detection (and descriptors extraction) and matching thanks to OpenCV libr...
Definition: vpKeyPoint.h:221
static void compute3DForPointsInPolygons(const vpHomogeneousMatrix &cMo, const vpCameraParameters &cam, std::vector< cv::KeyPoint > &candidates, const std::vector< vpPolygon > &polygons, const std::vector< std::vector< vpPoint > > &roisPt, std::vector< cv::Point3f > &points, cv::Mat *descriptors=nullptr)
Definition: vpKeyPoint.cpp:465
static double rad(double deg)
Definition: vpMath.h:129
static double getMedian(const std::vector< double > &v)
Definition: vpMath.cpp:322
static double getStdev(const std::vector< double > &v, bool useBesselCorrection=false)
Definition: vpMath.cpp:353
static double getMean(const std::vector< double > &v)
Definition: vpMath.cpp:302
Make the complete tracking of an object by using its CAD model.
virtual void setNearClippingDistance(const double &dist) VP_OVERRIDE
virtual void display(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cMo, const vpCameraParameters &cam, const vpColor &col, unsigned int thickness=1, bool displayFullModel=false) VP_OVERRIDE
virtual void setFarClippingDistance(const double &dist) VP_OVERRIDE
virtual void setClipping(const unsigned int &flags) VP_OVERRIDE
void setMovingEdge(const vpMe &me)
virtual void setCameraParameters(const vpCameraParameters &cam) VP_OVERRIDE
virtual void setPose(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cdMo) VP_OVERRIDE
virtual void loadConfigFile(const std::string &configFile, bool verbose=true) VP_OVERRIDE
virtual void getCameraParameters(vpCameraParameters &cam) const
Definition: vpMbTracker.h:250
virtual void getPose(vpHomogeneousMatrix &cMo) const
Definition: vpMbTracker.h:416
virtual void setAngleDisappear(const double &a)
Definition: vpMbTracker.h:483
virtual void initFromPose(const vpImage< unsigned char > &I, const std::string &initFile)
virtual void loadModel(const std::string &modelFile, bool verbose=false, const vpHomogeneousMatrix &T=vpHomogeneousMatrix())
virtual void setAngleAppear(const double &a)
Definition: vpMbTracker.h:472
virtual std::pair< std::vector< vpPolygon >, std::vector< std::vector< vpPoint > > > getPolygonFaces(bool orderPolygons=true, bool useVisibility=true, bool clipPolygon=false)
virtual unsigned int getClipping() const
Definition: vpMbTracker.h:258
Definition: vpMe.h:134
void setMu1(const double &mu_1)
Definition: vpMe.h:385
void setRange(const unsigned int &range)
Definition: vpMe.h:415
void setLikelihoodThresholdType(const vpLikelihoodThresholdType likelihood_threshold_type)
Definition: vpMe.h:505
void setNbTotalSample(const int &ntotal_sample)
Definition: vpMe.h:399
void setMaskNumber(const unsigned int &mask_number)
Definition: vpMe.cpp:552
void setThreshold(const double &threshold)
Definition: vpMe.h:466
void setSampleStep(const double &sample_step)
Definition: vpMe.h:422
void setMaskSize(const unsigned int &mask_size)
Definition: vpMe.cpp:560
void setMu2(const double &mu_2)
Definition: vpMe.h:392
@ NORMALIZED_THRESHOLD
Definition: vpMe.h:145
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:70
Class that enables to manipulate easily a video file or a sequence of images. As it inherits from the...
void acquire(vpImage< vpRGBa > &I)
void open(vpImage< vpRGBa > &I)
void setFileName(const std::string &filename)
long getFrameIndex() const