Visual Servoing Platform  version 3.6.1 under development (2024-10-15)
testImageTemplateMatching.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 vpImageTools::templateMatching().
32  */
33 
40 #include <visp3/core/vpImage.h>
41 #include <visp3/core/vpImageTools.h>
42 #include <visp3/core/vpIoTools.h>
43 #include <visp3/gui/vpDisplayGDI.h>
44 #include <visp3/gui/vpDisplayOpenCV.h>
45 #include <visp3/gui/vpDisplayX.h>
46 #include <visp3/io/vpParseArgv.h>
47 #include <visp3/io/vpVideoReader.h>
48 
49 // List of allowed command line options
50 #define GETOPTARGS "cdi:th"
51 
52 #ifdef ENABLE_VISP_NAMESPACE
53 using namespace VISP_NAMESPACE_NAME;
54 #endif
55 
56 namespace
57 {
58 void usage(const char *name, const char *badparam, std::string ipath)
59 {
60  fprintf(stdout, "\n\
61  Test vpImageTools::templateMatching().\n\
62  \n\
63  SYNOPSIS\n\
64  %s [-i <VISP_IMAGES directory>] \n\
65  [-c] [-t] \n\
66  [-h]\n \
67  ",
68  name);
69 
70  fprintf(stdout, "\n\
71  OPTIONS: Default\n\
72  -i <VISP_IMAGES directory> %s\n\
73  Set VISP_IMAGES input path.\n\
74  Setting the VISP_INPUT_IMAGE_PATH environment\n\
75  variable produces the same behaviour than using\n\
76  this option.\n\
77  \n\
78  -c \n\
79  Mouse click.\n\
80  -t \n\
81  Perform template matching on cube sequence.\n\
82  -h\n\
83  Print the help.\n\n",
84  ipath.c_str());
85 
86  if (badparam)
87  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
88 }
89 
90 bool getOptions(int argc, const char **argv, std::string &ipath, bool &click, bool &doTemplateMatching)
91 {
92  const char *optarg_;
93  int c;
94  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
95 
96  switch (c) {
97  case 'i':
98  ipath = optarg_;
99  break;
100  case 'h':
101  usage(argv[0], nullptr, ipath);
102  return false;
103  break;
104  case 't':
105  doTemplateMatching = true;
106  break;
107 
108  case 'c':
109  click = true;
110  break;
111  case 'd':
112  break;
113 
114  default:
115  usage(argv[0], optarg_, ipath);
116  return false;
117  break;
118  }
119  }
120 
121  if ((c == 1) || (c == -1)) {
122  // standalone param or error
123  usage(argv[0], nullptr, ipath);
124  std::cerr << "ERROR: " << std::endl;
125  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
126  return false;
127  }
128 
129  return true;
130 }
131 } // namespace
132 
133 int main(int argc, const char **argv)
134 {
135 #if defined(VISP_HAVE_OPENCV) && (VISP_HAVE_OPENCV_VERSION >= 0x030000) && defined(HAVE_OPENCV_IMGPROC)
136  {
137  const int h = 5, w = 5;
138  vpImage<unsigned char> I(h, w);
139  I[0][0] = 1;
140  I[0][1] = 2;
141  I[0][2] = 2;
142  I[0][3] = 4;
143  I[0][4] = 1;
144  I[1][0] = 3;
145  I[1][1] = 4;
146  I[1][2] = 1;
147  I[1][3] = 5;
148  I[1][4] = 2;
149  I[2][0] = 2;
150  I[2][1] = 3;
151  I[2][2] = 3;
152  I[2][3] = 2;
153  I[2][4] = 4;
154  I[3][0] = 4;
155  I[3][1] = 1;
156  I[3][2] = 5;
157  I[3][3] = 4;
158  I[3][4] = 6;
159  I[4][0] = 6;
160  I[4][1] = 3;
161  I[4][2] = 2;
162  I[4][3] = 1;
163  I[4][4] = 3;
164 
165  vpImage<double> II, IIsq;
166  vpImageTools::integralImage(I, II, IIsq);
167  std::cout << "I:\n" << I << std::endl;
168  std::cout << "II:\n" << II << std::endl;
169  std::cout << "IIsq:\n" << IIsq << std::endl;
170 
171  cv::Mat mat(h, w, CV_64F);
172  for (int i = 0; i < h; i++) {
173  for (int j = 0; j < w; j++) {
174  mat.at<double>(i, j) = I[i][j];
175  }
176  }
177 
178  cv::Mat sum, sqsum;
179  cv::integral(mat, sum, sqsum);
180  std::cout << "mat:\n" << mat << std::endl;
181  std::cout << "sum:\n" << sum << std::endl;
182  std::cout << "sqsum:\n" << sqsum << std::endl;
183 
184  for (int i = 0; i < h; i++) {
185  for (int j = 0; j < w; j++) {
186  if (!vpMath::equal(II[i][j], sum.at<double>(i, j), std::numeric_limits<double>::epsilon())) {
187  std::cerr << "Error vpImageTools::integralImage(II), reference: " << std::setprecision(17)
188  << sum.at<double>(i, j) << " ; compute: " << II[i][j] << std::endl;
189  return EXIT_FAILURE;
190  }
191 
192  if (!vpMath::equal(IIsq[i][j], sqsum.at<double>(i, j), std::numeric_limits<double>::epsilon())) {
193  std::cerr << "Error vpImageTools::integralImage(IIsq), reference: " << std::setprecision(17)
194  << sqsum.at<double>(i, j) << " ; compute: " << IIsq[i][j] << std::endl;
195  return EXIT_FAILURE;
196  }
197  }
198  }
199  }
200 #endif
201 
202 try {
203  std::string env_ipath;
204  std::string opt_ipath;
205  std::string ipath;
206  std::string filename;
207  bool click = false;
208  bool doTemplateMatching = false;
209 
210 #if VISP_HAVE_DATASET_VERSION >= 0x030600
211  std::string ext("png");
212 #else
213  std::string ext("pgm");
214 #endif
215 
216  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
217  // environment variable value
218  env_ipath = vpIoTools::getViSPImagesDataPath();
219 
220  // Set the default input path
221  if (!env_ipath.empty()) {
222  ipath = env_ipath;
223  }
224 
225  // Read the command line options
226  if (!getOptions(argc, argv, opt_ipath, click, doTemplateMatching)) {
227  exit(EXIT_FAILURE);
228  }
229 
230  // Get the option values
231  if (!opt_ipath.empty()) {
232  ipath = opt_ipath;
233  }
234 
235  // Compare ipath and env_ipath. If they differ, we take into account
236  // the input path coming from the command line option
237  if (!opt_ipath.empty() && !env_ipath.empty()) {
238  if (ipath != env_ipath) {
239  std::cout << std::endl << "WARNING: " << std::endl;
240  std::cout << " Since -i <visp image path=" << ipath << "> "
241  << " is different from VISP_IMAGE_PATH=" << env_ipath << std::endl
242  << " we skip the environment variable." << std::endl;
243  }
244  }
245 
246  // Test if an input path is set
247  if (opt_ipath.empty() && env_ipath.empty()) {
248  usage(argv[0], nullptr, ipath);
249  std::cerr << std::endl << "ERROR:" << std::endl;
250  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
251  << " environment variable to specify the location of the " << std::endl
252  << " image path where test images are located." << std::endl
253  << std::endl;
254  exit(EXIT_FAILURE);
255  }
256 
257  //
258  // Here starts really the test
259  //
260 
261  // Load cube sequence
262  filename = vpIoTools::createFilePath(ipath, "mbt/cube/image%04d." + ext);
263 
264  vpVideoReader reader;
265  reader.setFileName(filename);
266  vpImage<unsigned char> I, I_template;
267  reader.open(I);
268  vpRect template_roi(vpImagePoint(201, 310), vpImagePoint(201 + 152 - 1, 310 + 138 - 1));
269  vpImageTools::crop(I, template_roi, I_template);
270 
271  if (doTemplateMatching) {
272 #if defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI) || defined(VISP_HAVE_OPENCV)
273 
274 #if defined(VISP_HAVE_X11)
275  vpDisplayX d;
276 #elif defined(VISP_HAVE_GDI)
277  vpDisplayGDI d;
278 #elif defined(HAVE_OPENCV_HIGHGUI)
279  vpDisplayOpenCV d;
280 #endif
281 
282  d.init(I, 0, 0, "Image");
283 
284  vpImage<double> I_score;
285  std::vector<double> benchmark_vec;
286  bool quit = false;
287  while (!reader.end() && !quit) {
288  reader.acquire(I);
289 
291 
292  std::stringstream ss;
293  ss << "Frame: " << reader.getFrameIndex();
294  vpDisplay::displayText(I, 20, 20, ss.str(), vpColor::red);
295 
296  // Basic template matching
297  double t_proc = vpTime::measureTimeMs();
298  const unsigned int step_u = 5, step_v = 5;
299  vpImageTools::templateMatching(I, I_template, I_score, step_u, step_v);
300 
301  vpImagePoint max_loc;
302  double max_correlation = -1.0;
303  I_score.getMinMaxLoc(nullptr, &max_loc, nullptr, &max_correlation);
304  t_proc = vpTime::measureTimeMs() - t_proc;
305  benchmark_vec.push_back(t_proc);
306 
307  ss.str("");
308  ss << "Template matching: " << t_proc << " ms";
309  vpDisplay::displayText(I, 40, 20, ss.str(), vpColor::red);
310 
311  ss.str("");
312  ss << "Max correlation: " << max_correlation;
313  vpDisplay::displayText(I, 60, 20, ss.str(), vpColor::red);
314 
315  vpDisplay::displayRectangle(I, max_loc, I_template.getWidth(), I_template.getHeight(), vpColor::red, false, 1);
316 
317  vpDisplay::flush(I);
318 
320  if (vpDisplay::getClick(I, button, click)) {
321  switch (button) {
323  quit = !click;
324  break;
325 
327  click = !click;
328  break;
329 
330  default:
331  break;
332  }
333  }
334  }
335 
336  if (!benchmark_vec.empty()) {
337  std::cout << "Processing time, Mean: " << vpMath::getMean(benchmark_vec)
338  << " ms ; Median: " << vpMath::getMedian(benchmark_vec)
339  << " ms ; Std: " << vpMath::getStdev(benchmark_vec) << " ms" << std::endl;
340  }
341 #endif
342  }
343  else {
344  // ctest case
345  // Basic template matching
346  const unsigned int step_u = 5, step_v = 5;
347  vpImage<double> I_score, I_score_gold;
348 
349  double t = vpTime::measureTimeMs();
350  vpImageTools::templateMatching(I, I_template, I_score, step_u, step_v, true);
351  t = vpTime::measureTimeMs() - t;
352 
353  double t_gold = vpTime::measureTimeMs();
354  vpImageTools::templateMatching(I, I_template, I_score_gold, step_u, step_v, false);
355  t_gold = vpTime::measureTimeMs() - t_gold;
356 
357  std::cout << "Template matching: " << t << " ms" << std::endl;
358  std::cout << "Template matching (gold): " << t_gold << " ms" << std::endl;
359 
360  for (unsigned int i = 0; i < I_score.getHeight(); i++) {
361  for (unsigned int j = 0; j < I_score.getWidth(); j++) {
362  if (!vpMath::equal(I_score[i][j], I_score_gold[i][j], 1e-9)) {
363  std::cerr << "Issue with template matching, gold: " << std::setprecision(17) << I_score_gold[i][j]
364  << " ; compute: " << I_score[i][j] << std::endl;
365  return EXIT_FAILURE;
366  }
367  }
368  }
369  }
370 
371 }
372 catch (const vpException &e) {
373  std::cerr << "\nCatch an exception: " << e << std::endl;
374  return EXIT_FAILURE;
375 }
376 
377 return EXIT_SUCCESS;
378 }
static const vpColor red
Definition: vpColor.h:217
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:130
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
void init(vpImage< unsigned char > &I, int winx=-1, int winy=-1, const std::string &title="") VP_OVERRIDE
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)
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 displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
error that can be emitted by ViSP classes.
Definition: vpException.h:60
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:82
static void templateMatching(const vpImage< unsigned char > &I, const vpImage< unsigned char > &I_tpl, vpImage< double > &I_score, unsigned int step_u, unsigned int step_v, bool useOptimized=true)
static void crop(const vpImage< Type > &I, double roi_top, double roi_left, unsigned int roi_height, unsigned int roi_width, vpImage< Type > &crop, unsigned int v_scale=1, unsigned int h_scale=1)
Definition: vpImageTools.h:315
static void integralImage(const vpImage< unsigned char > &I, vpImage< double > &II, vpImage< double > &IIsq)
void getMinMaxLoc(vpImagePoint *minLoc, vpImagePoint *maxLoc, Type *minVal=nullptr, Type *maxVal=nullptr) const
Get the position of the minimum and/or the maximum pixel value within the bitmap and the correspondin...
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
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 bool equal(double x, double y, double threshold=0.001)
Definition: vpMath.h:459
static double getMean(const std::vector< double > &v)
Definition: vpMath.cpp:302
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:70
Defines a rectangle in the plane.
Definition: vpRect.h:79
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
VISP_EXPORT double measureTimeMs()