Visual Servoing Platform  version 3.0.1
testKeyPoint-4.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
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  * Test keypoint matching and pose estimation with mostly OpenCV functions calls
32  * to detect potential memory leaks in testKeyPoint-2.cpp.
33  *
34  * Authors:
35  * Souriya Trinh
36  *
37  *****************************************************************************/
38 
39 #include <iostream>
40 
41 #include <visp3/core/vpConfig.h>
42 
43 #if defined(VISP_HAVE_OPENCV) && (VISP_HAVE_OPENCV_VERSION >= 0x020301)
44 
45 #include <opencv2/core/core.hpp>
46 #include <opencv2/features2d/features2d.hpp>
47 #include <visp3/core/vpImage.h>
48 #include <visp3/io/vpImageIo.h>
49 #include <visp3/gui/vpDisplayX.h>
50 #include <visp3/gui/vpDisplayGTK.h>
51 #include <visp3/gui/vpDisplayGDI.h>
52 #include <visp3/gui/vpDisplayOpenCV.h>
53 #include <visp3/io/vpVideoReader.h>
54 #include <visp3/core/vpIoTools.h>
55 #include <visp3/io/vpParseArgv.h>
56 #include <visp3/mbt/vpMbEdgeTracker.h>
57 #include <visp3/core/vpHomogeneousMatrix.h>
58 #include <visp3/vision/vpKeyPoint.h>
59 
60 // List of allowed command line options
61 #define GETOPTARGS "cdh"
62 
63 void usage(const char *name, const char *badparam);
64 bool getOptions(int argc, const char **argv, bool &click_allowed, bool &display);
65 
74 void usage(const char *name, const char *badparam)
75 {
76  fprintf(stdout, "\n\
77 Test keypoints matching.\n\
78 \n\
79 SYNOPSIS\n\
80  %s [-c] [-d] [-h]\n", name);
81 
82  fprintf(stdout, "\n\
83 OPTIONS: \n\
84 \n\
85  -c\n\
86  Disable the mouse click. Useful to automate the \n\
87  execution of this program without human intervention.\n\
88 \n\
89  -d \n\
90  Turn off the display.\n\
91 \n\
92  -h\n\
93  Print the help.\n");
94 
95  if (badparam)
96  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
97 }
98 
110 bool getOptions(int argc, const char **argv, bool &click_allowed, bool &display)
111 {
112  const char *optarg_;
113  int c;
114  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
115 
116  switch (c) {
117  case 'c': click_allowed = false; break;
118  case 'd': display = false; break;
119  case 'h': usage(argv[0], NULL); return false; break;
120 
121  default:
122  usage(argv[0], optarg_);
123  return false; break;
124  }
125  }
126 
127  if ((c == 1) || (c == -1)) {
128  // standalone param or error
129  usage(argv[0], NULL);
130  std::cerr << "ERROR: " << std::endl;
131  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
132  return false;
133  }
134 
135  return true;
136 }
137 
144 int main(int argc, const char ** argv) {
145  try {
146  std::string env_ipath;
147  bool opt_click_allowed = true;
148  bool opt_display = true;
149 
150  // Read the command line options
151  if (getOptions(argc, argv, opt_click_allowed, opt_display) == false) {
152  exit (-1);
153  }
154 
155  //Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH environment variable value
156  env_ipath = vpIoTools::getViSPImagesDataPath();
157 
158  if(env_ipath.empty()) {
159  std::cerr << "Please set the VISP_INPUT_IMAGE_PATH environment variable value." << std::endl;
160  return -1;
161  }
162 
163  vpImage<unsigned char> I, Imatch, Iref;
164 
165  //Set the path location of the image sequence
166  std::string dirname = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube");
167 
168  //Build the name of the image files
169  std::string filenameRef = vpIoTools::createFilePath(dirname, "image0000.pgm");
170  vpImageIo::read(I, filenameRef);
171  Iref = I;
172  std::string filenameCur = vpIoTools::createFilePath(dirname, "image%04d.pgm");
173 
174 #if defined VISP_HAVE_X11
175  vpDisplayX display, display2;
176 #elif defined VISP_HAVE_GTK
177  vpDisplayGTK display, display2;
178 #elif defined VISP_HAVE_GDI
179  vpDisplayGDI display, display2;
180 #else
181  vpDisplayOpenCV display, display2;
182 #endif
183 
184  if (opt_display) {
186  display.init(I, 0, 0, "ORB keypoints matching");
187  Imatch.resize(I.getHeight(), 2*I.getWidth());
188  Imatch.insert(I, vpImagePoint(0, 0));
190  display2.init(Imatch, 0, (int)I.getHeight()/vpDisplay::getDownScalingFactor(I) + 70, "ORB keypoints matching");
191  }
192 
193  vpCameraParameters cam;
194  vpMbEdgeTracker tracker;
195  //Load config for tracker
196  std::string tracker_config_file = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube.xml");
197 
198  bool usexml = false;
199 #ifdef VISP_HAVE_XML2
200  tracker.loadConfigFile(tracker_config_file);
201  tracker.getCameraParameters(cam);
202 
203  usexml = true;
204 #endif
205  if (! usexml) {
206  vpMe me;
207  me.setMaskSize(5);
208  me.setMaskNumber(180);
209  me.setRange(8);
210  me.setThreshold(10000);
211  me.setMu1(0.5);
212  me.setMu2(0.5);
213  me.setSampleStep(4);
214  me.setNbTotalSample(250);
215  tracker.setMovingEdge(me);
216  cam.initPersProjWithoutDistortion(547.7367575, 542.0744058, 338.7036994, 234.5083345);
217  tracker.setCameraParameters(cam);
218  tracker.setNearClippingDistance(0.01);
219  tracker.setFarClippingDistance(100.0);
221  }
222 
223  tracker.setAngleAppear(vpMath::rad(89));
224  tracker.setAngleDisappear(vpMath::rad(89));
225 
226  //Load CAO model
227  std::string cao_model_file = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube.cao");
228  tracker.loadModel(cao_model_file);
229 
230  //Initialize the pose
231  std::string init_file = vpIoTools::createFilePath(env_ipath, "ViSP-images/mbt/cube.init");
232  if (opt_display && opt_click_allowed) {
233  tracker.initClick(I, init_file);
234  }
235  else
236  {
237  vpHomogeneousMatrix cMoi(0.02044769891, 0.1101505452, 0.5078963719, 2.063603907, 1.110231561, -0.4392789872);
238  tracker.initFromPose(I, cMoi);
239  }
240 
241  //Get the init pose
243  tracker.getPose(cMo);
244 
245  //Init keypoints
246  cv::Ptr<cv::FeatureDetector> detector;
247  cv::Ptr<cv::DescriptorExtractor> extractor;
248  cv::Ptr<cv::DescriptorMatcher> matcher;
249 
250 #if (VISP_HAVE_OPENCV_VERSION >= 0x030000)
251  detector = cv::ORB::create(500, 1.2f, 1);
252  extractor = cv::ORB::create(500, 1.2f, 1);
253 #elif (VISP_HAVE_OPENCV_VERSION >= 0x020301)
254  detector = cv::FeatureDetector::create("ORB");
255  extractor = cv::DescriptorExtractor::create("ORB");
256 #endif
257  matcher = cv::DescriptorMatcher::create("BruteForce-Hamming");
258 
259 #if (VISP_HAVE_OPENCV_VERSION >= 0x020400 && VISP_HAVE_OPENCV_VERSION < 0x030000)
260  detector->set("nLevels", 1);
261 #endif
262 
263  //Detect keypoints on the current image
264  std::vector<cv::KeyPoint> trainKeyPoints;
265  cv::Mat matImg;
266  vpImageConvert::convert(I, matImg);
267  detector->detect(matImg, trainKeyPoints);
268 
269 
270  //Keep only keypoints on the cube
271  std::vector<vpPolygon> polygons;
272  std::vector<std::vector<vpPoint> > roisPt;
273  std::pair<std::vector<vpPolygon>, std::vector<std::vector<vpPoint> > > pair = tracker.getPolygonFaces(false);
274  polygons = pair.first;
275  roisPt = pair.second;
276 
277  //Compute the 3D coordinates
278  std::vector<cv::Point3f> points3f;
279  vpKeyPoint::compute3DForPointsInPolygons(cMo, cam, trainKeyPoints, polygons, roisPt, points3f);
280 
281 
282  //Extract descriptors
283  cv::Mat trainDescriptors;
284  extractor->compute(matImg, trainKeyPoints, trainDescriptors);
285 
286  if(trainKeyPoints.size() != (size_t) trainDescriptors.rows || trainKeyPoints.size() != points3f.size()) {
287  std::cerr << "Problem with training data size !" << std::endl;
288  return -1;
289  }
290 
291 
292  //Init reader for getting the input image sequence
293  vpVideoReader g;
294  g.setFileName(filenameCur);
295  g.open(I);
296  g.acquire(I);
297 
298  bool opt_click = false;
300  while((opt_display && !g.end()) || (!opt_display && g.getFrameIndex() < 30)) {
301  g.acquire(I);
302 
303  vpImageConvert::convert(I, matImg);
304  std::vector<cv::KeyPoint> queryKeyPoints;
305  detector->detect(matImg, queryKeyPoints);
306 
307  cv::Mat queryDescriptors;
308  extractor->compute(matImg, queryKeyPoints, queryDescriptors);
309 
310  std::vector<std::vector<cv::DMatch> > knn_matches;
311  std::vector<cv::DMatch> matches;
312  matcher->knnMatch(queryDescriptors, trainDescriptors, knn_matches, 2);
313  for(std::vector<std::vector<cv::DMatch> >::const_iterator it = knn_matches.begin(); it != knn_matches.end(); ++it) {
314  if(it->size() > 1) {
315  double ratio = (*it)[0].distance / (*it)[1].distance;
316  if(ratio < 0.85) {
317  matches.push_back((*it)[0]);
318  }
319  }
320  }
321 
322  vpPose estimated_pose;
323  for(std::vector<cv::DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it) {
324  vpPoint pt(points3f[(size_t)(it->trainIdx)].x,
325  points3f[(size_t)(it->trainIdx)].y,
326  points3f[(size_t)(it->trainIdx)].z);
327 
328  double x = 0.0, y = 0.0;
329  vpPixelMeterConversion::convertPoint(cam, queryKeyPoints[(size_t)(it->queryIdx)].pt.x, queryKeyPoints[(size_t)(it->queryIdx)].pt.y, x, y);
330  pt.set_x(x);
331  pt.set_y(y);
332 
333  estimated_pose.addPoint(pt);
334  }
335 
336  bool is_pose_estimated = false;
337  if(estimated_pose.npt >= 4) {
338  try {
339  unsigned int nb_inliers = (unsigned int) (0.6 * estimated_pose.npt);
340  estimated_pose.setRansacNbInliersToReachConsensus(nb_inliers);
341  estimated_pose.setRansacThreshold(0.01);
342  estimated_pose.setRansacMaxTrials(500);
343  estimated_pose.computePose(vpPose::RANSAC, cMo);
344  is_pose_estimated = true;
345  } catch(...) {
346  is_pose_estimated = false;
347  }
348  }
349 
350  if(opt_display) {
352 
353  Imatch.insert(I, vpImagePoint(0, Iref.getWidth()));
354  vpDisplay::display(Imatch);
355  for(std::vector<cv::DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it) {
356  vpImagePoint leftPt(trainKeyPoints[(size_t) it->trainIdx].pt.y, trainKeyPoints[(size_t) it->trainIdx].pt.x);
357  vpImagePoint rightPt(queryKeyPoints[(size_t) it->queryIdx].pt.y, queryKeyPoints[(size_t) it->queryIdx].pt.x
358  + Iref.getWidth());
359  vpDisplay::displayLine(Imatch, leftPt, rightPt, vpColor::green);
360  }
361 
362  if(is_pose_estimated) {
363  tracker.setPose(I, cMo);
364  tracker.display(I, cMo, cam, vpColor::red);
365  vpDisplay::displayFrame(I, cMo, cam, 0.05, vpColor::none);
366  }
367 
368  vpDisplay::flush(Imatch);
369  vpDisplay::flush(I);
370  }
371 
372  //Click requested to process next image
373  if (opt_click_allowed && opt_display) {
374  if(opt_click) {
375  vpDisplay::getClick(I, button, true);
376  if(button == vpMouseButton::button3) {
377  opt_click = false;
378  }
379  } else {
380  //Use right click to enable/disable step by step tracking
381  if(vpDisplay::getClick(I, button, false)) {
382  if (button == vpMouseButton::button3) {
383  opt_click = true;
384  }
385  else if(button == vpMouseButton::button1) {
386  break;
387  }
388  }
389  }
390  }
391  }
392 
393  } catch(vpException &e) {
394  std::cerr << e.what() << std::endl;
395  return -1;
396  }
397 
398  std::cout << "testKeyPoint-4 is ok !" << std::endl;
399  return 0;
400 }
401 #else
402 int main() {
403  std::cerr << "You need OpenCV library." << std::endl;
404 
405  return 0;
406 }
407 
408 #endif
virtual unsigned int getClipping() const
Definition: vpMbTracker.h:208
void setMovingEdge(const vpMe &me)
virtual void getPose(vpHomogeneousMatrix &cMo_) const
Definition: vpMbTracker.h:333
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1157
virtual void setAngleDisappear(const double &a)
Definition: vpMbTracker.h:382
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
Implementation of an homogeneous matrix and operations on such kind of matrices.
void setMaskNumber(const unsigned int &a)
Definition: vpMe.cpp:488
virtual void setDownScalingFactor(unsigned int scale)
Definition: vpDisplay.cpp:248
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:128
void setSampleStep(const double &s)
Definition: vpMe.h:263
void setNbTotalSample(const int &nb)
Definition: vpMe.h:240
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:153
Class that enables to manipulate easily a video file or a sequence of images. As it inherits from the...
static const vpColor none
Definition: vpColor.h:175
error that can be emited by ViSP classes.
Definition: vpException.h:73
void setRansacThreshold(const double &t)
Definition: vpPose.h:227
void init(vpImage< unsigned char > &I, int winx=-1, int winy=-1, const std::string &title="")
Definition: vpMe.h:59
static void convertPoint(const vpCameraParameters &cam, const double &u, const double &v, double &x, double &y)
Point coordinates conversion from pixel coordinates to normalized coordinates in meter...
Make the complete tracking of an object by using its CAD model.
virtual void setPose(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cdMo)
virtual void setCameraParameters(const vpCameraParameters &camera)
virtual void initFromPose(const vpImage< unsigned char > &I, const std::string &initFile)
void loadConfigFile(const std::string &configFile)
static const vpColor green
Definition: vpColor.h:166
static void flush(const vpImage< unsigned char > &I)
void setMu1(const double &mu_1)
Definition: vpMe.h:226
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:76
static const vpColor red
Definition: vpColor.h:163
Class that defines what is a point.
Definition: vpPoint.h:59
void initPersProjWithoutDistortion(const double px, const double py, const double u0, const double v0)
virtual void setNearClippingDistance(const double &dist)
void open(vpImage< vpRGBa > &I)
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=NULL)
Definition: vpKeyPoint.cpp:765
void setMaskSize(const unsigned int &a)
Definition: vpMe.cpp:496
static std::string createFilePath(const std::string &parent, const std::string child)
Definition: vpIoTools.cpp:1366
static void display(const vpImage< unsigned char > &I)
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
Class used for pose computation from N points (pose from point only). Some of the algorithms implemen...
Definition: vpPose.h:76
Generic class defining intrinsic camera parameters.
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:138
void acquire(vpImage< vpRGBa > &I)
bool computePose(vpPoseMethodType method, vpHomogeneousMatrix &cMo, bool(*func)(vpHomogeneousMatrix *)=NULL)
Definition: vpPose.cpp:372
void resize(const unsigned int h, const unsigned int w)
resize the image : Image initialization
Definition: vpImage.h:903
virtual void setFarClippingDistance(const double &dist)
void setFileName(const char *filename)
virtual void setAngleAppear(const double &a)
Definition: vpMbTracker.h:371
virtual void initClick(const vpImage< unsigned char > &I, const std::string &initFile, const bool displayHelp=false)
const char * what() const
static double rad(double deg)
Definition: vpMath.h:104
unsigned int npt
Number of point used in pose computation.
Definition: vpPose.h:100
void setRansacMaxTrials(const int &rM)
Definition: vpPose.h:235
void setRansacNbInliersToReachConsensus(const unsigned int &nbC)
Definition: vpPose.h:226
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))
void setMu2(const double &mu_2)
Definition: vpMe.h:233
long getFrameIndex() const
virtual void loadModel(const char *modelFile, const bool verbose=false)
unsigned int getHeight() const
Definition: vpImage.h:175
virtual void getCameraParameters(vpCameraParameters &camera) const
Definition: vpMbTracker.h:201
static void read(vpImage< unsigned char > &I, const std::string &filename)
Definition: vpImageIo.cpp:205
unsigned int getDownScalingFactor()
Definition: vpDisplay.h:214
void insert(const vpImage< Type > &src, const vpImagePoint topLeft)
Definition: vpImage.h:1226
void setThreshold(const double &t)
Definition: vpMe.h:284
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)
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:88
static void displayLine(const vpImage< unsigned char > &I, const vpImagePoint &ip1, const vpImagePoint &ip2, const vpColor &color, unsigned int thickness=1)
void setRange(const unsigned int &r)
Definition: vpMe.h:256
virtual void setClipping(const unsigned int &flags)
void addPoint(const vpPoint &P)
Definition: vpPose.cpp:145
unsigned int getWidth() const
Definition: vpImage.h:226
virtual std::pair< std::vector< vpPolygon >, std::vector< std::vector< vpPoint > > > getPolygonFaces(const bool orderPolygons=true, const bool useVisibility=true, const bool clipPolygon=false)