Visual Servoing Platform  version 3.6.1 under development (2024-07-27)
readRealSenseData.cpp
1 /****************************************************************************
2  *
3  * ViSP, open source Visual Servoing Platform software.
4  * Copyright (C) 2005 - 2023 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 https://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 *****************************************************************************/
32 
39 #include <iostream>
40 
41 #include <visp3/core/vpConfig.h>
42 
43 #if defined(VISP_HAVE_THREADS) && (defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI))
44 #include <condition_variable>
45 #include <fstream>
46 #include <mutex>
47 #include <queue>
48 #include <thread>
49 
50 #include <visp3/core/vpImageConvert.h>
51 #include <visp3/core/vpIoException.h>
52 #include <visp3/core/vpIoTools.h>
53 #include <visp3/gui/vpDisplayGDI.h>
54 #include <visp3/gui/vpDisplayX.h>
55 #include <visp3/gui/vpDisplayPCL.h>
56 #include <visp3/io/vpImageIo.h>
57 #include <visp3/io/vpParseArgv.h>
58 #include <visp3/io/vpVideoWriter.h>
59 
60 #if defined(VISP_HAVE_PCL)
61 #include <pcl/pcl_config.h>
62 #if defined(VISP_HAVE_PCL_COMMON)
63 #include <pcl/point_types.h>
64 #include <pcl/point_cloud.h>
65 #endif
66 #if defined(VISP_HAVE_PCL_IO)
67 #include <pcl/io/pcd_io.h>
68 #endif
69 #endif
70 
71 #ifdef VISP_HAVE_MINIZ
72 #define GETOPTARGS "ci:e:jbzodh"
73 #else
74 #define GETOPTARGS "ci:e:jbodh"
75 #endif
76 
77 #ifdef ENABLE_VISP_NAMESPACE
78 using namespace VISP_NAMESPACE_NAME;
79 #endif
80 
81 namespace
82 {
83 
84 void usage(const char *name, const char *badparam)
85 {
86  std::cout << "\nNAME " << std::endl
87  << " " << vpIoTools::getName(name)
88  << " - Read data acquired with a Realsense device." << std::endl
89  << std::endl
90  << "SYNOPSIS " << std::endl
91  << " " << name
92  << " [-i <directory>]"
93  << " [-e <filename pattern (e.g. %04d)>]"
94  << " [-c]"
95  << " [-j]"
96  << " [-b]"
97 #ifdef VISP_HAVE_MINIZ
98  << " [-z]"
99 #endif
100  << " [-o]"
101  << " [-d]"
102  << " [--help,-h]"
103  << std::endl;
104  std::cout << "\nOPTIONS " << std::endl
105  << " -i <directory>" << std::endl
106  << " Input folder that contains the data to read." << std::endl
107  << std::endl
108  << " -e <pattern>" << std::endl
109  << " Filename pattern, e.g. %04d." << std::endl
110  << std::endl
111  << " -c" << std::endl
112  << " Flag to display data in step by step mode triggered by a user click." << std::endl
113  << std::endl
114  << " -j" << std::endl
115  << " Image data are saved in JPEG format, otherwise in PNG." << std::endl
116  << std::endl
117  << " -b" << std::endl
118  << " Depth and Pointcloud streams are saved in binary format." << std::endl
119  << std::endl
120 #ifdef VISP_HAVE_MINIZ
121  << " -z" << std::endl
122  << " Pointcloud stream is saved in NPZ format." << std::endl
123  << std::endl
124 #endif
125  << " -o" << std::endl
126  << " Save color images in PNG format (lossless) in a new folder." << std::endl
127  << std::endl
128  << " -d" << std::endl
129  << " Display depth in color." << std::endl
130  << std::endl
131  << " --help, -h" << std::endl
132  << " Display this helper message." << std::endl
133  << std::endl;
134 
135  if (badparam) {
136  std::cout << "\nERROR: Bad parameter " << badparam << std::endl;
137  }
138 }
139 
140 bool getOptions(int argc, const char *argv[], std::string &input_directory, std::string &pattern, bool &click,
141  bool &force_binary_format, bool &read_jpeg, bool &read_npz, bool &save_video, bool &color_depth)
142 {
143  const char *optarg;
144  const char **argv1 = (const char **)argv;
145  int c;
146  while ((c = vpParseArgv::parse(argc, argv1, GETOPTARGS, &optarg)) > 1) {
147 
148  switch (c) {
149  case 'i':
150  input_directory = optarg;
151  break;
152  case 'e':
153  pattern = optarg;
154  break;
155  case 'c':
156  click = true;
157  break;
158  case 'j':
159  read_jpeg = true;
160  break;
161  case 'b':
162  force_binary_format = true;
163  break;
164 #ifdef VISP_HAVE_MINIZ
165  case 'z':
166  read_npz = true;
167  break;
168 #endif
169  case 'o':
170  save_video = true;
171  break;
172  case 'd':
173  color_depth = true;
174  break;
175 
176  case 'h':
177  usage(argv[0], nullptr);
178  return false;
179  break;
180 
181  default:
182  usage(argv[0], optarg);
183  return false;
184  break;
185  }
186  }
187 
188  if ((c == 1) || (c == -1)) {
189  // standalone param or error
190  usage(argv[0], nullptr);
191  std::cerr << "ERROR: " << std::endl;
192  std::cerr << " Bad argument " << optarg << std::endl << std::endl;
193  return false;
194  }
195 
196  return true;
197 }
198 
199 bool readData(int cpt, const std::string &input_directory, const std::string &pattern, vpImage<vpRGBa> &I_color,
200  vpImage<uint16_t> &I_depth_raw, bool force_binary_format, bool read_jpeg, bool read_npz
201 #if defined(VISP_HAVE_PCL) && defined(VISP_HAVE_PCL_COMMON)
202  , pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud
203 #endif
204 )
205 {
206  std::string image_filename_ext = read_jpeg ? ".jpg" : ".png";
207  std::string depth_filename_ext = force_binary_format ? ".bin" : ".npz";
208  char buffer[FILENAME_MAX];
209  std::stringstream ss;
210  ss << input_directory << "/color_image_" << pattern << image_filename_ext;
211  snprintf(buffer, FILENAME_MAX, ss.str().c_str(), cpt);
212  std::string filename_color = buffer;
213 
214  ss.str("");
215  ss << input_directory << "/depth_image_" << pattern << depth_filename_ext;
216  snprintf(buffer, FILENAME_MAX, ss.str().c_str(), cpt);
217  std::string filename_depth = buffer;
218 
219  ss.str("");
220  ss << input_directory << "/point_cloud_" << pattern << (force_binary_format ? ".bin" :
221  (read_npz ? ".npz" : ".pcd"));
222  snprintf(buffer, FILENAME_MAX, ss.str().c_str(), cpt);
223  std::string filename_pointcloud = buffer;
224 
225  if (!vpIoTools::checkFilename(filename_color) && !vpIoTools::checkFilename(filename_depth) &&
226  !vpIoTools::checkFilename(filename_pointcloud)) {
227  std::cerr << "End of sequence." << std::endl;
228  return false;
229  }
230 
231  // Read color
232  if (vpIoTools::checkFilename(filename_color)) {
233  vpImageIo::read(I_color, filename_color);
234  }
235 
236  // Read raw depth
237  if (vpIoTools::checkFilename(filename_depth)) {
238  if (force_binary_format) {
239  std::ifstream file_depth(filename_depth.c_str(), std::ios::in | std::ios::binary);
240  if (file_depth.is_open()) {
241  unsigned int height = 0, width = 0;
242  vpIoTools::readBinaryValueLE(file_depth, height);
243  vpIoTools::readBinaryValueLE(file_depth, width);
244  I_depth_raw.resize(height, width);
245 
246  uint16_t depth_value = 0;
247  for (unsigned int i = 0; i < height; i++) {
248  for (unsigned int j = 0; j < width; j++) {
249  vpIoTools::readBinaryValueLE(file_depth, depth_value);
250  I_depth_raw[i][j] = depth_value;
251  }
252  }
253  }
254  }
255 #ifdef VISP_HAVE_MINIZ
256  else {
257  visp::cnpy::npz_t npz_data = visp::cnpy::npz_load(filename_depth);
258 
259  // Load depth data
260  visp::cnpy::NpyArray arr_depth_data = npz_data["data"];
261  if (arr_depth_data.data_holder == nullptr) {
262  throw vpIoException(vpIoException::ioError, "Loaded NPZ data is null.");
263  }
264 
265  uint16_t *depth_data_ptr = arr_depth_data.data<uint16_t>();
266  assert(arr_depth_data.shape.size() == 3); // H x W x C
267  assert(arr_depth_data.shape[2] == 1); // Single channel
268 
269  unsigned int height = static_cast<unsigned int>(arr_depth_data.shape[0]);
270  unsigned int width = static_cast<unsigned int>(arr_depth_data.shape[1]);
271  const bool copyData = true;
272  I_depth_raw = vpImage<uint16_t>(depth_data_ptr, height, width, copyData);
273  }
274 #else
275  else {
276  throw(vpIoException(vpIoException::ioError, "Cannot open non-binary depth file when npz I/O functions are disabled."));
277  }
278 #endif
279  }
280 
281  // Read pointcloud
282  if (vpIoTools::checkFilename(filename_pointcloud)) {
283 #if defined(VISP_HAVE_PCL)
284  // TODO: not tested
285  if (force_binary_format) {
286  std::ifstream file_pointcloud(filename_pointcloud.c_str(), std::ios::in | std::ios::binary);
287  if (!file_pointcloud.is_open()) {
288  std::cerr << "Cannot read pointcloud file: " << filename_pointcloud << std::endl;
289  }
290 
291  uint32_t height = 0, width = 0;
292  const char is_dense = 1;
293  vpIoTools::readBinaryValueLE(file_pointcloud, height);
294  vpIoTools::readBinaryValueLE(file_pointcloud, width);
295  file_pointcloud.read((char *)(&is_dense), sizeof(is_dense));
296 
297  point_cloud->width = width;
298  point_cloud->height = height;
299  point_cloud->is_dense = (is_dense != 0);
300  point_cloud->resize((size_t)width * height);
301 
302  float x = 0.0f, y = 0.0f, z = 0.0f;
303  for (uint32_t i = 0; i < height; i++) {
304  for (uint32_t j = 0; j < width; j++) {
305  vpIoTools::readBinaryValueLE(file_pointcloud, x);
306  vpIoTools::readBinaryValueLE(file_pointcloud, y);
307  vpIoTools::readBinaryValueLE(file_pointcloud, z);
308 
309  point_cloud->points[(size_t)(i * width + j)].x = x;
310  point_cloud->points[(size_t)(i * width + j)].y = y;
311  point_cloud->points[(size_t)(i * width + j)].z = z;
312  }
313  }
314  }
315 #ifdef VISP_HAVE_MINIZ
316  else if (read_npz) {
317  visp::cnpy::npz_t npz_data = visp::cnpy::npz_load(filename_pointcloud);
318 
319  // Load pointcloud data
320  visp::cnpy::NpyArray arr_pcl_data = npz_data["data"];
321  if (arr_pcl_data.data_holder == nullptr) {
322  throw vpIoException(vpIoException::ioError, "Loaded NPZ data is null.");
323  }
324 
325  float *pcl_data_ptr = arr_pcl_data.data<float>();
326  assert(arr_pcl_data.shape.size() == 3); // H x W x C
327  assert(arr_pcl_data.shape[2] == 3); // 3-channels: X, Y, Z
328 
329  uint32_t height = arr_pcl_data.shape[0], width = arr_pcl_data.shape[1];
330  const char is_dense = 1;
331 
332  point_cloud->width = width;
333  point_cloud->height = height;
334  point_cloud->is_dense = (is_dense != 0);
335  point_cloud->resize((size_t)width * height);
336 
337  for (uint32_t i = 0; i < height; i++) {
338  for (uint32_t j = 0; j < width; j++) {
339  point_cloud->points[(size_t)(i * width + j)].x = pcl_data_ptr[(size_t)(i * width + j)*3 + 0];
340  point_cloud->points[(size_t)(i * width + j)].y = pcl_data_ptr[(size_t)(i * width + j)*3 + 1];
341  point_cloud->points[(size_t)(i * width + j)].z = pcl_data_ptr[(size_t)(i * width + j)*3 + 2];
342  }
343  }
344  }
345 #endif
346  else {
347 #if defined(VISP_HAVE_PCL_IO)
348  if (pcl::io::loadPCDFile<pcl::PointXYZ>(filename_pointcloud, *point_cloud) == -1) {
349  std::cerr << "Cannot read PCD: " << filename_pointcloud << std::endl;
350  }
351 #else
352  throw(vpIoException(vpIoException::ioError, "Cannot read pcd file without PCL io module"));
353 #endif
354  }
355 #endif
356  }
357 
358  return true;
359 }
360 } // Namespace
361 
362 int main(int argc, const char *argv[])
363 {
364  std::string input_directory = "";
365  std::string pattern = "%04d";
366  bool click = false;
367  bool force_binary_format = false;
368  bool save_video = false;
369  bool color_depth = false;
370  bool read_jpeg = false;
371  bool read_npz = false;
372 
373  // Read the command line options
374  if (!getOptions(argc, argv, input_directory, pattern, click, force_binary_format, read_jpeg, read_npz,
375  save_video, color_depth)) {
376  return EXIT_FAILURE;
377  }
378 
379  vpImage<vpRGBa> I_color(480, 640), I_depth_color(480, 640);
380  vpImage<uint16_t> I_depth_raw(480, 640);
381  vpImage<unsigned char> I_depth(480, 640);
382 
383 #ifdef VISP_HAVE_X11
384  vpDisplayX d1, d2;
385 #else
386  vpDisplayGDI d1, d2;
387 #endif
388  bool init_display = false;
389 
390 #if defined(VISP_HAVE_PCL)
391  std::mutex mutex;
392  pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud(new pcl::PointCloud<pcl::PointXYZ>());
393 #if defined(VISP_HAVE_PCL_VISUALIZATION)
394  vpDisplayPCL pcl_viewer;
395 #endif
396 #endif
397 
398  vpVideoWriter writer;
399  vpImage<vpRGBa> O;
400  if (save_video) {
401  std::string output_directory = vpTime::getDateTime("%Y-%m-%d_%H.%M.%S");
402  vpIoTools::makeDirectory(output_directory);
403  writer.setFileName(output_directory + "/" + pattern + ".png");
404  }
405 
406  int cpt_frame = 0;
407  bool quit = false;
408  while (!quit) {
409  double t = vpTime::measureTimeMs();
410 
411 #if defined(VISP_HAVE_PCL) && defined(VISP_HAVE_PCL_COMMON)
412  {
413  std::lock_guard<std::mutex> lock(mutex);
414  quit = !readData(cpt_frame, input_directory, pattern, I_color, I_depth_raw, force_binary_format, read_jpeg,
415  read_npz, pointcloud);
416  }
417 #else
418  quit = !readData(cpt_frame, input_directory, pattern, I_color, I_depth_raw, force_binary_format, read_jpeg,
419  read_npz);
420 #endif
421 
422  if (color_depth)
423  vpImageConvert::createDepthHistogram(I_depth_raw, I_depth_color);
424  else
425  vpImageConvert::createDepthHistogram(I_depth_raw, I_depth);
426 
427  if (!init_display) {
428  init_display = true;
429  d1.init(I_color, 0, 0, "Color image");
430  if (color_depth) {
431  d2.init(I_depth_color, I_color.getWidth() + 10, 0, "Depth image");
432  }
433  else {
434  d2.init(I_depth, I_color.getWidth() + 10, 0, "Depth image");
435  }
436 #if defined(VISP_HAVE_PCL) && defined(VISP_HAVE_PCL_VISUALIZATION)
437  pcl_viewer.setPosition(I_color.getWidth() + 10, I_color.getHeight() + 70);
438  pcl_viewer.setWindowName("3D point cloud");
439  pcl_viewer.startThread(std::ref(mutex), pointcloud);
440 #endif
441  }
442 
443  vpDisplay::display(I_color);
444  if (color_depth)
445  vpDisplay::display(I_depth_color);
446  else
447  vpDisplay::display(I_depth);
448 
449  std::stringstream ss;
450  ss << "Frame: " << cpt_frame;
451  vpDisplay::displayText(I_color, 20, 20, ss.str(), vpColor::red);
452  if (color_depth)
453  vpDisplay::displayText(I_depth_color, 20, 20, ss.str(), vpColor::red);
454  else
455  vpDisplay::displayText(I_depth, 20, 20, ss.str(), vpColor::red);
456 
457  vpDisplay::flush(I_color);
458  if (color_depth)
459  vpDisplay::flush(I_depth_color);
460  else
461  vpDisplay::flush(I_depth);
462 
463  if (save_video) {
464  if (O.getSize() == 0) {
465  O.resize(I_color.getHeight(), I_color.getWidth() + I_depth_color.getWidth());
466  writer.open(O);
467  }
468 
469  O.insert(I_color, vpImagePoint());
470  if (!color_depth)
471  vpImageConvert::convert(I_depth, I_depth_color);
472  O.insert(I_depth_color, vpImagePoint(0, I_color.getWidth()));
473  writer.saveFrame(O);
474  }
475 
477  if (vpDisplay::getClick(I_color, button, click)) {
478  switch (button) {
480  if (!quit)
481  quit = !click;
482  break;
483 
485  click = !click;
486  break;
487 
488  default:
489  break;
490  }
491  }
492 
493  vpTime::wait(t, 30);
494  cpt_frame++;
495  }
496 
497  return EXIT_SUCCESS;
498 }
499 #else
500 int main()
501 {
502  std::cerr << "Enable C++11 or higher (cmake -DUSE_CXX_STANDARD=11) and install X11 or GDI!" << std::endl;
503  return EXIT_SUCCESS;
504 }
505 #endif
static const vpColor red
Definition: vpColor.h:217
Display for windows using GDI (available on any windows 32 platform).
Definition: vpDisplayGDI.h:130
void setPosition(int posx, int posy)
void startThread(std::mutex &mutex, pcl::PointCloud< pcl::PointXYZ >::Ptr pointcloud)
void setWindowName(const std::string &window_name)
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:135
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)
static void display(const vpImage< unsigned char > &I)
static void flush(const vpImage< unsigned char > &I)
static void displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
@ ioError
I/O error.
Definition: vpException.h:67
static void createDepthHistogram(const vpImage< uint16_t > &src_depth, vpImage< vpRGBa > &dest_rgba)
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)
Definition: vpImageIo.cpp:147
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
Definition: vpImagePoint.h:82
unsigned int getWidth() const
Definition: vpImage.h:242
void resize(unsigned int h, unsigned int w)
resize the image : Image initialization
Definition: vpImage.h:538
void insert(const vpImage< Type > &src, const vpImagePoint &topLeft)
Definition: vpImage.h:633
unsigned int getSize() const
Definition: vpImage.h:221
unsigned int getHeight() const
Definition: vpImage.h:181
Error that can be emitted by the vpIoTools class and its derivatives.
Definition: vpIoException.h:55
static bool checkFilename(const std::string &filename)
Definition: vpIoTools.cpp:786
static void readBinaryValueLE(std::ifstream &file, int16_t &short_value)
static void makeDirectory(const std::string &dirname)
Definition: vpIoTools.cpp:550
static std::string getName(const std::string &pathname)
Definition: vpIoTools.cpp:1205
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:70
Class that enables to write easily a video file or a sequence of images.
void saveFrame(vpImage< vpRGBa > &I)
void setFileName(const std::string &filename)
void open(vpImage< vpRGBa > &I)
VISP_EXPORT npz_t npz_load(std::string fname)
std::map< std::string, NpyArray > npz_t
Definition: vpIoTools.h:130
VISP_EXPORT int wait(double t0, double t)
VISP_EXPORT std::string getDateTime(const std::string &format="%Y/%m/%d %H:%M:%S")
VISP_EXPORT double measureTimeMs()
std::shared_ptr< std::vector< char > > data_holder
Definition: vpIoTools.h:123
std::vector< size_t > shape
Definition: vpIoTools.h:124