Skip to content

Enhance API Design #4

@DapengFeng

Description

@DapengFeng

Hi @andrewssobral , inspired by your excellent repo:), I have implemented a similar Adapter Class. Do you have any suggestions for API design enhancement?

template <typename T,
          uint32_t channels_ = 1,
          typename = std::enable_if_t<std::is_arithmetic_v<T>>>
class Adapter {
 public:
  using Tensor = torch::Tensor;
  using Mat = cv::Mat;
  using MatrixColMajor = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
  using MatrixRowMajor =
      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
  explicit Adapter(const Tensor& tensor) {
    Tensor cpu_tensor;
    if constexpr (channels_ == 1) {
      cpu_tensor = tensor.detach().to(torch::kCPU, true).contiguous();
    } else {
      cpu_tensor = tensor.detach().to(torch::kCPU, true).permute({1, 2, 0}).contiguous();
    }
    data_ptr_ = cpu_tensor.data_ptr();
    rows_ = cpu_tensor.size(0);
    cols_ = cpu_tensor.size(1);
  }

  explicit Adapter(const Mat& mat) {
    data_ptr_ = mat.data;
    rows_ = mat.rows;
    cols_ = mat.cols;
  }

  explicit Adapter(const MatrixColMajor& mat) {
    data_ptr_ = const_cast<T*>(mat.data());
    rows_ = mat.cols();
    cols_ = mat.rows();
    is_raw_ = false;
  }

  inline Tensor toTensor(const bool copy = true) {
    Tensor tensor;
    if constexpr (channels_ == 1) {
      tensor = torch::from_blob(data_ptr_, {rows_, cols_}, torch::TensorOptions(torch::CppTypeToScalarType<T>()));
    } else {
      tensor = torch::from_blob(data_ptr_, {rows_, cols_, channels_},
                                torch::TensorOptions(torch::CppTypeToScalarType<T>()))
                   .permute({2, 0, 1})
                   .contiguous();
    }
    if (!is_raw_) {
      tensor = tensor.mT();
    }
    if (copy) {
      return tensor.clone();
    } else {
      return tensor;
    }
  }

  template <typename = std::enable_if_t<std::is_floating_point_v<T> && sizeof(T) == sizeof(float)>>
  inline Mat toCvMat(const bool copy = true) {
    Mat mat(rows_, cols_, CV_32FC(channels_), data_ptr_);
    if (!is_raw_) {
      mat = mat.t();
    }
    if (copy) {
      return mat.clone();
    } else {
      return mat;
    }
  }

  template <typename = std::enable_if_t<channels_ == 1>>
  inline MatrixColMajor toEigenMatrix() {
    if (!is_raw_) {
      return Eigen::Map<MatrixColMajor>(reinterpret_cast<T*>(data_ptr_), cols_, rows_);
    }
    return Eigen::Map<MatrixRowMajor>(reinterpret_cast<T*>(data_ptr_), rows_, cols_);
  }

 private:
  void* data_ptr_;
  uint32_t rows_;
  uint32_t cols_;
  bool is_raw_ = true;
};

Note

  • Shadow copy of Eigen Matrix.
  • High dimensional tensor.
  • Host (cpu) and Device (gpu, npu, and others).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions