Point Cloud Library (PCL)  1.9.1-dev
conversions.h
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2010-2012, Willow Garage, Inc.
6  *
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * * Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  * * Redistributions in binary form must reproduce the above
16  * copyright notice, this list of conditions and the following
17  * disclaimer in the documentation and/or other materials provided
18  * with the distribution.
19  * * Neither the name of the copyright holder(s) nor the names of its
20  * contributors may be used to endorse or promote products derived
21  * from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  * $Id$
37  *
38  */
39 
40 #pragma once
41 
42 #ifdef __GNUC__
43 #pragma GCC system_header
44 #endif
45 
46 #include <pcl/PCLPointField.h>
47 #include <pcl/PCLPointCloud2.h>
48 #include <pcl/PCLImage.h>
49 #include <pcl/point_cloud.h>
50 #include <pcl/point_traits.h>
51 #include <pcl/for_each_type.h>
52 #include <pcl/exceptions.h>
53 #include <pcl/console/print.h>
54 #ifndef Q_MOC_RUN
55 #include <boost/foreach.hpp>
56 #endif
57 
58 namespace pcl
59 {
60  namespace detail
61  {
62  // For converting template point cloud to message.
63  template<typename PointT>
64  struct FieldAdder
65  {
66  FieldAdder (std::vector<pcl::PCLPointField>& fields) : fields_ (fields) {};
67 
68  template<typename U> void operator() ()
69  {
75  fields_.push_back (f);
76  }
77 
78  std::vector<pcl::PCLPointField>& fields_;
79  };
80 
81  // For converting message to template point cloud.
82  template<typename PointT>
83  struct FieldMapper
84  {
85  FieldMapper (const std::vector<pcl::PCLPointField>& fields,
86  std::vector<FieldMapping>& map)
87  : fields_ (fields), map_ (map)
88  {
89  }
90 
91  template<typename Tag> void
93  {
94  for (const auto& field : fields_)
95  {
96  if (FieldMatches<PointT, Tag>()(field))
97  {
98  FieldMapping mapping;
99  mapping.serialized_offset = field.offset;
101  mapping.size = sizeof (typename traits::datatype<PointT, Tag>::type);
102  map_.push_back (mapping);
103  return;
104  }
105  }
106  // Disable thrown exception per #595: http://dev.pointclouds.org/issues/595
107  PCL_WARN ("Failed to find match for field '%s'.\n", traits::name<PointT, Tag>::value);
108  //throw pcl::InvalidConversionException (ss.str ());
109  }
110 
111  const std::vector<pcl::PCLPointField>& fields_;
112  std::vector<FieldMapping>& map_;
113  };
114 
115  inline bool
117  {
118  return (a.serialized_offset < b.serialized_offset);
119  }
120 
121  } //namespace detail
122 
123  template<typename PointT> void
124  createMapping (const std::vector<pcl::PCLPointField>& msg_fields, MsgFieldMap& field_map)
125  {
126  // Create initial 1-1 mapping between serialized data segments and struct fields
127  detail::FieldMapper<PointT> mapper (msg_fields, field_map);
128  for_each_type< typename traits::fieldList<PointT>::type > (mapper);
129 
130  // Coalesce adjacent fields into single memcpy's where possible
131  if (field_map.size() > 1)
132  {
133  std::sort(field_map.begin(), field_map.end(), detail::fieldOrdering);
134  MsgFieldMap::iterator i = field_map.begin(), j = i + 1;
135  while (j != field_map.end())
136  {
137  // This check is designed to permit padding between adjacent fields.
138  /// @todo One could construct a pathological case where the struct has a
139  /// field where the serialized data has padding
140  if (j->serialized_offset - i->serialized_offset == j->struct_offset - i->struct_offset)
141  {
142  i->size += (j->struct_offset + j->size) - (i->struct_offset + i->size);
143  j = field_map.erase(j);
144  }
145  else
146  {
147  ++i;
148  ++j;
149  }
150  }
151  }
152  }
153 
154  /** \brief Convert a PCLPointCloud2 binary data blob into a pcl::PointCloud<T> object using a field_map.
155  * \param[in] msg the PCLPointCloud2 binary blob
156  * \param[out] cloud the resultant pcl::PointCloud<T>
157  * \param[in] field_map a MsgFieldMap object
158  *
159  * \note Use fromPCLPointCloud2 (PCLPointCloud2, PointCloud<T>) directly or create you
160  * own MsgFieldMap using:
161  *
162  * \code
163  * MsgFieldMap field_map;
164  * createMapping<PointT> (msg.fields, field_map);
165  * \endcode
166  */
167  template <typename PointT> void
169  const MsgFieldMap& field_map)
170  {
171  // Copy info fields
172  cloud.header = msg.header;
173  cloud.width = msg.width;
174  cloud.height = msg.height;
175  cloud.is_dense = msg.is_dense == 1;
176 
177  // Copy point data
178  std::uint32_t num_points = msg.width * msg.height;
179  cloud.points.resize (num_points);
180  std::uint8_t* cloud_data = reinterpret_cast<std::uint8_t*>(&cloud.points[0]);
181 
182  // Check if we can copy adjacent points in a single memcpy. We can do so if there
183  // is exactly one field to copy and it is the same size as the source and destination
184  // point types.
185  if (field_map.size() == 1 &&
186  field_map[0].serialized_offset == 0 &&
187  field_map[0].struct_offset == 0 &&
188  field_map[0].size == msg.point_step &&
189  field_map[0].size == sizeof(PointT))
190  {
191  std::uint32_t cloud_row_step = static_cast<std::uint32_t> (sizeof (PointT) * cloud.width);
192  const std::uint8_t* msg_data = &msg.data[0];
193  // Should usually be able to copy all rows at once
194  if (msg.row_step == cloud_row_step)
195  {
196  memcpy (cloud_data, msg_data, msg.data.size ());
197  }
198  else
199  {
200  for (std::uint32_t i = 0; i < msg.height; ++i, cloud_data += cloud_row_step, msg_data += msg.row_step)
201  memcpy (cloud_data, msg_data, cloud_row_step);
202  }
203 
204  }
205  else
206  {
207  // If not, memcpy each group of contiguous fields separately
208  for (std::uint32_t row = 0; row < msg.height; ++row)
209  {
210  const std::uint8_t* row_data = &msg.data[row * msg.row_step];
211  for (std::uint32_t col = 0; col < msg.width; ++col)
212  {
213  const std::uint8_t* msg_data = row_data + col * msg.point_step;
214  for (const detail::FieldMapping& mapping : field_map)
215  {
216  memcpy (cloud_data + mapping.struct_offset, msg_data + mapping.serialized_offset, mapping.size);
217  }
218  cloud_data += sizeof (PointT);
219  }
220  }
221  }
222  }
223 
224  /** \brief Convert a PCLPointCloud2 binary data blob into a pcl::PointCloud<T> object.
225  * \param[in] msg the PCLPointCloud2 binary blob
226  * \param[out] cloud the resultant pcl::PointCloud<T>
227  */
228  template<typename PointT> void
230  {
231  MsgFieldMap field_map;
232  createMapping<PointT> (msg.fields, field_map);
233  fromPCLPointCloud2 (msg, cloud, field_map);
234  }
235 
236  /** \brief Convert a pcl::PointCloud<T> object to a PCLPointCloud2 binary data blob.
237  * \param[in] cloud the input pcl::PointCloud<T>
238  * \param[out] msg the resultant PCLPointCloud2 binary blob
239  */
240  template<typename PointT> void
242  {
243  // Ease the user's burden on specifying width/height for unorganized datasets
244  if (cloud.width == 0 && cloud.height == 0)
245  {
246  msg.width = static_cast<std::uint32_t>(cloud.points.size ());
247  msg.height = 1;
248  }
249  else
250  {
251  assert (cloud.points.size () == cloud.width * cloud.height);
252  msg.height = cloud.height;
253  msg.width = cloud.width;
254  }
255 
256  // Fill point cloud binary data (padding and all)
257  std::size_t data_size = sizeof (PointT) * cloud.points.size ();
258  msg.data.resize (data_size);
259  if (data_size)
260  {
261  memcpy(&msg.data[0], &cloud.points[0], data_size);
262  }
263 
264  // Fill fields metadata
265  msg.fields.clear ();
266  for_each_type<typename traits::fieldList<PointT>::type> (detail::FieldAdder<PointT>(msg.fields));
267 
268  msg.header = cloud.header;
269  msg.point_step = sizeof (PointT);
270  msg.row_step = static_cast<std::uint32_t> (sizeof (PointT) * msg.width);
271  msg.is_dense = cloud.is_dense;
272  /// @todo msg.is_bigendian = ?;
273  }
274 
275  /** \brief Copy the RGB fields of a PointCloud into pcl::PCLImage format
276  * \param[in] cloud the point cloud message
277  * \param[out] msg the resultant pcl::PCLImage
278  * CloudT cloud type, CloudT should be akin to pcl::PointCloud<pcl::PointXYZRGBA>
279  * \note will throw std::runtime_error if there is a problem
280  */
281  template<typename CloudT> void
282  toPCLPointCloud2 (const CloudT& cloud, pcl::PCLImage& msg)
283  {
284  // Ease the user's burden on specifying width/height for unorganized datasets
285  if (cloud.width == 0 && cloud.height == 0)
286  throw std::runtime_error("Needs to be a dense like cloud!!");
287  else
288  {
289  if (cloud.points.size () != cloud.width * cloud.height)
290  throw std::runtime_error("The width and height do not match the cloud size!");
291  msg.height = cloud.height;
292  msg.width = cloud.width;
293  }
294 
295  // ensor_msgs::image_encodings::BGR8;
296  msg.encoding = "bgr8";
297  msg.step = msg.width * sizeof (std::uint8_t) * 3;
298  msg.data.resize (msg.step * msg.height);
299  for (std::size_t y = 0; y < cloud.height; y++)
300  {
301  for (std::size_t x = 0; x < cloud.width; x++)
302  {
303  std::uint8_t * pixel = &(msg.data[y * msg.step + x * 3]);
304  memcpy (pixel, &cloud (x, y).rgb, 3 * sizeof(std::uint8_t));
305  }
306  }
307  }
308 
309  /** \brief Copy the RGB fields of a PCLPointCloud2 msg into pcl::PCLImage format
310  * \param cloud the point cloud message
311  * \param msg the resultant pcl::PCLImage
312  * will throw std::runtime_error if there is a problem
313  */
314  inline void
316  {
317  const auto predicate = [](const auto& field) { return field.name == "rgb"; };
318  const auto result = std::find_if(cloud.fields.cbegin (), cloud.fields.cend (), predicate);
319  if (result == cloud.fields.end ())
320  throw std::runtime_error ("No rgb field!!");
321 
322  const auto rgb_index = std::distance(cloud.fields.begin (), result);
323  if (cloud.width == 0 && cloud.height == 0)
324  throw std::runtime_error ("Needs to be a dense like cloud!!");
325  else
326  {
327  msg.height = cloud.height;
328  msg.width = cloud.width;
329  }
330  int rgb_offset = cloud.fields[rgb_index].offset;
331  int point_step = cloud.point_step;
332 
333  // pcl::image_encodings::BGR8;
334  msg.encoding = "bgr8";
335  msg.step = static_cast<std::uint32_t>(msg.width * sizeof (std::uint8_t) * 3);
336  msg.data.resize (msg.step * msg.height);
337 
338  for (std::size_t y = 0; y < cloud.height; y++)
339  {
340  for (std::size_t x = 0; x < cloud.width; x++, rgb_offset += point_step)
341  {
342  std::uint8_t * pixel = &(msg.data[y * msg.step + x * 3]);
343  memcpy (pixel, &(cloud.data[rgb_offset]), 3 * sizeof (std::uint8_t));
344  }
345  }
346  }
347 }
void fromPCLPointCloud2(const pcl::PCLPointCloud2 &msg, pcl::PointCloud< PointT > &cloud, const MsgFieldMap &field_map)
Convert a PCLPointCloud2 binary data blob into a pcl::PointCloud<T> object using a field_map...
Definition: conversions.h:168
std::vector< detail::FieldMapping > MsgFieldMap
Definition: point_cloud.h:71
std::vector<::pcl::PCLPointField > fields
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:394
std::vector< pcl::PCLPointField > & fields_
Definition: conversions.h:78
This file defines compatibility wrappers for low level I/O functions.
Definition: convolution.h:45
bool fieldOrdering(const FieldMapping &a, const FieldMapping &b)
Definition: conversions.h:116
::pcl::PCLHeader header
std::uint32_t offset
Definition: PCLPointField.h:19
std::uint8_t is_dense
std::size_t serialized_offset
Definition: point_cloud.h:63
std::uint32_t height
std::uint32_t count
Definition: PCLPointField.h:21
std::uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:397
std::uint32_t height
Definition: PCLImage.h:20
std::vector< std::uint8_t > data
Definition: PCLImage.h:27
std::uint32_t point_step
float distance(const PointT &p1, const PointT &p2)
Definition: geometry.h:60
std::uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:399
std::uint32_t width
Definition: PCLImage.h:21
PointCloud represents the base class in PCL for storing collections of 3D points. ...
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:391
std::uint32_t width
std::vector< std::uint8_t > data
void toPCLPointCloud2(const pcl::PointCloud< PointT > &cloud, pcl::PCLPointCloud2 &msg)
Convert a pcl::PointCloud<T> object to a PCLPointCloud2 binary data blob.
Definition: conversions.h:241
bool is_dense
True if no points are invalid (e.g., have NaN or Inf values in any of their floating point fields)...
Definition: point_cloud.h:402
std::string encoding
Definition: PCLImage.h:22
std::uint32_t row_step
std::string name
Definition: PCLPointField.h:17
A point structure representing Euclidean xyz coordinates, and the RGB color.
std::uint8_t datatype
Definition: PCLPointField.h:20
FieldAdder(std::vector< pcl::PCLPointField > &fields)
Definition: conversions.h:66
std::vector< FieldMapping > & map_
Definition: conversions.h:112
void createMapping(const std::vector< pcl::PCLPointField > &msg_fields, MsgFieldMap &field_map)
Definition: conversions.h:124
const std::vector< pcl::PCLPointField > & fields_
Definition: conversions.h:111
FieldMapper(const std::vector< pcl::PCLPointField > &fields, std::vector< FieldMapping > &map)
Definition: conversions.h:85
std::uint32_t step
Definition: PCLImage.h:25