Search code examples
c++vectortype-conversionopen3d

How to extract sub-vectors of different datatypes from vector<char>?


I have a std::vector<char> data which represents data from a network byte-stream as well as different offsets as integer values. I know that the vector holds the data for a 4x4 trajectory matrix (32bit float), a RGB image (Unity TextureFormat.RGB24) and a gray scale image (Unity TextureFormat.RFloat).

What I need to do is the extract the following from this data:

  • Eigen::Matrix4d trajectory
  • std::vector<uint8_t> rgb_image_data
  • std::vector<uint8_t> gray_image_data

I want to do TSDF Volume integration with RGBD images using Open3D. I have the same setup as python script already working (simply using numpy arrays for the data buffers), but need to rewrite it in C++ and I'm quite unsure how to do these conversions best.


Solution

  • You need to copy the bytes into objects of the right type

    std::vector<char> data = /* get from network */;
    Eigen::Matrix4d trajectory;
    std::vector<uint8_t> rgb_image_data(rgb_image_size);
    std::vector<uint8_t> gray_image_data(gray_image_size);
    
    std::memcpy(&trajectory, data.data() + trajectory_offset, sizeof(Eigen::Matrix4d));
    std::memcpy(rgb_image_data.data(), data.data() + rgb_image_offset, rgb_image_size);
    std::memcpy(gray_image_data.data(), data.data() + gray_image_offset, gray_image_size);
    

    That is assuming that the source copied in a whole Eigen::Matrix4d, rather than the double[4][4] it contains.