image_cast.hpp 1.44 KB
Newer Older
1
2
3
4
5
6
7
#pragma once

#include <mln/core/image/ndbuffer_image.hpp>

#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>

8
9
#include <fmt/format.h>

10
11
namespace pln
{
Baptiste Esteban's avatar
Baptiste Esteban committed
12
13
14
  /// \brief Convert a NumPy array to a ndbuffer_image
  /// \param[in] arr A NumPy array
  /// \return A ndbuffer_image
15
  PYBIND11_EXPORT mln::ndbuffer_image from_numpy(pybind11::array arr);
16

Baptiste Esteban's avatar
Baptiste Esteban committed
17
18
19
  /// \brief Convert a ndbuffer_image array to a NumPy
  /// \param[in] arr A ndbuffer_image
  /// \return A NumPy array
20
  PYBIND11_EXPORT pybind11::object to_numpy(const mln::ndbuffer_image& img);
21
22
23
24
25


  /// \brief Export the binding of the class
  /// ndbuffer_image_data
  /// \param[in] m The module in which the class will be exported
26
  PYBIND11_EXPORT void init_pylena_numpy(pybind11::module& m);
27
} // namespace pln
28
29
30

namespace pybind11::detail
{
31
32
33
34
  template <>
  struct type_caster<mln::ndbuffer_image>
  {
    PYBIND11_TYPE_CASTER(mln::ndbuffer_image, _("numpy.ndarray"));
35

36
37
    bool load(handle h, bool)
    {
38
39
      if (!pybind11::array::check_(h))
        throw std::invalid_argument(fmt::format("Input value is not a valid array (Got `{}`)", static_cast<std::string>(pybind11::str(pybind11::type::handle_of(h)))));
40
41
42
43
      pybind11::array arr = reinterpret_borrow<pybind11::array>(h);
      value               = pln::from_numpy(arr);
      return true;
    }
44

45
    static handle cast(const mln::ndbuffer_image& img, return_value_policy, handle) { return pln::to_numpy(img).inc_ref(); }
46
47
  };
} // namespace pybind11::detail