forked from edmBernard/pybind11_opencv_numpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathndarray_converter.h
70 lines (50 loc) · 1.76 KB
/
ndarray_converter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# ifndef __NDARRAY_CONVERTER_H__
# define __NDARRAY_CONVERTER_H__
#include <Python.h>
#include <opencv2/core/core.hpp>
#include <numpy/ndarrayobject.h>
class NumpyAllocator : public cv::MatAllocator
{
public:
NumpyAllocator();
~NumpyAllocator();
cv::UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const;
#if CV_MAJOR_VERSION < 4
cv::UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, cv::UMatUsageFlags usageFlags) const;
#else
cv::UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, cv::AccessFlag flags, cv::UMatUsageFlags usageFlags) const;
#endif
#if CV_MAJOR_VERSION < 4
bool allocate(cv::UMatData* u, int accessFlags, cv::UMatUsageFlags usageFlags) const;
#else
bool allocate(cv::UMatData* u, cv::AccessFlag accessFlags, cv::UMatUsageFlags usageFlags) const;
#endif
void deallocate(cv::UMatData* u) const;
private:
const cv::MatAllocator* stdAllocator;
};
extern NumpyAllocator g_numpyAllocator;
class NDArrayConverter {
public:
// must call this first, or the other routines don't work!
static bool init_numpy();
static bool toMat(PyObject* o, cv::Mat &m);
static PyObject* toNDArray(const cv::Mat& mat);
};
//
// Define the type converter
//
#include <pybind11/pybind11.h>
namespace pybind11 { namespace detail {
template <> struct type_caster<cv::Mat> {
public:
PYBIND11_TYPE_CASTER(cv::Mat, _("numpy.ndarray"));
bool load(handle src, bool /* convert */) {
return NDArrayConverter::toMat(src.ptr(), value);
}
static handle cast(const cv::Mat &m, return_value_policy, handle defval) {
return handle(NDArrayConverter::toNDArray(m));
}
};
}} // namespace pybind11::detail
# endif