Advertisement
ma_mehralian

Python3 C-API

Feb 6th, 2018
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.92 KB | None | 0 0
  1. #include <Python.h>
  2. class PyAdapter {
  3. private:
  4.     PyObject *pModule;
  5.     PyObject *pModel;
  6.     PyObject *pDetectionFunc;
  7.     std::vector< std::pair<char, cv::Rect>> labels;
  8.  
  9.     int PyAdapter::LoadModel() {
  10.         //---- initialize python
  11.         wchar_t* argv[] = { L"test_application" };
  12.         Py_SetProgramName(argv[0]);
  13.         Py_SetPythonHome(L"D:\\Programs\\Python\\Python36-x64");
  14.         Py_Initialize();
  15.         if (!Py_IsInitialized()){
  16.             fprintf(stderr, "Error initializing Python interpreter");
  17.             return -1;
  18.         }
  19.         PySys_SetArgv(1, argv);
  20.  
  21.         //---- set path
  22.         PyObject *sys_path, *path;
  23.         sys_path = PySys_GetObject("path");
  24.         path = PyUnicode_FromString("D:\\python\\py-master\\");
  25.         PyList_Append(sys_path, path);
  26.  
  27.         //---- load module
  28.         PyObject *pName;
  29.         pName = PyUnicode_FromString("detection");
  30.         this->pModule = PyImport_Import(pName);
  31.         Py_DECREF(pName);
  32.         if (this->pModule == NULL) {
  33.             Py_DECREF(this->pModule);
  34.             PyErr_Print();
  35.             fprintf(stderr, "Failed to load module");
  36.             return -1;
  37.         }
  38.  
  39.         //---- load model
  40.         PyObject *pFunc, *pArgs, *pArg;
  41.         pFunc = PyObject_GetAttrString(this->pModule, "model_init");
  42.         if (!pFunc || !PyCallable_Check(pFunc)) {
  43.             if (PyErr_Occurred())
  44.                 PyErr_Print();
  45.             fprintf(stderr, "Cannot run function");
  46.             return -1;
  47.         }
  48.         pArgs = PyTuple_New(1);
  49.         pArg = PyUnicode_FromString("D:\\python\\py-master\\models\\m1.bin");
  50.         PyTuple_SetItem(pArgs, 0, pArg);
  51.         this->pModel = PyObject_CallObject(pFunc, pArgs);
  52.         Py_DECREF(pArgs);
  53.         Py_DECREF(pFunc);
  54.         if (this->pModel == NULL) {
  55.             Py_DECREF(this->pModule);
  56.             PyErr_Print();
  57.             fprintf(stderr, "Model load failed\n");
  58.             return -1;
  59.         }
  60.  
  61.         //---- get detection function
  62.         this->pDetectionFunc = PyObject_GetAttrString(this->pModule, "detect_me");
  63.         if (!this->pDetectionFunc || !PyCallable_Check(this->pDetectionFunc)) {
  64.             if (PyErr_Occurred())
  65.                 PyErr_Print();
  66.             fprintf(stderr, "Cannot run function");
  67.             return -1;
  68.         }
  69.  
  70.         return 0;
  71.     }
  72.  
  73.     int PyAdapter::UnloadModel() {
  74.         Py_XDECREF(pDetectionFunc);
  75.         Py_XDECREF(pModel);
  76.         Py_XDECREF(pModule);
  77.         Py_Finalize();
  78.         return 0;
  79.     }
  80.  
  81. public:
  82.  
  83.     PyAdapter::PyAdapter() {
  84.         if (this->LoadModel() < 0)
  85.             throw std::runtime_error("Error on model load.");
  86.     }
  87.  
  88.     PyAdapter::~PyAdapter() {
  89.         if (this->UnloadModel() < 0)
  90.             throw std::runtime_error("Error on model unload.");
  91.     }
  92.  
  93.     std::vector< std::pair<char, cv::Rect>> &GetLabels() {
  94.         return labels;
  95.     }
  96.  
  97.     int PyAdapter::Detect(cv::Mat &img) {
  98.         PyObject *pArgs, *pArg;
  99.         PyObject *pDetection;
  100.        
  101.         pArgs = PyTuple_New(5);
  102.         PyTuple_SetItem(pArgs, 0, this->pModel);
  103.         pArg = PyByteArray_FromStringAndSize((char*)img.data, img.total() * img.elemSize());
  104.         PyTuple_SetItem(pArgs, 1, pArg);
  105.         PyTuple_SetItem(pArgs, 2, PyLong_FromLong(img.cols));
  106.         PyTuple_SetItem(pArgs, 3, PyLong_FromLong(img.rows));
  107.         PyTuple_SetItem(pArgs, 4, PyLong_FromLong(img.channels()));
  108.         pDetection = PyObject_CallObject(this->pDetectionFunc, pArgs);
  109.         Py_DECREF(pArgs);
  110.         if (pDetection == NULL || !PyByteArray_Check(pDetection)) {
  111.             if (PyErr_Occurred())
  112.                 PyErr_Print();
  113.             fprintf(stderr, "Invalid result\n");
  114.             return -1;
  115.         }
  116.  
  117.         //---- change to opencv mat
  118.         this->labels.clear();
  119.         int NUM_CLASS = 10;
  120.         int SIZE = PyByteArray_Size(pDetection);
  121.         float *data = (float *)PyByteArray_AsString(pDetection);
  122.         Mat det(SIZE / ((NUM_CLASS + 4) * 4), NUM_CLASS + 4, CV_32FC1, data);
  123.         Mat scores = det(cv::Rect(4, 0, det.cols - 4, det.rows));
  124.         vector<pair<char, Rect>> labels;
  125.         double min = 0, max = 0;
  126.         Point minLoc, maxLoc;
  127.         for (int i = 0; i < scores.rows; i++) {
  128.             minMaxLoc(scores.row(i), &min, &max, &minLoc, &maxLoc);
  129.             if (max > 0.5) {
  130.                 int x1 = (int)det.at<float>(i, 0),
  131.                     y1 = (int)det.at<float>(i, 1),
  132.                     x2 = (int)det.at<float>(i, 2),
  133.                     y2 = (int)det.at<float>(i, 3);
  134.                 this->labels.push_back(pair<char, Rect>(maxLoc.x, Rect(x1, y1, x2 - x1, y2 - y1)));
  135.             }
  136.         }
  137.         Py_DECREF(pDetection);
  138.         return 0;
  139.     }
  140.  
  141. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement