Main MRPT website > C++ reference for 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 /* ------------------------------------------------------
11  rgbd2rawlog
12  A small tool to translate RGB+D datasets from TUM:
13  http://cvpr.in.tum.de/data/datasets/rgbd-dataset/
14 
15  into MRPT rawlog binary format, ready to be parsed
16  by RawLogViewer or user programs.
17 
18 Usage:
19  rgbd_dataset2rawlog [PATH_TO_RGBD_DATASET] [OUTPUT_NAME]
20 
21 Where expected input files are:
22  - PATH_TO_RGBD_DATASET/accelerometer.txt
23  - PATH_TO_RGBD_DATASET/depth.txt
24  - PATH_TO_RGBD_DATASET/rgb.txt
25  - PATH_TO_RGBD_DATASET/rgb/... (Images, 3x8u)
26  - PATH_TO_RGBD_DATASET/depth/... (Images, 1x16u)
27 
28 Output files:
29  - OUTPUT_NAME.rawlog: The output rawlog file.
30  - OUTPUT_NAME_Images/...: External RGB images.
31 
32  ------------------------------------------------------ */
33 
34 #include <mrpt/system/filesystem.h>
40 #include <iostream>
41 
42 using namespace std;
43 using namespace mrpt;
44 using namespace mrpt::obs;
45 using namespace mrpt::serialization;
46 
47 const double KINECT_FPS = 30.0;
48 
49 // Based on:
50 // http://stackoverflow.com/questions/218488/finding-best-matching-key-for-a-given-key-in-a-sorted-stl-container
51 template <class CONTAINER>
53  const CONTAINER& data, const typename CONTAINER::key_type& searchkey)
54 {
55  typename CONTAINER::const_iterator upper = data.lower_bound(searchkey);
56  if (upper == data.begin() || upper->first == searchkey) return upper;
57  typename CONTAINER::const_iterator lower = upper;
58  --lower;
59  if (upper == data.end() ||
60  (searchkey - lower->first) < (upper->first - searchkey))
61  return lower;
62  return upper;
63 }
64 
65 void rgbd2rawlog(const string& src_path, const string& out_name)
66 {
67  const string in_fil_acc = src_path + string("/accelerometer.txt");
68  const string in_fil_depth =
69  mrpt::system::fileExists(src_path + string("/ir.txt"))
70  ? src_path + string("/ir.txt")
71  : src_path + string("/depth.txt");
72  const string in_fil_rgb = src_path + string("/rgb.txt");
73 
74  // ASSERT_FILE_EXISTS_(in_fil_acc)
75  // ASSERT_FILE_EXISTS_(in_fil_depth)
76  // ASSERT_FILE_EXISTS_(in_fil_rgb)
77 
78  // make a list with RGB & DEPTH files ------------------------
79  map<double, string> list_rgb, list_depth;
80  map<double, vector<double>> list_acc;
81  std::istringstream line;
82  if (mrpt::system::fileExists(in_fil_rgb))
83  {
84  mrpt::io::CTextFileLinesParser fparser(in_fil_rgb);
85  while (fparser.getNextLine(line))
86  {
87  double tim;
88  string f;
89  if (line >> tim >> f) list_rgb[tim] = f;
90  }
91  }
92  if (mrpt::system::fileExists(in_fil_depth))
93  {
94  mrpt::io::CTextFileLinesParser fparser(in_fil_depth);
95  while (fparser.getNextLine(line))
96  {
97  double tim;
98  string f;
99  if (line >> tim >> f) list_depth[tim] = f;
100  }
101  }
102  if (mrpt::system::fileExists(in_fil_acc))
103  {
104  mrpt::io::CTextFileLinesParser fparser(in_fil_acc);
105  while (fparser.getNextLine(line))
106  {
107  double tim;
108  double ax, ay, az;
109  if (line >> tim >> ax >> ay >> az)
110  {
111  vector<double>& v = list_acc[tim];
112  v.resize(3);
113  v[0] = ax;
114  v[1] = ay;
115  v[2] = az;
116  }
117  }
118  }
119  cout << "Parsed: " << list_depth.size() << " / " << list_rgb.size() << " / "
120  << list_acc.size() << " depth/rgb/acc entries.\n";
121 
122  const bool only_ir = list_depth.size() > 10 && list_rgb.empty();
123  const bool only_rgb = list_depth.empty() && list_rgb.size() > 10;
124 
125  // Create output directory for images ------------------------------
126  const string out_img_dir = out_name + string("_Images");
127 
128  cout << "Creating images directory: " << out_img_dir << endl;
129  mrpt::system::createDirectory(out_img_dir);
130 
131  // Create rawlog file ----------------------------------------------
132  const string out_rawlog_fil = out_name + string(".rawlog");
133  cout << "Creating rawlog: " << out_rawlog_fil << endl;
134  mrpt::io::CFileGZOutputStream f_out(out_rawlog_fil);
135 
136  // Fill out the common field to all entries:
138  obs.sensorLabel = "KINECT";
139  obs.range_is_depth = true; // Kinect style: ranges are actually depth
140  // values, not Euclidean distances.
141 
142  // Range & RGB images are already registered and warped to remove
143  // distortion:
144  const double FOCAL = 525.0;
145  obs.cameraParams.nrows = 640;
146  obs.cameraParams.ncols = 480;
147  obs.cameraParams.fx(FOCAL);
148  obs.cameraParams.fy(FOCAL);
149  obs.cameraParams.cx(319.5);
150  obs.cameraParams.cy(239.5);
153  0, 0, 0, mrpt::DEG2RAD(-90), 0,
154  mrpt::DEG2RAD(-90)); // No translation between rgb & range
155  // cameras, and rotation only due to XYZ
156  // axes conventions.
157 
158  CObservationIMU obs_imu;
159  obs_imu.sensorLabel = "KINECT_ACC";
160  obs_imu.dataIsPresent[IMU_X_ACC] = true;
161  obs_imu.dataIsPresent[IMU_Y_ACC] = true;
162  obs_imu.dataIsPresent[IMU_Z_ACC] = true;
163 
164  // Go thru the data:
165  unsigned int counter = 0;
166  if (!only_ir && !only_rgb)
167  {
168  for (map<double, string>::const_iterator it_list_rgb = list_rgb.begin();
169  it_list_rgb != list_rgb.end(); ++it_list_rgb)
170  {
171  cout << "Processing image " << counter << "\r";
172  cout.flush();
173  counter++;
174 
175  // This is not the most efficient solution in the world, but...come
176  // on! it's just a rawlog converter tool!
178  find_closest(list_depth, it_list_rgb->first);
179 
180  const double At =
181  std::abs(it_list_rgb->first - it_list_depth->first);
182  if (At > (1. / KINECT_FPS) * .5)
183  {
184  cout << "\nWarning: Discarding observation for too separated "
185  "RGB/D timestamps: "
186  << At * 1e3 << " ms\n";
187  }
188  else
189  {
190  // OK, we accept this RGB-DEPTH pair:
191  const double avrg_time =
192  .5 * (it_list_rgb->first + it_list_depth->first);
194 
195  // RGB img:
196  obs.hasIntensityImage = true;
198  src_path + string("/") + it_list_rgb->second);
199  const string sRGBfile =
200  mrpt::format("%.06f_rgb.png", avrg_time);
202  out_img_dir + string("/") + sRGBfile);
203  obs.intensityImage.setExternalStorage(sRGBfile);
204 
205  // Depth:
206  obs.hasRangeImage = true;
208  mrpt::img::CImage depth_img;
209  if (!depth_img.loadFromFile(
210  src_path + string("/") + it_list_depth->second))
211  throw std::runtime_error(
212  string("Error loading depth image!: ") +
213  it_list_depth->second);
214 
215  const unsigned int w = depth_img.getWidth();
216  const unsigned int h = depth_img.getHeight();
217  obs.rangeImage_setSize(h, w);
218 
219  for (unsigned int row = 0; row < h; row++)
220  {
221  const uint16_t* ptr = reinterpret_cast<const uint16_t*>(
222  depth_img.get_unsafe(0, row));
223  for (unsigned int col = 0; col < w; col++)
224  obs.rangeImage(row, col) = (*ptr++) * (1. / 5000);
225  }
226 
227  const string sDepthfile =
228  mrpt::format("%.06f_depth.bin", avrg_time);
230  sDepthfile, out_img_dir + string("/"));
231 
232  // save:
233  archiveFrom(f_out) << obs;
234 
235  // Search for acc data:
236  map<double, vector<double>>::const_iterator it_list_acc =
237  find_closest(list_acc, avrg_time);
238  const double At_acc =
239  std::abs(it_list_rgb->first - it_list_acc->first);
240  if (At_acc < 1e-2)
241  {
242  obs_imu.timestamp =
244 
245  obs_imu.rawMeasurements[IMU_X_ACC] = it_list_acc->second[0];
246  obs_imu.rawMeasurements[IMU_Y_ACC] = it_list_acc->second[1];
247  obs_imu.rawMeasurements[IMU_Z_ACC] = it_list_acc->second[2];
248 
249  archiveFrom(f_out) << obs_imu;
250  }
251  }
252  }
253  }
254  else if (only_ir)
255  {
256  for (map<double, string>::const_iterator it_list_depth =
257  list_depth.begin();
258  it_list_depth != list_depth.end(); ++it_list_depth)
259  {
260  cout << "Processing image " << counter << "\r";
261  cout.flush();
262  counter++;
263 
264  const double avrg_time = it_list_depth->first;
265  obs.timestamp =
266  mrpt::system::time_tToTimestamp(it_list_depth->first);
267 
268  // Depth:
269  obs.hasRangeImage = true;
271  mrpt::img::CImage depth_img;
272  if (!depth_img.loadFromFile(
273  src_path + string("/") + it_list_depth->second))
274  throw std::runtime_error(
275  string("Error loading depth image!: ") +
276  it_list_depth->second);
277 
278  const unsigned int w = depth_img.getWidth();
279  const unsigned int h = depth_img.getHeight();
280  obs.rangeImage_setSize(h, w);
281 
282  for (unsigned int row = 0; row < h; row++)
283  {
284  const uint16_t* ptr = reinterpret_cast<const uint16_t*>(
285  depth_img.get_unsafe(0, row));
286  for (unsigned int col = 0; col < w; col++)
287  obs.rangeImage(row, col) = (*ptr++) * (1. / 5000);
288  }
289 
290  const string sDepthfile =
291  mrpt::format("%.06f_depth.bin", avrg_time);
293  sDepthfile, out_img_dir + string("/"));
294 
295  // save:
296  archiveFrom(f_out) << obs;
297  }
298  }
299  else if (only_rgb)
300  {
301  for (map<double, string>::const_iterator it_list_rgb = list_rgb.begin();
302  it_list_rgb != list_rgb.end(); ++it_list_rgb)
303  {
304  cout << "Processing image " << counter << "\r";
305  cout.flush();
306  counter++;
307 
308  const double avrg_time = it_list_rgb->first;
309  obs.timestamp = mrpt::system::time_tToTimestamp(it_list_rgb->first);
310 
311  // RGB img:
312  obs.hasIntensityImage = true;
314  src_path + string("/") + it_list_rgb->second);
315  const string sRGBfile = mrpt::format("%.06f_rgb.png", avrg_time);
316  obs.intensityImage.saveToFile(out_img_dir + string("/") + sRGBfile);
317  obs.intensityImage.setExternalStorage(sRGBfile);
318 
319  // save:
320  archiveFrom(f_out) << obs;
321  }
322  }
323 
324  cout << "\nAll done!\n";
325 }
326 
327 // ------------------------------------------------------
328 // MAIN
329 // ------------------------------------------------------
330 int main(int argc, char** argv)
331 {
332  try
333  {
334  if (argc != 3)
335  {
336  cerr << "Usage: " << argv[0]
337  << " [PATH_TO_RGBD_DATASET] [OUTPUT_NAME]\n";
338  return 1;
339  }
340 
341  rgbd2rawlog(argv[1], argv[2]);
342 
343  return 0;
344  }
345  catch (std::exception& e)
346  {
347  std::cout << "MRPT exception caught: " << e.what() << std::endl;
348  return -1;
349  }
350  catch (...)
351  {
352  printf("Untyped exception!!");
353  return -1;
354  }
355 }
filesystem.h
mrpt::obs::CObservation::sensorLabel
std::string sensorLabel
An arbitrary label that can be used to identify the sensor.
Definition: CObservation.h:62
mrpt::obs::CObservationIMU::rawMeasurements
std::vector< double > rawMeasurements
The accelerometer and/or gyroscope measurements taken by the IMU at the given timestamp.
Definition: CObservationIMU.h:138
mrpt::img::CImage::getWidth
size_t getWidth() const override
Returns the width of the image in pixels.
Definition: CImage.cpp:864
mrpt::obs::CObservation3DRangeScan::range_is_depth
bool range_is_depth
true: Kinect-like ranges: entries of rangeImage are distances along the +X axis; false: Ranges in ran...
Definition: CObservation3DRangeScan.h:448
const_iterator
const Scalar * const_iterator
Definition: eigen_plugins.h:27
uint16_t
unsigned __int16 uint16_t
Definition: rptypes.h:44
mrpt::system::time_tToTimestamp
mrpt::system::TTimeStamp time_tToTimestamp(const double t)
Transform from standard "time_t" (actually a double number, it can contain fractions of seconds) to T...
Definition: datetime.cpp:50
mrpt::obs::CObservation3DRangeScan::cameraParamsIntensity
mrpt::img::TCamera cameraParamsIntensity
Projection parameters of the intensity (graylevel or RGB) camera.
Definition: CObservation3DRangeScan.h:721
mrpt::img::TCamera::fx
double fx() const
Get the value of the focal length x-value (in pixels).
Definition: TCamera.h:165
CTextFileLinesParser.h
mrpt::img::TCamera::ncols
uint32_t ncols
Camera resolution.
Definition: TCamera.h:41
CFileGZOutputStream.h
CObservation3DRangeScan.h
mrpt
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
Definition: CKalmanFilterCapable.h:30
w
GLubyte GLubyte GLubyte GLubyte w
Definition: glext.h:4178
mrpt::obs::CObservationIMU
This class stores measurements from an Inertial Measurement Unit (IMU) (attitude estimation,...
Definition: CObservationIMU.h:108
mrpt::system::fileExists
bool fileExists(const std::string &fileName)
Test if a given file (or directory) exists.
Definition: filesystem.cpp:127
mrpt::obs::CObservation3DRangeScan::rangeImage_setSize
void rangeImage_setSize(const int HEIGHT, const int WIDTH)
Similar to calling "rangeImage.setSize(H,W)" but this method provides memory pooling to speed-up the ...
Definition: CObservation3DRangeScan.cpp:908
mrpt::img::TCamera::cy
double cy() const
Get the value of the principal point y-coordinate (in pixels).
Definition: TCamera.h:163
mrpt::obs
This namespace contains representation of robot actions and observations.
Definition: CParticleFilter.h:17
mrpt::obs::CObservation::timestamp
mrpt::system::TTimeStamp timestamp
The associated UTC time-stamp.
Definition: CObservation.h:60
mrpt::obs::CObservation3DRangeScan::cameraParams
mrpt::img::TCamera cameraParams
Projection parameters of the depth camera.
Definition: CObservation3DRangeScan.h:719
KINECT_FPS
const double KINECT_FPS
Definition: vision_stereo_rectify/test.cpp:47
v
const GLdouble * v
Definition: glext.h:3678
main
int main()
Definition: vision_stereo_rectify/test.cpp:78
mrpt::img::TCamera::fy
double fy() const
Get the value of the focal length y-value (in pixels).
Definition: TCamera.h:167
mrpt::obs::CObservation3DRangeScan::relativePoseIntensityWRTDepth
mrpt::poses::CPose3D relativePoseIntensityWRTDepth
Relative pose of the intensity camera wrt the depth camera (which is the coordinates origin for this ...
Definition: CObservation3DRangeScan.h:731
data
GLsizei GLsizei GLenum GLenum const GLvoid * data
Definition: glext.h:3547
mrpt::obs::CObservation3DRangeScan::intensityImage
mrpt::img::CImage intensityImage
If hasIntensityImage=true, a color or gray-level intensity image of the same size than "rangeImage".
Definition: CObservation3DRangeScan.h:502
mrpt::obs::CObservation3DRangeScan
Declares a class derived from "CObservation" that encapsules a 3D range scan measurement,...
Definition: CObservation3DRangeScan.h:224
rgbd2rawlog
void rgbd2rawlog(const string &src_path, const string &out_name)
Definition: vision_stereo_rectify/test.cpp:65
mrpt::img::TCamera::cx
double cx() const
Get the value of the principal point x-coordinate (in pixels).
Definition: TCamera.h:161
mrpt::obs::IMU_Z_ACC
@ IMU_Z_ACC
z-axis acceleration (local/vehicle frame) (m/sec2)
Definition: CObservationIMU.h:33
find_closest
CONTAINER::const_iterator find_closest(const CONTAINER &data, const typename CONTAINER::key_type &searchkey)
Definition: vision_stereo_rectify/test.cpp:52
mrpt::format
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
Definition: format.cpp:16
mrpt::img::TCamera::nrows
uint32_t nrows
Definition: TCamera.h:41
mrpt::io::CFileGZOutputStream
Saves data to a file and transparently compress the data using the given compression level.
Definition: io/CFileGZOutputStream.h:26
mrpt::poses::CPose3D
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
Definition: CPose3D.h:88
mrpt::obs::CObservation3DRangeScan::hasIntensityImage
bool hasIntensityImage
true means the field intensityImage contains valid data
Definition: CObservation3DRangeScan.h:499
mrpt::obs::CObservation3DRangeScan::hasRangeImage
bool hasRangeImage
true means the field rangeImage contains valid data
Definition: CObservation3DRangeScan.h:441
mrpt::img::CImage::get_unsafe
unsigned char * get_unsafe(unsigned int col, unsigned int row, unsigned int channel=0) const
Access to pixels without checking boundaries - Use normally the () operator better,...
Definition: CImage.cpp:491
mrpt::obs::IMU_X_ACC
@ IMU_X_ACC
x-axis acceleration (local/vehicle frame) (m/sec2)
Definition: CObservationIMU.h:29
mrpt::serialization
Definition: aligned_serialization.h:14
mrpt::img::CImage
A class for storing images as grayscale or RGB bitmaps.
Definition: img/CImage.h:130
mrpt::obs::CObservationIMU::dataIsPresent
std::vector< bool > dataIsPresent
Each entry in this vector is true if the corresponding data index contains valid data (the IMU unit s...
Definition: CObservationIMU.h:132
CObservationIMU.h
mrpt::img::CImage::saveToFile
bool saveToFile(const std::string &fileName, int jpeg_quality=95) const
Save the image to a file, whose format is determined from the extension (internally uses OpenCV).
Definition: CImage.cpp:296
mrpt::serialization::archiveFrom
CArchiveStreamBase< STREAM > archiveFrom(STREAM &s)
Helper function to create a templatized wrapper CArchive object for a: MRPT's CStream,...
Definition: CArchive.h:561
mrpt::obs::IMU_Y_ACC
@ IMU_Y_ACC
y-axis acceleration (local/vehicle frame) (m/sec2)
Definition: CObservationIMU.h:31
mrpt::obs::CObservation3DRangeScan::rangeImage
mrpt::math::CMatrix rangeImage
If hasRangeImage=true, a matrix of floats with the range data as captured by the camera (in meters)
Definition: CObservation3DRangeScan.h:444
mrpt::img::CImage::getHeight
size_t getHeight() const override
Returns the height of the image in pixels.
Definition: CImage.cpp:892
row
GLenum GLenum GLvoid * row
Definition: glext.h:3576
mrpt::img::CImage::setExternalStorage
void setExternalStorage(const std::string &fileName) noexcept
By using this method the image is marked as referenced to an external file, which will be loaded only...
Definition: CImage.cpp:1887
mrpt::obs::CObservation3DRangeScan::rangeImage_convertToExternalStorage
void rangeImage_convertToExternalStorage(const std::string &fileName, const std::string &use_this_base_dir)
Users won't normally want to call this, it's only used from internal MRPT programs.
Definition: CObservation3DRangeScan.cpp:586
mrpt::io::CTextFileLinesParser
A class for parsing text files, returning each non-empty and non-comment line, along its line number.
Definition: CTextFileLinesParser.h:26
string
GLsizei const GLchar ** string
Definition: glext.h:4101
CArchive.h
mrpt::system::createDirectory
bool createDirectory(const std::string &dirName)
Creates a directory.
Definition: filesystem.cpp:158
mrpt::img::CImage::loadFromFile
bool loadFromFile(const std::string &fileName, int isColor=-1)
Load image from a file, whose format is determined from the extension (internally uses OpenCV).
Definition: CImage.cpp:271
mrpt::obs::CObservation3DRangeScan::rangeImage_forceResetExternalStorage
void rangeImage_forceResetExternalStorage()
Forces marking this observation as non-externally stored - it doesn't anything else apart from reseti...
Definition: CObservation3DRangeScan.h:481
mrpt::DEG2RAD
double DEG2RAD(const double x)
Degrees to radians.
Definition: core/include/mrpt/core/bits_math.h:42



Page generated by Doxygen 1.8.17 for MRPT 1.9.9 Git: ad3a9d8ae Tue May 1 23:10:22 2018 -0700 at miƩ 12 jul 2023 10:03:34 CEST