Visual Servoing Platform version 3.7.0
Loading...
Searching...
No Matches
testConnectedComponents.cpp
1/*
2 * ViSP, open source Visual Servoing Platform software.
3 * Copyright (C) 2005 - 2025 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 connected components.
32 */
33
39
40#include <map>
41#include <set>
42#include <visp3/core/vpImageTools.h>
43#include <visp3/core/vpIoTools.h>
44#include <visp3/imgproc/vpImgproc.h>
45#include <visp3/io/vpImageIo.h>
46#include <visp3/io/vpParseArgv.h>
47
48// List of allowed command line options
49#define GETOPTARGS "cdi:o:h"
50
51#ifdef ENABLE_VISP_NAMESPACE
52using namespace VISP_NAMESPACE_NAME;
53#endif
54
55void usage(const char *name, const char *badparam, const std::string &ipath, const std::string &opath, const std::string &user);
56bool getOptions(int argc, const char **argv, std::string &ipath, std::string &opath, std::string user);
57bool 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 */
68void usage(const char *name, const char *badparam, const std::string &ipath, const std::string &opath, const std::string &user)
69{
70 fprintf(stdout, "\n\
71Test connected components.\n\
72\n\
73SYNOPSIS\n\
74 %s [-i <input image path>] [-o <output image path>]\n\
75 [-h]\n \
76",
77name);
78
79 fprintf(stdout, "\n\
80OPTIONS: Default\n\
81 -i <input image path> %s\n\
82 Set image input path.\n\
83 From this path read \"Klimt/Klimt.pgm\"\n\
84 image.\n\
85 Setting the VISP_INPUT_IMAGE_PATH environment\n\
86 variable produces the same behaviour than using\n\
87 this option.\n\
88\n\
89 -o <output image path> %s\n\
90 Set image output path.\n\
91 From this directory, creates the \"%s\"\n\
92 subdirectory depending on the username, where \n\
93 output result images are written.\n\
94\n\
95 -h\n\
96 Print the help.\n\n",
97 ipath.c_str(), opath.c_str(), user.c_str());
98
99 if (badparam)
100 fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
101}
102
114bool getOptions(int argc, const char **argv, std::string &ipath, std::string &opath, std::string user)
115{
116 const char *optarg_;
117 int c;
118 while ((c = vpParseArgv::parse(argc, argv, GETOPTARGS, &optarg_)) > 1) {
119
120 switch (c) {
121 case 'i':
122 ipath = optarg_;
123 break;
124 case 'o':
125 opath = optarg_;
126 break;
127 case 'h':
128 usage(argv[0], nullptr, ipath, opath, user);
129 return false;
130
131 case 'c':
132 case 'd':
133 break;
134
135 default:
136 usage(argv[0], optarg_, ipath, opath, user);
137 return false;
138 }
139 }
140
141 if ((c == 1) || (c == -1)) {
142 // standalone param or error
143 usage(argv[0], nullptr, 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
152bool 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 = static_cast<unsigned int>(it1->second.front().get_i()), j = static_cast<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 = static_cast<unsigned int>(it_pt1->get_i());
189 j = static_cast<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
200int 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
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 }
249 catch (...) {
250 usage(argv[0], nullptr, ipath, opt_opath, username);
251 std::cerr << std::endl << "ERROR:" << std::endl;
252 std::cerr << " Cannot create " << opath << std::endl;
253 std::cerr << " Check your -o " << opt_opath << " option " << std::endl;
254 exit(EXIT_FAILURE);
255 }
256 }
257
258 // Compare ipath and env_ipath. If they differ, we take into account
259 // the input path coming from the command line option
260 if (!opt_ipath.empty() && !env_ipath.empty()) {
261 if (ipath != env_ipath) {
262 std::cout << std::endl << "WARNING: " << std::endl;
263 std::cout << " Since -i <visp image path=" << ipath << "> "
264 << " is different from VISP_IMAGE_PATH=" << env_ipath << std::endl
265 << " we skip the environment variable." << std::endl;
266 }
267 }
268
269 // Test if an input path is set
270 if (opt_ipath.empty() && env_ipath.empty()) {
271 usage(argv[0], nullptr, ipath, opt_opath, username);
272 std::cerr << std::endl << "ERROR:" << std::endl;
273 std::cerr << " Use -i <visp image path> option or set VISP_INPUT_IMAGE_PATH " << std::endl
274 << " environment variable to specify the location of the " << std::endl
275 << " image path where test images are located." << std::endl
276 << std::endl;
277 exit(EXIT_FAILURE);
278 }
279
280 //
281 // Here starts really the test
282 //
283
284 // Read Klimt.ppm
285 filename = vpIoTools::createFilePath(ipath, "Klimt/Klimt.pgm");
287 std::cout << "Read image: " << filename << std::endl;
288 vpImageIo::read(I, filename);
289 vpImageTools::binarise(I, (unsigned char)127, (unsigned char)255, (unsigned char)0, (unsigned char)255,
290 (unsigned char)255);
291 std::cout << "Image: " << I.getWidth() << "x" << I.getHeight() << std::endl;
292
293 vpImage<int> labels_connex4;
294 int nbComponents = 0;
295 double t = vpTime::measureTimeMs();
298 std::cout << "\n4-connexity connected components:" << std::endl;
299 std::cout << "Time: " << t << " ms" << std::endl;
300 std::cout << "nbComponents=" << nbComponents << std::endl;
301
302 vpImage<int> labels_connex8;
306 std::cout << "\n8-connexity connected components:" << std::endl;
307 std::cout << "Time: " << t << " ms" << std::endl;
308 std::cout << "nbComponents=" << nbComponents << std::endl;
309
310 // Save results
311 vpImage<vpRGBa> labels_connex4_color(labels_connex4.getHeight(), labels_connex4.getWidth(), vpRGBa(0, 0, 0, 0));
312 for (unsigned int i = 0; i < labels_connex4.getHeight(); i++) {
313 for (unsigned int j = 0; j < labels_connex4.getWidth(); j++) {
314 if (labels_connex4[i][j] != 0) {
315 labels_connex4_color[i][j] = vpRGBa(vpColor::getColor(static_cast<unsigned int>(labels_connex4[i][j])).R,
316 vpColor::getColor(static_cast<unsigned int>(labels_connex4[i][j])).G,
317 vpColor::getColor(static_cast<unsigned int>(labels_connex4[i][j])).B);
318 }
319 }
320 }
321
322 filename = vpIoTools::createFilePath(opath, "Klimt_connected_components_4.ppm");
323 vpImageIo::write(labels_connex4_color, filename);
324
325 vpImage<vpRGBa> labels_connex8_color(labels_connex8.getHeight(), labels_connex8.getWidth(), vpRGBa(0, 0, 0, 0));
326 for (unsigned int i = 0; i < labels_connex8.getHeight(); i++) {
327 for (unsigned int j = 0; j < labels_connex8.getWidth(); j++) {
328 if (labels_connex8[i][j] != 0) {
329 labels_connex8_color[i][j] = vpRGBa(vpColor::getColor(static_cast<unsigned int>(labels_connex4[i][j])).R,
330 vpColor::getColor(static_cast<unsigned int>(labels_connex4[i][j])).G,
331 vpColor::getColor(static_cast<unsigned int>(labels_connex4[i][j])).B);
332 }
333 }
334 }
335
336 filename = vpIoTools::createFilePath(opath, "Klimt_connected_components_8.ppm");
337 vpImageIo::write(labels_connex8_color, filename);
338
339#if defined(VISP_HAVE_OPENCV) && (VISP_HAVE_OPENCV_VERSION >= 0x030000) && defined(HAVE_OPENCV_IMGPROC)
340 cv::Mat matImg;
341 vpImageConvert::convert(I, matImg);
342
343 cv::Mat matLabels_4;
344 double t_opencv = vpTime::measureTimeMs();
345 cv::connectedComponents(matImg, matLabels_4, 4);
346 t_opencv = vpTime::measureTimeMs() - t_opencv;
347
348 std::set<int> set_labels_connex4_opencv;
349 vpImage<int> labels_connex4_opencv(static_cast<unsigned int>(matLabels_4.rows), static_cast<unsigned int>(matLabels_4.cols));
350 for (int i = 0; i < matLabels_4.rows; i++) {
351 for (int j = 0; j < matLabels_4.cols; j++) {
352 labels_connex4_opencv[i][j] = matLabels_4.at<int>(i, j);
353
354 if (matLabels_4.at<int>(i, j))
355 set_labels_connex4_opencv.insert(matLabels_4.at<int>(i, j));
356 }
357 }
358
359 std::cout << "\n4-connexity connected components (OpenCV):" << std::endl;
360 std::cout << "Time: " << t_opencv << " ms" << std::endl;
361 std::cout << "nb components: " << set_labels_connex4_opencv.size() << std::endl;
362 bool check_label = checkLabels(labels_connex4_opencv, labels_connex4);
363 std::cout << "checkLabels(labels_connex4_opencv, labels_connex4): " << check_label << std::endl;
364 // std::cout << "(labels_connex4_opencv == labels_connex4)? " <<
365 // (labels_connex4_opencv == labels_connex4) << std::endl;
366 if (!check_label) {
367 throw vpException(vpException::fatalError, "(labels_connex4_opencv != labels_connex4)");
368 }
369
370 cv::Mat matLabels_8;
371 t_opencv = vpTime::measureTimeMs();
372 cv::connectedComponents(matImg, matLabels_8, 8);
373 t_opencv = vpTime::measureTimeMs() - t_opencv;
374
375 std::set<int> set_labels_connex8_opencv;
376 vpImage<int> labels_connex8_opencv(static_cast<unsigned int>(matLabels_8.rows), static_cast<unsigned int>(matLabels_8.cols));
377 for (int i = 0; i < matLabels_8.rows; i++) {
378 for (int j = 0; j < matLabels_8.cols; j++) {
379 labels_connex8_opencv[i][j] = matLabels_8.at<int>(i, j);
380
381 if (matLabels_8.at<int>(i, j))
382 set_labels_connex8_opencv.insert(matLabels_8.at<int>(i, j));
383 }
384 }
385
386 std::cout << "\n8-connexity connected components (OpenCV):" << std::endl;
387 std::cout << "nb components: " << set_labels_connex8_opencv.size() << std::endl;
388 std::cout << "Time: " << t_opencv << " ms" << std::endl;
389 check_label = checkLabels(labels_connex8_opencv, labels_connex8);
390 std::cout << "checkLabels(labels_connex8_opencv, labels_connex8): " << check_label << std::endl;
391 // std::cout << "(labels_connex8_opencv == labels_connex8)? " <<
392 // (labels_connex8_opencv == labels_connex8) << std::endl;
393
394 if (!check_label) {
395 throw vpException(vpException::fatalError, "(labels_connex8_opencv != labels_connex8)");
396 }
397#endif
398
399 return EXIT_SUCCESS;
400 }
401 catch (const vpException &e) {
402 std::cerr << "Catch an exception: " << e.what() << std::endl;
403 return EXIT_FAILURE;
404 }
405}
static vpColor getColor(const unsigned int &i)
Definition vpColor.h:300
error that can be emitted by ViSP classes.
Definition vpException.h:60
@ fatalError
Fatal error.
Definition vpException.h:72
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
static void read(vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
static void write(const vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
static void binarise(vpImage< Type > &I, Type threshold1, Type threshold2, Type value1, Type value2, Type value3, bool useLUT=true)
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()
static bool checkDirectory(const std::string &dirname)
static std::string getUserName()
static std::string createFilePath(const std::string &parent, const std::string &child)
static void makeDirectory(const std::string &dirname)
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
VISP_EXPORT void connectedComponents(const VISP_NAMESPACE_ADDRESSING vpImage< unsigned char > &I, VISP_NAMESPACE_ADDRESSING vpImage< int > &labels, int &nbComponents, const VISP_NAMESPACE_ADDRESSING vpImageMorphology::vpConnexityType &connexity=VISP_NAMESPACE_ADDRESSING vpImageMorphology::CONNEXITY_4)
VISP_EXPORT double measureTimeMs()