-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathexamples.cpp
85 lines (72 loc) · 1.78 KB
/
examples.cpp
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
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <boost/python.hpp>
#include "conversion.h"
namespace py = boost::python;
typedef unsigned char uchar_t;
/**
* Displays an image, passed in from python as an ndarray.
*/
void
display(PyObject *img)
{
NDArrayConverter cvt;
cv::Mat mat { cvt.toMat(img) };
cv::namedWindow("display", CV_WINDOW_NORMAL);
cv::imshow("display", mat);
cv::waitKey(0);
}
/**
* Converts a grayscale image to a bilevel image.
*/
PyObject*
binarize(PyObject *grayImg, short threshold)
{
NDArrayConverter cvt;
cv::Mat img { cvt.toMat(grayImg) };
for (int i = 0; i < img.rows; ++i)
{
uchar_t *ptr = img.ptr<uchar_t>(i);
for (int j = 0; j < img.cols; ++j)
{
ptr[j] = ptr[j] < threshold ? 0 : 255;
}
}
return cvt.toNDArray(img);
}
/**
* Multiplies two ndarrays by first converting them to cv::Mat and returns
* an ndarray containing the result back.
*/
PyObject*
mul(PyObject *left, PyObject *right)
{
NDArrayConverter cvt;
cv::Mat leftMat, rightMat;
leftMat = cvt.toMat(left);
rightMat = cvt.toMat(right);
auto r1 = leftMat.rows, c1 = leftMat.cols, r2 = rightMat.rows,
c2 = rightMat.cols;
// Work only with 2-D matrices that can be legally multiplied.
if (c1 != r2)
{
PyErr_SetString(PyExc_TypeError,
"Incompatible sizes for matrix multiplication.");
py::throw_error_already_set();
}
cv::Mat result = leftMat * rightMat;
PyObject* ret = cvt.toNDArray(result);
return ret;
}
static void init()
{
Py_Initialize();
import_array();
}
BOOST_PYTHON_MODULE(examples)
{
init();
py::def("display", display);
py::def("binarize", binarize);
py::def("mul", mul);
}