Visual Servoing Platform  version 3.2.0 under development (2019-01-22)
testConnectedComponents.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  * Test connected components.
33  *
34  * Authors:
35  * Souriya Trinh
36  *
37  *****************************************************************************/
38 #include <map>
39 #include <set>
40 #include <visp3/core/vpImageTools.h>
41 #include <visp3/core/vpIoTools.h>
42 #include <visp3/imgproc/vpImgproc.h>
43 #include <visp3/io/vpImageIo.h>
44 #include <visp3/io/vpParseArgv.h>
45 
52 // List of allowed command line options
53 #define GETOPTARGS "cdi:o:h"
54 
55 void usage(const char *name, const char *badparam, std::string ipath, std::string opath, std::string user);
56 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &opath, std::string user);
57 bool checkLabels(const vpImage<int> &label1, const vpImage<int> &label2);
58 
59 /*
60  Print the program options.
61 
62  \param name : Program name.
63  \param badparam : Bad parameter name.
64  \param ipath: Input image path.
65  \param opath : Output image path.
66  \param user : Username.
67  */
68 void usage(const char *name, const char *badparam, std::string ipath, std::string opath, std::string user)
69 {
70  fprintf(stdout, "\n\
71 Test connected components.\n\
72 \n\
73 SYNOPSIS\n\
74  %s [-i <input image path>] [-o <output image path>]\n\
75  [-h]\n \
76 ", name);
77 
78  fprintf(stdout, "\n\
79 OPTIONS: Default\n\
80  -i <input image path> %s\n\
81  Set image input path.\n\
82  From this path read \"Klimt/Klimt.pgm\"\n\
83  image.\n\
84  Setting the VISP_INPUT_IMAGE_PATH environment\n\
85  variable produces the same behaviour than using\n\
86  this option.\n\
87 \n\
88  -o <output image path> %s\n\
89  Set image output path.\n\
90  From this directory, creates the \"%s\"\n\
91  subdirectory depending on the username, where \n\
92  output result images are written.\n\
93 \n\
94  -h\n\
95  Print the help.\n\n", ipath.c_str(), opath.c_str(), user.c_str());
96 
97  if (badparam)
98  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
99 }
100 
112 bool getOptions(int argc, const char **argv, std::string &ipath, std::string &opath, std::string user)
113 {
114  const char *optarg_;
115  int c;
116  while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
117 
118  switch (c) {
119  case 'i':
120  ipath = optarg_;
121  break;
122  case 'o':
123  opath = optarg_;
124  break;
125  case 'h':
126  usage(argv[0], NULL, ipath, opath, user);
127  return false;
128  break;
129 
130  case 'c':
131  case 'd':
132  break;
133 
134  default:
135  usage(argv[0], optarg_, ipath, opath, user);
136  return false;
137  break;
138  }
139  }
140 
141  if ((c == 1) || (c == -1)) {
142  // standalone param or error
143  usage(argv[0], NULL, ipath, opath, user);
144  std::cerr << "ERROR: " << std::endl;
145  std::cerr << " Bad argument " << optarg_ << std::endl << std::endl;
146  return false;
147  }
148 
149  return true;
150 }
151 
152 bool checkLabels(const vpImage<int> &label1, const vpImage<int> &label2)
153 {
154  if (label1.getHeight() != label2.getHeight() || label1.getWidth() != label2.getWidth())
155  return false;
156 
157  std::map<int, std::vector<vpImagePoint> > map_label1, map_label2;
158  for (unsigned int i = 0; i < label1.getHeight(); i++) {
159  for (unsigned int j = 0; j < label1.getWidth(); j++) {
160  if ((label1[i][j] > 0 && label2[i][j] == 0) || (label1[i][j] == 0 && label2[i][j] > 0)) {
161  std::cerr << "label1[i][j] > 0 && label2[i][j] == 0 || label1[i][j] "
162  "== 0 && label2[i][j] > 0"
163  << std::endl;
164  return false;
165  }
166 
167  if (label1[i][j])
168  map_label1[label1[i][j]].push_back(vpImagePoint(i, j));
169 
170  if (label2[i][j])
171  map_label2[label2[i][j]].push_back(vpImagePoint(i, j));
172  }
173  }
174 
175  if (map_label1.size() != map_label2.size()) {
176  std::cerr << "map_label1.size() != map_label2.size()" << std::endl;
177  return false;
178  }
179 
180  for (std::map<int, std::vector<vpImagePoint> >::const_iterator it1 = map_label1.begin(); it1 != map_label1.end();
181  ++it1) {
182  // Get corresponding label in the other method
183  unsigned int i = (unsigned int)it1->second.front().get_i(), j = (unsigned int)it1->second.front().get_j();
184  int lab2 = label2[i][j];
185 
186  std::vector<vpImagePoint>::const_iterator it_pt1 = it1->second.begin();
187  for (; it_pt1 != it1->second.end(); ++it_pt1) {
188  i = (unsigned int)it_pt1->get_i();
189  j = (unsigned int)it_pt1->get_j();
190  if (label2[i][j] != lab2) {
191  std::cerr << "label2[i][j] != lab2" << std::endl;
192  return false;
193  }
194  }
195  }
196 
197  return true;
198 }
199 
200 int main(int argc, const char **argv)
201 {
202  try {
203  std::string env_ipath;
204  std::string opt_ipath;
205  std::string opt_opath;
206  std::string ipath;
207  std::string opath;
208  std::string filename;
209  std::string username;
210 
211  // Get the visp-images-data package path or VISP_INPUT_IMAGE_PATH
212  // environment variable value
213  env_ipath = vpIoTools::getViSPImagesDataPath();
214 
215  // Set the default input path
216  if (!env_ipath.empty())
217  ipath = env_ipath;
218 
219 // Set the default output path
220 #if defined(_WIN32)
221  opt_opath = "C:/temp";
222 #else
223  opt_opath = "/tmp";
224 #endif
225 
226  // Get the user login name
227  vpIoTools::getUserName(username);
228 
229  // Read the command line options
230  if (getOptions(argc, argv, opt_ipath, opt_opath, username) == false) {
231  exit(EXIT_FAILURE);
232  }
233 
234  // Get the option values
235  if (!opt_ipath.empty())
236  ipath = opt_ipath;
237  if (!opt_opath.empty())
238  opath = opt_opath;
239 
240  // Append to the output path string, the login name of the user
241  opath = vpIoTools::createFilePath(opath, username);
242 
243  // Test if the output path exist. If no try to create it
244  if (vpIoTools::checkDirectory(opath) == false) {
245  try {
246  // Create the dirname
248  } catch (...) {
249  usage(argv[0], NULL, ipath, opt_opath, username);
250  std::cerr << std::endl << "ERROR:" << std::endl;
251  std::cerr << " Cannot create " << opath << std::endl;
252  std::cerr << " Check your -o " << opt_opath << " option " << std::endl;
253  exit(EXIT_FAILURE);
254  }
255  }
256 
257  // Compare ipath and env_ipath. If they differ, we take into account
258  // the input path comming from the command line option
259  if (!opt_ipath.empty() && !env_ipath.empty()) {
260  if (ipath != env_ipath) {
261  std::cout << std::endl << "WARNING: " << std::endl;
262  std::cout << " Since -i <visp image path=" << ipath << "> "
263  << " is different from VISP_IMAGE_PATH=" << env_ipath << std::endl
264  << " we skip the environment variable." << std::endl;
265  }
266  }
267 
268  // Test if an input path is set
269  if (opt_ipath.empty() && env_ipath.empty()) {
270  usage(argv[0], NULL, ipath, opt_opath, username);
271  std::cerr << std::endl << "ERROR:" << std::endl;
272  std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
273  << " environment variable to specify the location of the " << std::endl
274  << " image path where test images are located." << std::endl
275  << std::endl;
276  exit(EXIT_FAILURE);
277  }
278 
279  //
280  // Here starts really the test
281  //
282 
283  // Read Klimt.ppm
284  filename = vpIoTools::createFilePath(ipath, "Klimt/Klimt.pgm");
286  std::cout << "Read image: " << filename << std::endl;
287  vpImageIo::read(I, filename);
288  vpImageTools::binarise(I, (unsigned char)127, (unsigned char)255, (unsigned char)0, (unsigned char)255,
289  (unsigned char)255);
290  std::cout << "Image: " << I.getWidth() << "x" << I.getHeight() << std::endl;
291 
292  vpImage<int> labels_connex4;
293  int nbComponents = 0;
294  double t = vpTime::measureTimeMs();
295  vp::connectedComponents(I, labels_connex4, nbComponents, vpImageMorphology::CONNEXITY_4);
296  t = vpTime::measureTimeMs() - t;
297  std::cout << "\n4-connexity connected components:" << std::endl;
298  std::cout << "Time: " << t << " ms" << std::endl;
299  std::cout << "nbComponents=" << nbComponents << std::endl;
300 
301  vpImage<int> labels_connex8;
302  t = vpTime::measureTimeMs();
303  vp::connectedComponents(I, labels_connex8, nbComponents, vpImageMorphology::CONNEXITY_8);
304  t = vpTime::measureTimeMs() - t;
305  std::cout << "\n8-connexity connected components:" << std::endl;
306  std::cout << "Time: " << t << " ms" << std::endl;
307  std::cout << "nbComponents=" << nbComponents << std::endl;
308 
309  // Save results
310  vpImage<vpRGBa> labels_connex4_color(labels_connex4.getHeight(), labels_connex4.getWidth(), vpRGBa(0, 0, 0, 0));
311  for (unsigned int i = 0; i < labels_connex4.getHeight(); i++) {
312  for (unsigned int j = 0; j < labels_connex4.getWidth(); j++) {
313  if (labels_connex4[i][j] != 0) {
314  labels_connex4_color[i][j] = vpRGBa(vpColor::getColor((unsigned int)labels_connex4[i][j]).R,
315  vpColor::getColor((unsigned int)labels_connex4[i][j]).G,
316  vpColor::getColor((unsigned int)labels_connex4[i][j]).B);
317  }
318  }
319  }
320 
321  filename = vpIoTools::createFilePath(opath, "Klimt_connected_components_4.ppm");
322  vpImageIo::write(labels_connex4_color, filename);
323 
324  vpImage<vpRGBa> labels_connex8_color(labels_connex8.getHeight(), labels_connex8.getWidth(), vpRGBa(0, 0, 0, 0));
325  for (unsigned int i = 0; i < labels_connex8.getHeight(); i++) {
326  for (unsigned int j = 0; j < labels_connex8.getWidth(); j++) {
327  if (labels_connex8[i][j] != 0) {
328  labels_connex8_color[i][j] = vpRGBa(vpColor::getColor((unsigned int)labels_connex8[i][j]).R,
329  vpColor::getColor((unsigned int)labels_connex8[i][j]).G,
330  vpColor::getColor((unsigned int)labels_connex8[i][j]).B);
331  }
332  }
333  }
334 
335  filename = vpIoTools::createFilePath(opath, "Klimt_connected_components_8.ppm");
336  vpImageIo::write(labels_connex8_color, filename);
337 
338 #if (VISP_HAVE_OPENCV_VERSION >= 0x030000)
339  cv::Mat matImg;
340  vpImageConvert::convert(I, matImg);
341 
342  cv::Mat matLabels_4;
343  double t_opencv = vpTime::measureTimeMs();
344  cv::connectedComponents(matImg, matLabels_4, 4);
345  t_opencv = vpTime::measureTimeMs() - t_opencv;
346 
347  std::set<int> set_labels_connex4_opencv;
348  vpImage<int> labels_connex4_opencv((unsigned int)matLabels_4.rows, (unsigned int)matLabels_4.cols);
349  for (int i = 0; i < matLabels_4.rows; i++) {
350  for (int j = 0; j < matLabels_4.cols; j++) {
351  labels_connex4_opencv[i][j] = matLabels_4.at<int>(i, j);
352 
353  if (matLabels_4.at<int>(i, j))
354  set_labels_connex4_opencv.insert(matLabels_4.at<int>(i, j));
355  }
356  }
357 
358  std::cout << "\n4-connexity connected components (OpenCV):" << std::endl;
359  std::cout << "Time: " << t_opencv << " ms" << std::endl;
360  std::cout << "nb components: " << set_labels_connex4_opencv.size() << std::endl;
361  bool check_label = checkLabels(labels_connex4_opencv, labels_connex4);
362  std::cout << "checkLabels(labels_connex4_opencv, labels_connex4): " << check_label << std::endl;
363  // std::cout << "(labels_connex4_opencv == labels_connex4)? " <<
364  // (labels_connex4_opencv == labels_connex4) << std::endl;
365  if (!check_label) {
366  throw vpException(vpException::fatalError, "(labels_connex4_opencv != labels_connex4)");
367  }
368 
369  cv::Mat matLabels_8;
370  t_opencv = vpTime::measureTimeMs();
371  cv::connectedComponents(matImg, matLabels_8, 8);
372  t_opencv = vpTime::measureTimeMs() - t_opencv;
373 
374  std::set<int> set_labels_connex8_opencv;
375  vpImage<int> labels_connex8_opencv((unsigned int)matLabels_8.rows, (unsigned int)matLabels_8.cols);
376  for (int i = 0; i < matLabels_8.rows; i++) {
377  for (int j = 0; j < matLabels_8.cols; j++) {
378  labels_connex8_opencv[i][j] = matLabels_8.at<int>(i, j);
379 
380  if (matLabels_8.at<int>(i, j))
381  set_labels_connex8_opencv.insert(matLabels_8.at<int>(i, j));
382  }
383  }
384 
385  std::cout << "\n8-connexity connected components (OpenCV):" << std::endl;
386  std::cout << "nb components: " << set_labels_connex8_opencv.size() << std::endl;
387  std::cout << "Time: " << t_opencv << " ms" << std::endl;
388  check_label = checkLabels(labels_connex8_opencv, labels_connex8);
389  std::cout << "checkLabels(labels_connex8_opencv, labels_connex8): " << check_label << std::endl;
390  // std::cout << "(labels_connex8_opencv == labels_connex8)? " <<
391  // (labels_connex8_opencv == labels_connex8) << std::endl;
392 
393  if (!check_label) {
394  throw vpException(vpException::fatalError, "(labels_connex8_opencv != labels_connex8)");
395  }
396 #endif
397 
398  return EXIT_SUCCESS;
399  } catch (const vpException &e) {
400  std::cerr << "Catch an exception: " << e.what() << std::endl;
401  return EXIT_FAILURE;
402  }
403 }
static void binarise(vpImage< Type > &I, Type threshold1, Type threshold2, Type value1, Type value2, Type value3, const bool useLUT=true)
Definition: vpImageTools.h:430
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:467
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1316
unsigned int getWidth() const
Definition: vpImage.h:239
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
error that can be emited by ViSP classes.
Definition: vpException.h:71
VISP_EXPORT void connectedComponents(const vpImage< unsigned char > &I, vpImage< int > &labels, int &nbComponents, const vpImageMorphology::vpConnexityType &connexity=vpImageMorphology::CONNEXITY_4)
VISP_EXPORT double measureTimeMs()
Definition: vpTime.cpp:88
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:69
Definition: vpRGBa.h:66
static void write(const vpImage< unsigned char > &I, const std::string &filename)
Definition: vpImageIo.cpp:375
static void makeDirectory(const char *dirname)
Definition: vpIoTools.cpp:597
const char * what() const
static std::string createFilePath(const std::string &parent, const std::string &child)
Definition: vpIoTools.cpp:1541
static std::string getUserName()
Definition: vpIoTools.cpp:298
static void read(vpImage< unsigned char > &I, const std::string &filename)
Definition: vpImageIo.cpp:207
unsigned int getHeight() const
Definition: vpImage.h:178
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:88
static vpColor getColor(const unsigned int &i)
Definition: vpColor.h:249
Definition of the vpImage class member functions.
Definition: vpImage.h:116