-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpyclassification.cpp
98 lines (77 loc) · 2.24 KB
/
pyclassification.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
86
87
88
89
90
91
92
93
94
95
96
97
#include "pyclassification.h"
PyClassification::PyClassification()
{
PyInit();
//process();
//PyClose();
}
PyClassification::~PyClassification()
{
PyClose();
}
void PyClassification::PyInit()
{
Py_Initialize();
//qDebug() << "Python Initialized";
// set system path to find correct python script
// @ZC TODO: using relative path
//string chdir_cmd = string("sys.path.append(\'/home/starasia/pylon_cv/python\')");
string chdir_cmd = string("sys.path.append(\'../python\')");
const char* cstr_cmd = chdir_cmd.c_str();
PyRun_SimpleString("import sys");
PyRun_SimpleString(cstr_cmd);
// import module(classification.py), it's a python script file name
pModule = PyImport_ImportModule("classification");
if (!pModule)
{
qDebug() << "get module failed!";
//exit (0);
}
// import function from the module
pFunc = PyObject_GetAttrString(pModule, "main");
if (!pFunc)
{
qDebug() << "get func failed!";
//exit (0);
}
}
QString PyClassification::process(cv::Mat image)
{
//cv::Mat img = cv::imread("../images/1.jpg", 1);
cv::Mat small_img;
cv::resize(image, small_img, Size(224, 224), 0, 0);
// python-opencv version must be v3.1.0
// Native-opencv version must be v3.0.0 ~ v3.4.0
pNDArray = pycvt::fromMatToNDArray(small_img);
// counld add more PyObj arguments before "NULL" indicator
pResult = PyObject_CallFunctionObjArgs(pFunc, pNDArray, NULL);
/* This method is to pass non-object para
pParam = Py_BuildValue("(s)", "MSG from QT");
pResult = PyEval_CallObject(pFunc, pParam);
*/
const char* resLabel = NULL;
float resConfidence = 0.0;
if(pResult)
{
if(PyArg_Parse(pResult, "(sf)", &resLabel, &resConfidence))
{
qDebug() << resLabel << ":" << resConfidence;
}
}
is_processed = true;
return QString(resLabel);
}
void PyClassification::PyClose()
{
// Decrement the reference count for python object, prevent memory leak
// PyObject must NOT be NULL.
Py_DECREF(pModule);
//Py_DECREF(pParam);
Py_DECREF(pFunc);
if (is_processed)
{
Py_DECREF(pNDArray);
Py_DECREF(pResult);
}
Py_Finalize();
}