MRPT  1.9.9
test.cpp
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | http://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
6  | See: http://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See details in http://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 
10 #include <mrpt/detectors.h>
13 #include <mrpt/obs/CRawlog.h>
14 #include <mrpt/gui.h>
19 #include <iostream>
20 #include <mrpt/core/exceptions.h>
21 #include <mrpt/examples_config.h>
22 #include <mrpt/img/TColor.h>
23 
24 using namespace mrpt;
25 using namespace mrpt::maps;
26 using namespace mrpt::obs;
27 using namespace mrpt::gui;
28 using namespace mrpt::math;
29 using namespace mrpt::hwdrivers;
30 using namespace mrpt::detectors;
31 using namespace mrpt::config;
32 using namespace std;
33 using namespace mrpt::img;
34 using namespace mrpt::serialization;
35 
36 string myDataDir(MRPT_EXAMPLES_BASE_DIRECTORY + string("detectors_face/"));
37 string myInitFile(
38  MRPT_EXAMPLES_BASE_DIRECTORY +
39  string("detectors_face/FACE_DETECTION_TEST.INI"));
40 
41 CFaceDetection faceDetector; // Face detector object
42 
43 bool showEachDetectedFace; // If using a 3D face detection (actually with
44 // swissrange) and we want stop every a face is
45 // detected for analize it.
46 bool batchMode;
47 vector<string> rawlogs;
48 vector<std::vector<uint32_t>> falsePositives;
49 vector<std::vector<uint32_t>> ignored;
50 string rawlogsDir;
51 
52 #ifdef MRPT_OPENCV_SRC_DIR
53 static string OPENCV_SRC_DIR = MRPT_OPENCV_SRC_DIR;
54 #else
55 static string OPENCV_SRC_DIR = "./";
56 #endif
57 
58 // ------------------------------------------------------
59 // TestCamera3DFaceDetection
60 // ------------------------------------------------------
62 {
63  CDisplayWindow win("Live video");
64  CDisplayWindow win2("FaceDetected");
65 
66  cout << "Close the window to exit." << endl;
67 
68  mrpt::gui::CDisplayWindow3D win3D("3D camera view", 800, 600);
70 
71  win3D.setCameraAzimuthDeg(140);
72  win3D.setCameraElevationDeg(20);
73  win3D.setCameraZoom(6.0);
74  win3D.setCameraPointingToPoint(2.5, 0, 0);
75 
76  mrpt::opengl::COpenGLScene::Ptr& scene = win3D.get3DSceneAndLock();
78 
80  mrpt::make_aligned_shared<mrpt::opengl::CPointCloudColoured>();
81  gl_points->setPointSize(4.5);
82 
84  mrpt::make_aligned_shared<mrpt::opengl::CPointCloudColoured>();
85  gl_points2->setPointSize(4.5);
86 
87  // Create the Opengl object for the point cloud:
88  scene->insert(gl_points);
89  scene->insert(mrpt::make_aligned_shared<mrpt::opengl::CGridPlaneXY>());
91 
92  win3D.unlockAccess3DScene();
93 
95  {
96  win3D2.setWindowTitle("3D Face detected");
97  win3D2.resize(400, 300);
98 
99  win3D2.setCameraAzimuthDeg(140);
100  win3D2.setCameraElevationDeg(20);
101  win3D2.setCameraZoom(6.0);
102  win3D2.setCameraPointingToPoint(2.5, 0, 0);
103 
104  scene2 = win3D2.get3DSceneAndLock();
105 
106  scene2->insert(gl_points2);
107  scene2->insert(mrpt::make_aligned_shared<mrpt::opengl::CGridPlaneXY>());
108 
109  win3D2.unlockAccess3DScene();
110  }
111 
112  double counter = 0;
113  mrpt::system::CTicTac tictac;
114 
115  CVectorDouble fps;
116 
117  while (win.isOpen())
118  {
119  if (!counter) tictac.Tic();
120 
122 
123  try
124  {
125  o = std::dynamic_pointer_cast<CObservation3DRangeScan>(
126  cam->getNextFrame());
127  }
128  catch (CExceptionEOF&)
129  {
130  break;
131  }
132  ASSERT_(o);
133 
134  vector_detectable_object detected;
135 
136  // CObservation3DRangeScan::Ptr o =
137  // std::dynamic_pointer_cast<CObservation3DRangeScan>(obs);
138 
139  faceDetector.detectObjects(o, detected);
140  // static int x = 0;
141 
142  if (detected.size() > 0)
143  {
144  for (unsigned int i = 0; i < detected.size(); i++)
145  {
146  ASSERT_(IS_CLASS(detected[i], CDetectable3D));
148  std::dynamic_pointer_cast<CDetectable3D>(detected[i]);
149 
151  {
153  o->getZoneAsObs(
154  face, obj->m_y, obj->m_y + obj->m_height, obj->m_x,
155  obj->m_x + obj->m_width);
156  win2.showImage(face.intensityImage);
157 
158  if (o->hasPoints3D)
159  {
160  win3D2.get3DSceneAndLock();
161 
162  CColouredPointsMap pntsMap;
163 
164  if (!o->hasConfidenceImage)
165  {
166  pntsMap.colorScheme.scheme =
168  pntsMap.loadFromRangeScan(face);
169  }
170  else
171  {
172  vector<float> xs, ys, zs;
173  unsigned int i = 0;
174  for (unsigned int j = 0;
175  j < face.confidenceImage.getHeight(); j++)
176  for (unsigned int k = 0;
177  k < face.confidenceImage.getWidth();
178  k++, i++)
179  {
180  unsigned char c =
181  *(face.confidenceImage.get_unsafe(
182  k, j, 0));
183  if (c > faceDetector.m_options
185  {
186  xs.push_back(face.points3D_x[i]);
187  ys.push_back(face.points3D_y[i]);
188  zs.push_back(face.points3D_z[i]);
189  }
190  }
191 
192  pntsMap.setAllPoints(xs, ys, zs);
193  }
194 
195  gl_points2->loadFromPointsMap(&pntsMap);
196 
197  win3D2.unlockAccess3DScene();
198  win3D2.repaint();
199  }
200  }
201 
202  o->intensityImage.rectangle(
203  obj->m_x, obj->m_y, obj->m_x + obj->m_width,
204  obj->m_y + obj->m_height, TColor(255, 0, 0));
205 
206  // x++;
207  // if (( showEachDetectedFace ) && ( x > 430 ) )
208  // system::pause();
209  }
210  }
211 
212  win.showImage(o->intensityImage);
213 
214  /*if (( showEachDetectedFace ) && ( detected.size() ))
215  system::pause();*/
216 
217  win3D.get3DSceneAndLock();
218  CColouredPointsMap pntsMap;
220  pntsMap.loadFromRangeScan(*(o.get()));
221 
222  gl_points->loadFromPointsMap(&pntsMap);
223  win3D.unlockAccess3DScene();
224  win3D.repaint();
225 
226  if (++counter == 10)
227  {
228  double t = tictac.Tac();
229  cout << "Frame Rate: " << counter / t << " fps" << endl;
230  fps.push_back(counter / t);
231  counter = 0;
232  }
233  std::this_thread::sleep_for(2ms);
234  }
235 
236  cout << "Fps mean: " << fps.sumAll() / fps.size() << endl;
237 
239 
240  cout << "Closing..." << endl;
241 }
242 
243 // ------------------------------------------------------
244 // TestCameraFaceDetection
245 // ------------------------------------------------------
247 {
249 
250  if (!cam)
251  {
252  cerr << "The user didn't pick any camera. Exiting." << endl;
253  return;
254  }
255 
256  mrpt::obs::CObservation::Ptr obs = cam->getNextFrame();
257  ASSERT_(obs);
258 
260  {
262  return;
263  }
264 
265  CDisplayWindow win("Live video");
266 
267  cout << "Close the window to exit." << endl;
268 
269  double counter = 0;
270  mrpt::system::CTicTac tictac;
271 
272  while (win.isOpen())
273  {
274  if (!counter) tictac.Tic();
275 
277  try
278  {
279  obs = cam->getNextFrame();
280  }
281  catch (CExceptionEOF&) // Check if eof, f.i. for RawLog files
282  {
283  break;
284  }
285  ASSERT_(obs);
286 
287  if (IS_CLASS(obs, CObservationImage))
288  {
289  vector_detectable_object detected;
290  faceDetector.detectObjects(obs, detected);
291 
293  std::dynamic_pointer_cast<CObservationImage>(obs);
294  for (unsigned int i = 0; i < detected.size(); i++)
295  {
296  ASSERT_(IS_CLASS(detected[i], CDetectable2D));
298  std::dynamic_pointer_cast<CDetectable2D>(detected[i]);
299  o->image.rectangle(
300  obj->m_x, obj->m_y, obj->m_x + obj->m_width,
301  obj->m_y + obj->m_height, TColor(255, 0, 0));
302  }
303 
304  win.showImage(o->image);
305  }
306  else if (IS_CLASS(obs, CObservationStereoImages))
307  {
308  vector_detectable_object detected;
309  faceDetector.detectObjects(obs, detected);
310 
312  std::dynamic_pointer_cast<CObservationStereoImages>(obs);
313 
314  for (unsigned int i = 0; i < detected.size(); i++)
315  {
316  ASSERT_(IS_CLASS(detected[i], CDetectable2D));
318  std::dynamic_pointer_cast<CDetectable2D>(detected[i]);
319  o->imageRight.rectangle(
320  obj->m_x, obj->m_y, obj->m_x + obj->m_width,
321  obj->m_y + obj->m_height, TColor(255, 0, 0));
322  }
323 
324  win.showImage(o->imageRight);
325  }
326 
327  if (++counter == 10)
328  {
329  double t = tictac.Tac();
330  cout << "Frame Rate: " << counter / t << " fps" << endl;
331  counter = 0;
332  }
333  std::this_thread::sleep_for(2ms);
334  }
335 
336  cout << "Closing..." << endl;
337 }
338 
339 // ------------------------------------------------------
340 // TestImagesFaceDetection
341 // ------------------------------------------------------
342 void TestImagesFaceDetection(int argc, char* argv[])
343 {
344  CImage img;
345  CDisplayWindow win("Result");
346  mrpt::system::CTicTac tictac;
347 
348  // For each aditional argument, tty to load an image and detect faces
349  for (int i = 1; i < argc; i++)
350  {
351  string fileName(argv[i]);
352 
353  if (!img.loadFromFile(myDataDir + fileName))
354  {
355  cerr << "Cannot load " << myDataDir + fileName << endl;
356  continue;
357  }
358 
359  vector_detectable_object detected;
360 
361  tictac.Tic();
362 
363  faceDetector.detectObjects(&img, detected);
364 
365  cout << "Detection time: " << tictac.Tac() << " s" << endl;
366 
367  for (unsigned int i = 0; i < detected.size(); i++)
368  {
369  ASSERT_(IS_CLASS(detected[i], CDetectable2D));
371  std::dynamic_pointer_cast<CDetectable2D>(detected[i]);
372  img.rectangle(
373  obj->m_x, obj->m_y, obj->m_x + obj->m_width,
374  obj->m_y + obj->m_height, TColor(255, 0, 0));
375  }
376 
377  win.showImage(img);
378 
380  }
381 }
382 
383 void BatchMode()
384 {
385  vector<double> frame_rates;
386 
387  for (size_t i = 0; i < rawlogs.size(); i++)
388  {
389  CRawlog rawlog;
390 
391  rawlog.loadFromRawLogFile(string(rawlogsDir + rawlogs[i] + ".rawlog"));
392 
393  cout << "Processing Rawlog [" << i + 1 << "/" << rawlogs.size()
394  << "]: " << rawlogs[i] << endl;
395 
396  const unsigned int size = rawlog.size();
397 
398  mrpt::system::CTicTac tictac;
399  size_t counter = 0;
400 
401  // PROCESS RAWLOG
402  for (unsigned int j = 1; j < size; j++)
403  {
404  if (!counter) tictac.Tic();
405 
407  std::dynamic_pointer_cast<CObservation3DRangeScan>(
408  rawlog.getAsObservation(j));
409 
410  ASSERT_(o);
411 
412  vector_detectable_object detected;
413 
414  faceDetector.detectObjects(o, detected);
415 
416  if (++counter == 10)
417  {
418  double t = tictac.Tac();
419  frame_rates.push_back(counter / t);
420  counter = 0;
421  }
422 
423  std::this_thread::sleep_for(2ms);
424  }
425 
426  unsigned int falsePositivesDeleted, realFacesDeleted;
428  falsePositives[i], ignored[i], falsePositivesDeleted,
429  realFacesDeleted);
430  cout << "False positives deleted: " << falsePositivesDeleted << endl;
431  cout << "Real faces delted: " << realFacesDeleted << endl << endl;
432  }
433 
434  cout << "Mean frame rate: " << sum(frame_rates) / frame_rates.size();
435 
436  // faceDetector.experimental_showMeasurements();
437 
438  system::pause();
439 }
440 
441 void mySplit(const string& str)
442 {
443  char *cstr, *p;
444 
445  cstr = new char[str.size() + 1];
446  strcpy(cstr, str.c_str());
447 
448  // cstr now contains a c-string copy of str
449 
450  p = strtok(cstr, " ");
451  while (p != nullptr)
452  {
453  string part(p);
454  rawlogs.push_back(part);
455  p = strtok(nullptr, " ");
456  }
457 
458  delete[] cstr;
459 }
460 
461 // ------------------------------------------------------
462 // TestPrepareDetector
463 // ------------------------------------------------------
464 void TestPrepareDetector()
465 {
466  CConfigFile cfg(myInitFile);
467 
468  int classifierType = cfg.read_int("Example", "classifierType", 0);
469 
470  if (classifierType == 0) // Haar
471  cfg.write(
472  "CascadeClassifier", "cascadeFileName",
474  "/data/haarcascades/haarcascade_frontalface_alt2.xml");
475  else if (classifierType == 1) // LBP
476  cfg.write(
477  "CascadeClassifier", "cascadeFileName",
478  OPENCV_SRC_DIR + "/data/lbpcascades/lbpcascade_frontalface.xml");
479  else
480  throw std::runtime_error("Incorrect cascade classifier type.");
481 
482  showEachDetectedFace = cfg.read_bool("Example", "showEachDetectedFace", 0);
483  batchMode = cfg.read_bool("Example", "batchMode", false);
484 
485  if (batchMode)
486  {
487  string str = cfg.read_string("Example", "rawlogs", "noRawlogs");
488  mySplit(str);
489 
490  size_t numRawlogs = rawlogs.size();
491  falsePositives.resize(numRawlogs);
492  ignored.resize(numRawlogs);
493 
494  for (size_t i = 0; i < numRawlogs; i++)
495  {
496  cfg.read_vector(
497  rawlogs[i], "falsePositives", std::vector<uint32_t>(),
498  falsePositives[i]);
499  cfg.read_vector(
500  rawlogs[i], "ignored", std::vector<uint32_t>(), ignored[i]);
501  }
502 
503  rawlogsDir = cfg.read_string("Example", "rawlogsDir", "");
504  }
505 
506  faceDetector.init(cfg);
507 }
508 
509 // ------------------------------------------------------
510 // MAIN
511 // ------------------------------------------------------
512 int main(int argc, char* argv[])
513 {
514  try
515  {
519 
521 
522  if (batchMode)
523  BatchMode();
524  else
525  {
526  if (argc > 1)
527  TestImagesFaceDetection(argc, argv);
528  else
530  }
531 
532  return 0;
533  }
534  catch (std::exception& e)
535  {
536  std::cout << "MRPT exception caught: " << e.what() << std::endl;
537  return -1;
538  }
539  catch (...)
540  {
541  printf("Untyped exception!!");
542  return -1;
543  }
544 }
double Tac() noexcept
Stops the stopwatch.
Definition: CTicTac.cpp:90
void unlockAccess3DScene()
Unlocks the access to the internal 3D scene.
static string OPENCV_SRC_DIR
Declares a class derived from "CObservation" that encapsules an image from a camera, whose relative pose to robot is also stored.
vector< string > rawlogs
GLdouble GLdouble t
Definition: glext.h:3689
void debug_returnResults(const std::vector< uint32_t > &falsePositives, const std::vector< uint32_t > &ignore, unsigned int &falsePositivesDeleted, unsigned int &realFacesDeleted)
CCameraSensor::Ptr prepareVideoSourceFromUserSelection()
Show to the user a list of possible camera drivers and creates and open the selected camera...
void setWindowTitle(const std::string &str) override
Changes the window title.
string rawlogsDir
mrpt::opengl::COpenGLScene::Ptr & get3DSceneAndLock()
Gets a reference to the smart shared pointer that holds the internal scene (carefuly read introductio...
void resize(unsigned int width, unsigned int height) override
Resizes the window, stretching the image to fit into the display area.
void setCameraPointingToPoint(float x, float y, float z)
Changes the camera parameters programmatically.
This class allows loading and storing values and vectors of different types from ".ini" files easily.
This file implements several operations that operate element-wise on individual or pairs of container...
A high-performance stopwatch, with typical resolution of nanoseconds.
std::string myDataDir
Declares a class derived from "CObservation" that encapsules a 3D range scan measurement, as from a time-of-flight range camera or any other RGBD sensor.
Column vector, like Eigen::MatrixX*, but automatically initialized to zeros since construction...
Definition: eigen_frwds.h:44
Contains classes for various device interfaces.
STL namespace.
std::vector< CDetectableObject::Ptr > vector_detectable_object
int counter
GLsizei GLsizei GLuint * obj
Definition: glext.h:4070
TColourOptions colorScheme
The options employed when inserting laser scans in the map.
vector< std::vector< uint32_t > > falsePositives
#define ASSERT_(f)
Defines an assertion mechanism.
Definition: exceptions.h:113
bool loadFromRawLogFile(const std::string &fileName, bool non_obs_objects_are_legal=false)
Load the contents from a file containing one of these possibilities:
Definition: CRawlog.cpp:190
This base provides a set of functions for maths stuff.
#define CLASS_ID(T)
Access to runtime class ID for a defined class name.
Definition: CObject.h:84
CObservation::Ptr getAsObservation(size_t index) const
Returns the i&#39;th element in the sequence, as being an observation, where index=0 is the first object...
Definition: CRawlog.cpp:105
const GLubyte * c
Definition: glext.h:6313
void setAllPoints(const std::vector< float > &X, const std::vector< float > &Y, const std::vector< float > &Z)
Set all the points at once from vectors with X,Y and Z coordinates.
Definition: CPointsMap.h:653
GLint GLvoid * img
Definition: glext.h:3763
This class creates a window as a graphical user interface (GUI) for displaying images to the user...
char * strtok(char *str, const char *strDelimit, char **context) noexcept
An OS-independent method for tokenizing a string.
CONTAINER::Scalar sum(const CONTAINER &v)
Computes the sum of all the elements.
virtual void init(const mrpt::config::CConfigFileBase &cfg)
Initialize the object with parameters loaded from the given config source.
Observation class for either a pair of left+right or left+disparity images from a stereo camera...
This class stores a rawlog (robotic datasets) in one of two possible formats:
Definition: CRawlog.h:66
This namespace contains representation of robot actions and observations.
void TestPrepareDetector()
Specific class for face detection.
A map of 2D/3D points with individual colours (RGB).
mrpt::gui::CDisplayWindow3D::Ptr win
void pause(const std::string &msg=std::string("Press any key to continue...")) noexcept
Shows the message "Press any key to continue" (or other custom message) to the current standard outpu...
Definition: os.cpp:428
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
CSetOfObjects::Ptr CornerXYZ(float scale=1.0)
Returns three arrows representing a X,Y,Z 3D corner.
#define IS_CLASS(ptrObj, class_name)
Evaluates to true if the given pointer to an object (derived from mrpt::rtti::CObject) is of the give...
Definition: CObject.h:102
virtual void loadFromRangeScan(const mrpt::obs::CObservation2DRangeScan &rangeScan, const mrpt::poses::CPose3D *robotPose=nullptr) override
See CPointsMap::loadFromRangeScan()
void setCameraZoom(float zoom)
Changes the camera parameters programmatically.
void registerClass(const mrpt::rtti::TRuntimeClassId *pNewClass)
Register a class into the MRPT internal list of "CObject" descendents.
Classes for creating GUI windows for 2D and 3D visualization.
Definition: about_box.h:14
vector< std::vector< uint32_t > > ignored
GLsizeiptr size
Definition: glext.h:3923
A RGB color - 8bit.
Definition: TColor.h:20
void TestCamera3DFaceDetection(CCameraSensor::Ptr cam)
void Tic() noexcept
Starts the stopwatch.
Definition: CTicTac.cpp:79
void repaint()
Repaints the window.
char * strcpy(char *dest, size_t destSize, const char *source) noexcept
An OS-independent version of strcpy.
Definition: os.cpp:297
CFaceDetection faceDetector
void TestImagesFaceDetection(int argc, char *argv[])
string myInitFile(MRPT_EXAMPLES_BASE_DIRECTORY+string("detectors_face/FACE_DETECTION_TEST.INI"))
size_t size() const
Returns the number of actions / observations object in the sequence.
Definition: CRawlog.cpp:88
GLfloat GLfloat p
Definition: glext.h:6305
void detectObjects(const mrpt::obs::CObservation::Ptr obs, vector_detectable_object &detected)
struct mrpt::detectors::CFaceDetection::TOptions m_options
Base class that contains common atributes and functions of detectable objects.
void TestCameraFaceDetection()
void mySplit(const string &str)
void setCameraAzimuthDeg(float deg)
Changes the camera parameters programmatically.
GLenum GLuint GLint GLenum face
Definition: glext.h:8194
A class for storing images as grayscale or RGB bitmaps.
Definition: img/CImage.h:130
Used in mrpt::serialization::CArchive.
Definition: CArchive.h:34
void setCameraElevationDeg(float deg)
Changes the camera parameters programmatically.
A graphical user interface (GUI) for efficiently rendering 3D scenes in real-time.
bool showEachDetectedFace



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 7d5e6d718 Fri Aug 24 01:51:28 2018 +0200 at lun nov 2 08:35:50 CET 2020