summaryrefslogtreecommitdiffstats
path: root/ml/dlib/dlib/python/numpy.h
blob: 9b2c1a01c6baf38ddd1abc71b3b10ee279cfd8ea (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright (C) 2014  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_PYTHON_NuMPY_Hh_
#define DLIB_PYTHON_NuMPY_Hh_

#include <pybind11/pybind11.h>
#include <dlib/error.h>
#include <dlib/algs.h>
#include <dlib/string.h>
#include <dlib/array.h>
#include <dlib/pixel.h>

namespace py = pybind11;

// ----------------------------------------------------------------------------------------

template <typename TT>
void validate_numpy_array_type (
    const py::object& obj
)
{
    const char ch = obj.attr("dtype").attr("char").cast<char>();

    using T = typename dlib::pixel_traits<TT>::basic_pixel_type;

    if (dlib::is_same_type<T,double>::value)
    {
        if (ch != 'd')
            throw dlib::error("Expected numpy.ndarray of float64");
    }
    else if (dlib::is_same_type<T,float>::value)
    {
        if (ch != 'f')
            throw dlib::error("Expected numpy.ndarray of float32");
    }
    else if (dlib::is_same_type<T,dlib::int16>::value)
    {
        if (ch != 'h')
            throw dlib::error("Expected numpy.ndarray of int16");
    }
    else if (dlib::is_same_type<T,dlib::uint16>::value)
    {
        if (ch != 'H')
            throw dlib::error("Expected numpy.ndarray of uint16");
    }
    else if (dlib::is_same_type<T,dlib::int32>::value)
    {
        if (ch != 'i')
            throw dlib::error("Expected numpy.ndarray of int32");
    }
    else if (dlib::is_same_type<T,dlib::uint32>::value)
    {
        if (ch != 'I')
            throw dlib::error("Expected numpy.ndarray of uint32");
    }
    else if (dlib::is_same_type<T,unsigned char>::value)
    {
        if (ch != 'B')
            throw dlib::error("Expected numpy.ndarray of uint8");
    }
    else if (dlib::is_same_type<T,signed char>::value)
    {
        if (ch != 'b')
            throw dlib::error("Expected numpy.ndarray of int8");
    }
    else
    {
        throw dlib::error("validate_numpy_array_type() called with unsupported type.");
    }
}

// ----------------------------------------------------------------------------------------

template <int dims>
void get_numpy_ndarray_shape (
    const py::object& obj,
    long (&shape)[dims]
)
/*!
    ensures
        - stores the shape of the array into #shape.
        - the dimension of the given numpy array is not greater than #dims.
!*/
{
    Py_buffer pybuf;
    if (PyObject_GetBuffer(obj.ptr(), &pybuf, PyBUF_STRIDES ))
        throw dlib::error("Expected numpy.ndarray with shape set.");

    try
    {

        if (pybuf.ndim > dims)
            throw dlib::error("Expected array with " + dlib::cast_to_string(dims) + " dimensions.");

        for (int i = 0; i < dims; ++i)
        {
            if (i < pybuf.ndim)
                shape[i] = pybuf.shape[i];
            else
                shape[i] = 1;
        }
    }
    catch(...)
    {
        PyBuffer_Release(&pybuf);
        throw;
    }
    PyBuffer_Release(&pybuf);
}

// ----------------------------------------------------------------------------------------

template <typename T, int dims>
void get_numpy_ndarray_parts (
    py::object& obj,
    T*& data,
    dlib::array<T>& contig_buf,
    long (&shape)[dims]
)
/*!
    ensures
        - extracts the pointer to the data from the given numpy ndarray.  Stores the shape
          of the array into #shape.
        - the dimension of the given numpy array is not greater than #dims.
        - #shape[#dims-1] == pixel_traits<T>::num when #dims is greater than 2
!*/
{
    Py_buffer pybuf;
    if (PyObject_GetBuffer(obj.ptr(), &pybuf, PyBUF_STRIDES | PyBUF_WRITABLE ))
        throw dlib::error("Expected writable numpy.ndarray with shape set.");

    try
    {
        validate_numpy_array_type<T>(obj);

        if (pybuf.ndim > dims)
            throw dlib::error("Expected array with " + dlib::cast_to_string(dims) + " dimensions.");
        get_numpy_ndarray_shape(obj, shape);

        if (dlib::pixel_traits<T>::num > 1 && dlib::pixel_traits<T>::num != shape[dims-1])
            throw dlib::error("Expected numpy.ndarray with " + dlib::cast_to_string(dlib::pixel_traits<T>::num) + " channels.");

        if (PyBuffer_IsContiguous(&pybuf, 'C'))
            data = (T*)pybuf.buf;
        else
        {
            contig_buf.resize(pybuf.len);
            if (PyBuffer_ToContiguous(&contig_buf[0], &pybuf, pybuf.len, 'C'))
                throw dlib::error("Can't copy numpy.ndarray to a contiguous buffer.");
            data = &contig_buf[0];
        }
    }
    catch(...)
    {
        PyBuffer_Release(&pybuf);
        throw;
    }
    PyBuffer_Release(&pybuf);
}

// ----------------------------------------------------------------------------------------

template <typename T, int dims>
void get_numpy_ndarray_parts (
    const py::object& obj,
    const T*& data,
    dlib::array<T>& contig_buf,
    long (&shape)[dims]
)
/*!
    ensures
        - extracts the pointer to the data from the given numpy ndarray.  Stores the shape
          of the array into #shape.
        - the dimension of the given numpy array is not greater than #dims.
        - #shape[#dims-1] == pixel_traits<T>::num when #dims is greater than 2
!*/
{
    Py_buffer pybuf;
    if (PyObject_GetBuffer(obj.ptr(), &pybuf, PyBUF_STRIDES ))
        throw dlib::error("Expected numpy.ndarray with shape set.");

    try
    {
        validate_numpy_array_type<T>(obj);

        if (pybuf.ndim > dims)
            throw dlib::error("Expected array with " + dlib::cast_to_string(dims) + " dimensions.");
        get_numpy_ndarray_shape(obj, shape);

        if (dlib::pixel_traits<T>::num > 1 && dlib::pixel_traits<T>::num != shape[dims-1])
            throw dlib::error("Expected numpy.ndarray with " + dlib::cast_to_string(dlib::pixel_traits<T>::num) + " channels.");

        if (PyBuffer_IsContiguous(&pybuf, 'C'))
            data = (const T*)pybuf.buf;
        else
        {
            contig_buf.resize(pybuf.len);
            if (PyBuffer_ToContiguous(&contig_buf[0], &pybuf, pybuf.len, 'C'))
                throw dlib::error("Can't copy numpy.ndarray to a contiguous buffer.");
            data = &contig_buf[0];
        }
    }
    catch(...)
    {
        PyBuffer_Release(&pybuf);
        throw;
    }
    PyBuffer_Release(&pybuf);
}

// ----------------------------------------------------------------------------------------

#endif // DLIB_PYTHON_NuMPY_Hh_