Visual Servoing Platform  version 3.6.1 under development (2024-04-19)
tutorial-dnn-object-detection-live.cpp
1 #include <visp3/core/vpConfig.h>
3 #include <visp3/core/vpIoTools.h>
4 #include <visp3/detection/vpDetectorDNNOpenCV.h>
5 #include <visp3/gui/vpDisplayGDI.h>
6 #include <visp3/gui/vpDisplayOpenCV.h>
7 #include <visp3/gui/vpDisplayX.h>
8 
9 #if defined(HAVE_OPENCV_VIDEOIO)
10 #include <opencv2/videoio.hpp>
11 #endif
12 
13 #ifdef VISP_HAVE_NLOHMANN_JSON
14 #include <nlohmann/json.hpp>
15 using json = nlohmann::json;
16 #endif
17 
18 typedef enum
19 {
20  DETECTION_CONTAINER_MAP = 0,
21  DETECTION_CONTAINER_VECTOR = 1,
22  DETECTION_CONTAINER_BOTH = 2,
23  DETECTION_CONTAINER_COUNT = 3
24 } ChosenDetectionContainer;
25 
26 std::string chosenDetectionContainerToString(const ChosenDetectionContainer &choice)
27 {
28  switch (choice) {
29  case DETECTION_CONTAINER_MAP:
30  return "map";
31  case DETECTION_CONTAINER_VECTOR:
32  return "vector";
33  case DETECTION_CONTAINER_BOTH:
34  return "both";
35  default:
36  break;
37  }
38  return "unknown";
39 }
40 
41 ChosenDetectionContainer chosenDetectionContainerFromString(const std::string &choiceStr)
42 {
43  ChosenDetectionContainer choice(DETECTION_CONTAINER_COUNT);
44  bool hasFoundMatch = false;
45  for (unsigned int i = 0; i < DETECTION_CONTAINER_COUNT && !hasFoundMatch; i++) {
46  ChosenDetectionContainer candidate = (ChosenDetectionContainer)i;
47  hasFoundMatch = (chosenDetectionContainerToString(candidate) == vpIoTools::toLowerCase(choiceStr));
48  if (hasFoundMatch) {
49  choice = candidate;
50  }
51  }
52  return choice;
53 }
54 
55 std::string getAvailableDetectionContainer()
56 {
57  std::string availableContainers("< ");
58  for (unsigned int i = 0; i < DETECTION_CONTAINER_COUNT - 1; i++) {
59  std::string name = chosenDetectionContainerToString((ChosenDetectionContainer)i);
60  availableContainers += name + " , ";
61  }
62  availableContainers +=
63  chosenDetectionContainerToString((ChosenDetectionContainer)(DETECTION_CONTAINER_COUNT - 1)) + " >";
64  return availableContainers;
65 }
66 
67 int main(int argc, const char *argv[])
68 {
69  // Check if std:c++17 or higher
70 #if defined(HAVE_OPENCV_DNN) && defined(HAVE_OPENCV_VIDEOIO) && \
71  ((__cplusplus >= 201703L) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L)))
72  try {
73  std::string opt_device("0");
75  std::string opt_dnn_model = "opencv_face_detector_uint8.pb";
76  std::string opt_dnn_config = "opencv_face_detector.pbtxt";
77  std::string opt_dnn_framework = "none";
78  std::string opt_dnn_label_file = "";
79  vpDetectorDNNOpenCV::DNNResultsParsingType opt_dnn_type = vpDetectorDNNOpenCV::RESNET_10;
81  int opt_dnn_width = 300, opt_dnn_height = 300;
82  double opt_dnn_meanR = 104.0, opt_dnn_meanG = 177.0, opt_dnn_meanB = 123.0;
83  double opt_dnn_scale_factor = 1.0;
84  bool opt_dnn_swapRB = false;
85  bool opt_step_by_step = false;
86  float opt_dnn_confThresh = 0.5f;
87  float opt_dnn_nmsThresh = 0.4f;
88  double opt_dnn_filterThresh = 0.25;
89  ChosenDetectionContainer opt_dnn_containerType = DETECTION_CONTAINER_MAP;
90  bool opt_verbose = false;
91  std::string opt_input_json = "";
92  std::string opt_output_json = "";
93 
94  for (int i = 1; i < argc; i++) {
95  if (std::string(argv[i]) == "--device" && i + 1 < argc) {
96  opt_device = std::string(argv[++i]);
97  }
98  else if (std::string(argv[i]) == "--step-by-step") {
99  opt_step_by_step = true;
100  }
101  else if (std::string(argv[i]) == "--model" && i + 1 < argc) {
102  opt_dnn_model = std::string(argv[++i]);
103  }
104  else if (std::string(argv[i]) == "--type" && i + 1 < argc) {
105  opt_dnn_type = vpDetectorDNNOpenCV::dnnResultsParsingTypeFromString(std::string(argv[++i]));
106  }
107  else if (std::string(argv[i]) == "--config" && i + 1 < argc) {
108  opt_dnn_config = std::string(argv[++i]);
109  if (opt_dnn_config.find("none") != std::string::npos) {
110  opt_dnn_config = std::string();
111  }
112  }
113  else if (std::string(argv[i]) == "--framework" && i + 1 < argc) {
114  opt_dnn_framework = std::string(argv[++i]);
115  if (opt_dnn_framework.find("none") != std::string::npos) {
116  opt_dnn_framework = std::string();
117  }
118  }
119  else if (std::string(argv[i]) == "--width" && i + 1 < argc) {
120  opt_dnn_width = atoi(argv[++i]);
121  }
122  else if (std::string(argv[i]) == "--height" && i + 1 < argc) {
123  opt_dnn_height = atoi(argv[++i]);
124  }
125  else if (std::string(argv[i]) == "--mean" && i + 3 < argc) {
126  opt_dnn_meanR = atof(argv[++i]);
127  opt_dnn_meanG = atof(argv[++i]);
128  opt_dnn_meanB = atof(argv[++i]);
129  }
130  else if (std::string(argv[i]) == "--scale" && i + 1 < argc) {
131  opt_dnn_scale_factor = atof(argv[++i]);
132  }
133  else if (std::string(argv[i]) == "--swapRB") {
134  opt_dnn_swapRB = true;
135  }
136  else if (std::string(argv[i]) == "--confThresh" && i + 1 < argc) {
137  opt_dnn_confThresh = (float)atof(argv[++i]);
138  }
139  else if (std::string(argv[i]) == "--nmsThresh" && i + 1 < argc) {
140  opt_dnn_nmsThresh = (float)atof(argv[++i]);
141  }
142  else if (std::string(argv[i]) == "--filterThresh" && i + 1 < argc) {
143  opt_dnn_filterThresh = atof(argv[++i]);
144  }
145  else if (std::string(argv[i]) == "--labels" && i + 1 < argc) {
146  opt_dnn_label_file = std::string(argv[++i]);
147  }
148  else if (std::string(argv[i]) == "--container" && i + 1 < argc) {
149  opt_dnn_containerType = chosenDetectionContainerFromString(std::string(argv[++i]));
150  }
151  else if (std::string(argv[i]) == "--input-json" && i + 1 < argc) {
152  opt_input_json = std::string(std::string(argv[++i]));
153  }
154  else if (std::string(argv[i]) == "--output-json" && i + 1 < argc) {
155  opt_output_json = std::string(std::string(argv[++i]));
156  }
157  else if (std::string(argv[i]) == "--verbose" || std::string(argv[i]) == "-v") {
158  opt_verbose = true;
159  }
160  else if (std::string(argv[i]) == "--help" || std::string(argv[i]) == "-h") {
161  std::cout << "\nSYNOPSIS " << std::endl
162  << argv[0] << " [--device <video>]"
163  << " [--model <dnn weights file>]"
164  << " [--type <dnn type>]"
165  << " [--config <dnn config file]"
166  << " [--framework <name>]"
167  << " [--width <blob width>] [--height <blob height>]"
168  << " [--mean <meanR meanG meanB>]"
169  << " [--scale <scale factor>]"
170  << " [--swapRB]"
171  << " [--confThresh <threshold>]"
172  << " [--nmsThresh <threshold>]"
173  << " [--filterThresh <threshold>]"
174  << " [--labels <file>]"
175  << " [--container <type>]"
176  << " [--input-json <path_to_input_json>]"
177  << " [--output-json <path_to_output_json>]"
178  << " [--step-by-step]"
179  << " [--verbose, -v]"
180  << " [--help, -h]" << std::endl;
181  std::cout << "\nOPTIONS " << std::endl
182  << " --device <video>" << std::endl
183  << " Camera device number or video name used to stream images." << std::endl
184  << " To use the first camera found on the bus set 0. On Ubuntu setting 0" << std::endl
185  << " will use /dev/video0 device. To use a video simply put the name of" << std::endl
186  << " the video, like \"path/my-video.mp4\" or \"path/image-%04d.png\"" << std::endl
187  << " if your video is a sequence of images." << std::endl
188  << " Default: " << opt_device << std::endl
189  << std::endl
190  << " --model <dnn weights file>" << std::endl
191  << " Path to dnn network trained weights." << std::endl
192  << " Default: " << opt_dnn_model << std::endl
193  << std::endl
194  << " --type <dnn type>" << std::endl
195  << " Type of dnn network. Admissible values are in " << std::endl
196  << " " << vpDetectorDNNOpenCV::getAvailableDnnResultsParsingTypes() << std::endl
197  << " Default: " << opt_dnn_type << std::endl
198  << std::endl
199  << " --config <dnn config file>" << std::endl
200  << " Path to dnn network config file or \"none\" not to use one. " << std::endl
201  << " Default: " << opt_dnn_config << std::endl
202  << std::endl
203  << " --framework <name>" << std::endl
204  << " Framework name or \"none\" not to specify one. " << std::endl
205  << " Default: " << opt_dnn_framework << std::endl
206  << std::endl
207  << " --width <blob width>" << std::endl
208  << " Input images will be resized to this width. " << std::endl
209  << " Default: " << opt_dnn_width << std::endl
210  << std::endl
211  << " --height <blob height>" << std::endl
212  << " Input images will be resized to this height. " << std::endl
213  << " Default: " << opt_dnn_height << std::endl
214  << std::endl
215  << " --mean <meanR meanG meanB>" << std::endl
216  << " Mean RGB subtraction values. " << std::endl
217  << " Default: " << opt_dnn_meanR << " " << opt_dnn_meanG << " " << opt_dnn_meanB << std::endl
218  << std::endl
219  << " --scale <scale factor>" << std::endl
220  << " Scale factor used to normalize the range of pixel values. " << std::endl
221  << " Default: " << opt_dnn_scale_factor << std::endl
222  << std::endl
223  << " --swapRB" << std::endl
224  << " When used this option allows to swap Red and Blue channels. " << std::endl
225  << std::endl
226  << " --confThresh <threshold>" << std::endl
227  << " Confidence threshold. " << std::endl
228  << " Default: " << opt_dnn_confThresh << std::endl
229  << std::endl
230  << " --nmsThresh <threshold>" << std::endl
231  << " Non maximum suppression threshold. " << std::endl
232  << " Default: " << opt_dnn_nmsThresh << std::endl
233  << std::endl
234  << " --filterThresh <threshold >" << std::endl
235  << " Filter threshold. Set 0. to disable." << std::endl
236  << " Default: " << opt_dnn_filterThresh << std::endl
237  << std::endl
238  << " --labels <file>" << std::endl
239  << " Path to label file either in txt or yaml format. Keep empty if unknown." << std::endl
240  << " Default: \"" << opt_dnn_label_file << "\"" << std::endl
241  << std::endl
242  << " --container <type>" << std::endl
243  << " Container type in " << getAvailableDetectionContainer() << std::endl
244  << " Default: " << chosenDetectionContainerToString(opt_dnn_containerType) << std::endl
245  << std::endl
246  << " --input-json <path_to_input_json>" << std::endl
247  << " Input JSON file used to configure the DNN. If set, the other arguments will be used to override the values set in the json file." << std::endl
248  << " Default: empty" << std::endl
249  << std::endl
250  << " --output-json <type>" << std::endl
251  << " Output JSON file where will be saved the DNN configuration. If empty, does not save the configuration." << std::endl
252  << " Default: empty" << std::endl
253  << std::endl
254  << " --step-by-step" << std::endl
255  << " Enable step by step mode, waiting for a user click to process next image." << std::endl
256  << std::endl
257  << " --verbose, -v" << std::endl
258  << " Enable verbose mode." << std::endl
259  << std::endl
260  << " --help, -h" << std::endl
261  << " Display this helper message." << std::endl
262  << std::endl;
263  return EXIT_SUCCESS;
264  }
265  }
266 
267  std::cout << "Video device : " << opt_device << std::endl;
268  std::cout << "Label file (optional): " << (opt_dnn_label_file.empty() ? "None" : opt_dnn_label_file) << std::endl;
269 
270  cv::VideoCapture capture;
271  bool hasCaptureOpeningSucceeded;
272  if (vpMath::isNumber(opt_device)) {
273  hasCaptureOpeningSucceeded = capture.open(std::atoi(opt_device.c_str()));
274  }
275  else {
276  hasCaptureOpeningSucceeded = capture.open(opt_device);
277  }
278  if (!hasCaptureOpeningSucceeded) {
279  std::cout << "Capture from camera: " << opt_device << " didn't work" << std::endl;
280  return EXIT_FAILURE;
281  }
282 
283  vpImage<vpRGBa> I;
284 #if defined(VISP_HAVE_X11)
285  vpDisplayX d;
286 #elif defined(VISP_HAVE_GDI)
287  vpDisplayGDI d;
288 #elif defined(HAVE_OPENCV_HIGHGUI)
289  vpDisplayOpenCV d;
290 #endif
292 
293  if (!opt_dnn_label_file.empty() && !vpIoTools::checkFilename(opt_dnn_label_file)) {
295  "The file containing the classes labels \"" + opt_dnn_label_file + "\" does not exist !"));
296  }
297 
298  vpDetectorDNNOpenCV dnn;
299 #ifdef VISP_HAVE_NLOHMANN_JSON
300  if (!opt_input_json.empty()) {
302  dnn.initFromJSON(opt_input_json);
304  }
305 #else
306  if (!opt_input_json.empty()) {
307  std::cerr << "Error: NLOHMANN JSON library is not installed, please install it following ViSP documentation to configure the vpDetectorDNNOpenCV from a JSON file." << std::endl;
308  return EXIT_FAILURE;
309  }
310 #endif
311  else {
313  vpDetectorDNNOpenCV::NetConfig netConfig(opt_dnn_confThresh, opt_dnn_nmsThresh, opt_dnn_label_file
314  , cv::Size(opt_dnn_width, opt_dnn_height), opt_dnn_filterThresh, cv::Scalar(opt_dnn_meanR, opt_dnn_meanG, opt_dnn_meanB)
315  , opt_dnn_scale_factor, opt_dnn_swapRB, opt_dnn_type
316  , opt_dnn_model, opt_dnn_config, opt_dnn_framework
317  );
318  dnn.setNetConfig(netConfig);
320  }
321 
322  std::cout << dnn.getNetConfig() << std::endl;
323 
324 #ifdef VISP_HAVE_NLOHMANN_JSON
325  if (!opt_output_json.empty()) {
326  dnn.saveConfigurationInJSON(opt_output_json);
327  }
328 #else
329  if (!opt_output_json.empty()) {
330  std::cerr << "Error: NLOHMANN JSON library is not installed, please install it following ViSP documentation to save the configuration in a JSON file." << std::endl;
331  }
332 #endif
333 
334  cv::Mat frame;
335  while (true) {
336  capture >> frame;
337  if (frame.empty())
338  break;
339 
340  if (I.getSize() == 0) {
341  vpImageConvert::convert(frame, I);
342  d.init(I);
343  vpDisplay::setTitle(I, "DNN object detection");
344  if (opt_verbose) {
345  std::cout << "Process image: " << I.getWidth() << " x " << I.getHeight() << std::endl;
346  }
347  }
348  else {
349  vpImageConvert::convert(frame, I);
350  }
351  if (opt_verbose) {
352  std::cout << "Process new image" << std::endl;
353  }
354 
356 
357  if (opt_dnn_containerType == DETECTION_CONTAINER_MAP || opt_dnn_containerType == DETECTION_CONTAINER_BOTH) {
358  double t = vpTime::measureTimeMs();
360  std::map<std::string, std::vector<vpDetectorDNNOpenCV::DetectedFeatures2D> > detections;
361  dnn.detect(frame, detections);
363  t = vpTime::measureTimeMs() - t;
364 
366  for (auto key_val : detections) {
367  if (opt_verbose) {
368  std::cout << " Class name : " << key_val.first << std::endl;
369  }
370  for (vpDetectorDNNOpenCV::DetectedFeatures2D detection : key_val.second) {
371  if (opt_verbose) {
372  std::cout << " Bounding box : " << detection.getBoundingBox() << std::endl;
373  std::cout << " Class Id : " << detection.getClassId() << std::endl;
374  if (detection.getClassName())
375  std::cout << " Class name : " << detection.getClassName().value() << std::endl;
376  std::cout << " Confidence score: " << detection.getConfidenceScore() << std::endl;
377  }
378  detection.display(I);
379  }
380  }
382 
383  std::ostringstream oss_map;
384  oss_map << "Detection time (map): " << t << " ms";
385  if (opt_verbose) {
386  // Displaying timing result in console
387  std::cout << " " << oss_map.str() << std::endl;
388  }
389  // Displaying timing result on the image
390  vpDisplay::displayText(I, 60, 20, oss_map.str(), vpColor::red);
391  }
392 
393  if (opt_dnn_containerType == DETECTION_CONTAINER_VECTOR || opt_dnn_containerType == DETECTION_CONTAINER_BOTH) {
394  double t_vector = vpTime::measureTimeMs();
396  std::vector<vpDetectorDNNOpenCV::DetectedFeatures2D> detections_vec;
397  dnn.detect(frame, detections_vec);
399  t_vector = vpTime::measureTimeMs() - t_vector;
400 
402  for (auto detection : detections_vec) {
403  if (opt_verbose) {
404  std::cout << " Bounding box : " << detection.getBoundingBox() << std::endl;
405  std::cout << " Class Id : " << detection.getClassId() << std::endl;
406  std::optional<std::string> classname_opt = detection.getClassName();
407  std::cout << " Class name : " << (classname_opt ? *classname_opt : "Not known") << std::endl;
408  std::cout << " Confidence score: " << detection.getConfidenceScore() << std::endl;
409  }
410  detection.display(I);
411  }
413 
414  std::ostringstream oss_vec;
415  oss_vec << "Detection time (vector): " << t_vector << " ms";
416  if (opt_verbose) {
417  // Displaying timing result in console
418  std::cout << " " << oss_vec.str() << std::endl;
419  }
420  // Displaying timing result on the image
421  vpDisplay::displayText(I, 80, 20, oss_vec.str(), vpColor::red);
422  }
423 
424  // // UI display
425  if (opt_step_by_step) {
426  vpDisplay::displayText(I, 20, 20, "Left click to display next image", vpColor::red);
427  }
428  vpDisplay::displayText(I, 40, 20, "Right click to quit", vpColor::red);
429 
430  vpDisplay::flush(I);
432 
433  if (vpDisplay::getClick(I, button, opt_step_by_step)) {
434  if (button == vpMouseButton::button1) {
435  // Left click => next image
436  continue;
437  }
438  else if (button == vpMouseButton::button3) {
439  // Right click => stop the program
440  break;
441  }
442  }
443  }
444 
445  }
446  catch (const vpException &e) {
447  std::cout << e.what() << std::endl;
448  }
449 #else
450  (void)argc;
451  (void)argv;
452 #endif
453  return EXIT_SUCCESS;
454 }
static const vpColor red
Definition: vpColor.h:211
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:128
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:128
void init(vpImage< unsigned char > &I, int win_x=-1, int win_y=-1, const std::string &win_title="") vp_override
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
virtual void setDownScalingFactor(unsigned int scale)
Definition: vpDisplay.cpp:227
static void display(const vpImage< unsigned char > &I)
static void setTitle(const vpImage< unsigned char > &I, const std::string &windowtitle)
static void flush(const vpImage< unsigned char > &I)
@ SCALE_AUTO
Definition: vpDisplay.h:179
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:59
@ fatalError
Fatal error.
Definition: vpException.h:84
const char * what() const
Definition: vpException.cpp:70
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
unsigned int getWidth() const
Definition: vpImage.h:245
unsigned int getSize() const
Definition: vpImage.h:224
unsigned int getHeight() const
Definition: vpImage.h:184
static std::string toLowerCase(const std::string &input)
Return a lower-case version of the string input . Numbers and special characters stay the same.
Definition: vpIoTools.cpp:2111
static bool checkFilename(const std::string &filename)
Definition: vpIoTools.cpp:1213
static bool isNumber(const std::string &str)
Definition: vpMath.cpp:215
VISP_EXPORT double measureTimeMs()