15 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
16 #include <numpy/arrayobject.h>
32 UERROR(
"Cannot initialize Python detector, the path is not valid: \"%s\"=\"%s\"",
33 Parameters::kPyDetectorPath().
c_str(),
path_.c_str());
37 pybind11::gil_scoped_acquire acquire;
40 if(!matcherPythonDir.empty())
42 PyRun_SimpleString(
"import sys");
43 PyRun_SimpleString(
uFormat(
"sys.path.append(\"%s\")", matcherPythonDir.c_str()).c_str());
50 UDEBUG(
"PyImport_Import() beg");
52 UDEBUG(
"PyImport_Import() end");
58 UERROR(
"Module \"%s\" could not be imported! (File=\"%s\")", scriptName.c_str(),
path_.c_str());
65 pybind11::gil_scoped_acquire acquire;
91 UASSERT(!image.empty() && image.channels() == 1 && image.depth() == CV_8U);
92 std::vector<cv::KeyPoint> keypoints;
93 cv::Mat imgRoi(image, roi);
99 UERROR(
"Python detector module not loaded!");
103 pybind11::gil_scoped_acquire acquire;
107 PyObject * pFunc = PyObject_GetAttrString(
pModule_,
"init");
110 if(PyCallable_Check(pFunc))
112 PyObject *
result = PyObject_CallFunction(pFunc,
"i",
cuda_?1:0);
116 UERROR(
"Call to \"init(...)\" in \"%s\" failed!",
path_.c_str());
129 UERROR(
"Cannot find method \"detect(...)\" in %s",
path_.c_str());
141 UERROR(
"Cannot call method \"init(...)\" in %s",
path_.c_str());
149 UERROR(
"Cannot find method \"init(...)\"");
158 npy_intp dims[2] = {imgRoi.rows, imgRoi.cols};
159 PyObject* pImageBuffer = PyArray_SimpleNewFromData(2, dims, NPY_UBYTE, (
void*)imgRoi.data);
162 UDEBUG(
"Preparing data time = %fs",
timer.ticks());
164 PyObject *pReturn = PyObject_CallFunctionObjArgs(
pFunc_, pImageBuffer,
NULL);
167 UERROR(
"Failed to call match() function!");
172 UDEBUG(
"Python detector time = %fs",
timer.ticks());
174 if (PyTuple_Check(pReturn) && PyTuple_GET_SIZE(pReturn) == 2)
176 PyObject *kptsPtr = PyTuple_GET_ITEM(pReturn, 0);
177 PyObject *descPtr = PyTuple_GET_ITEM(pReturn, 1);
178 if(PyArray_Check(kptsPtr) && PyArray_Check(descPtr))
180 PyArrayObject *arrayPtr =
reinterpret_cast<PyArrayObject*
>(kptsPtr);
181 int nKpts = PyArray_SHAPE(arrayPtr)[0];
182 int kptSize = PyArray_SHAPE(arrayPtr)[1];
183 int type = PyArray_TYPE(arrayPtr);
184 UDEBUG(
"Kpts array %dx%d (type=%d)", nKpts, kptSize,
type);
188 float* c_out =
reinterpret_cast<float*
>(PyArray_DATA(arrayPtr));
189 keypoints.reserve(nKpts);
190 for (
int i = 0;
i < nKpts*kptSize;
i+=kptSize)
192 cv::KeyPoint kpt(c_out[
i], c_out[
i+1], 8, -1, c_out[
i+2]);
193 keypoints.push_back(kpt);
196 arrayPtr =
reinterpret_cast<PyArrayObject*
>(descPtr);
197 int nDesc = PyArray_SHAPE(arrayPtr)[0];
199 int dim = PyArray_SHAPE(arrayPtr)[1];
200 type = PyArray_TYPE(arrayPtr);
204 c_out =
reinterpret_cast<float*
>(PyArray_DATA(arrayPtr));
207 cv::Mat
descriptor = cv::Mat(1,
dim, CV_32FC1, &c_out[
i]).clone();
214 UWARN(
"Expected tuple (Kpts 3 x N, Descriptors dim x N), returning empty features.");
218 Py_DECREF(pImageBuffer);