ifm / ifm3d

Library and Utilities for working with ifm pmd-based 3D ToF Cameras
https://api.ifm3d.com
Apache License 2.0
110 stars 69 forks source link

ifm3d::Image to cv::Mat conversion #362

Closed j-friedl closed 2 years ago

j-friedl commented 2 years ago

Hi! I'm wondering if there's an example on how to convert the ifm3d::Image to an cv::Mat? I want to be able to do something like this:

cv::Mat m = im->DistanceImage();

It would be really helpful if such conversions make it into the docs :) (also usage with PCL etc.)

inbangsa commented 2 years ago

@j-friedl

This work in progress and should be part of the future release.

following code will be a good start point :

// -*- c++ -*-
/*
 * Copyright 2021-present ifm electronic, gmbh
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef IFM3D_IMAGE_TO_CV_MAT_HPP
#define IFM3D_IMAGE_TO_CV_MAT_HPP

#include <ifm3d/stlimage/image.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/mat.hpp>
#include <cstdint>
#include <memory>
#include <map>

std::map<uint32_t, int32_t> ifm3d_type_to_cv_type{
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_8U),  CV_8U},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_8S),  CV_8S},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_16U), CV_16U},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_16S), CV_16S},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_32S), CV_32S},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_32F), CV_32F},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_64F), CV_64F},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_16U2),CV_16U},
  {static_cast<std::uint32_t>(ifm3d::pixel_format::FORMAT_32F3),CV_32F}};

namespace ifm3d
{

  cv::Mat
  convert_to_mat(ifm3d::Image& image)
  {
    int cv_type = CV_MAKETYPE(
      ifm3d_type_to_cv_type[static_cast<std::uint32_t>(image.dataFormat())],
      image.nchannels());

    return cv::Mat(image.height(), image.width(), cv_type, (void*)image.ptr(0));
  }

}// end: namespace ifm3d

#endif // IFM3D_IMAGE_TO_CV_MAT_HPP
j-friedl commented 2 years ago

Great it works thank you!

inbangsa commented 2 years ago

@j-friedl Nice to hear this , can we close this issue

j-friedl commented 2 years ago

Yes, thanks!