I am going to send a c++ array to a python function as numpy array and get back another numpy array. After consulting with numpy
We will be passing 2D array to python function written in file pyCode.py:
def pyArray (a):
print ("Contents of a :")
print (a)
c = 0
return c
c_code.cpp#include
#include
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include
float Array [] = {1.2, 3.4, 5.6, 7.8};
int main (int argc, char *argv[])
{
float *ptr = Array;
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs;
npy_intp dims[1] = { 4 };
PyObject *py_array;
setenv("PYTHONPATH",".",1);
Py_Initialize ();
pName = PyUnicode_FromString ("pyCode");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
import_array ();
py_array = PyArray_SimpleNewFromData(1, dims, NPY_FLOAT, ptr);
pArgs = PyTuple_New (1);
PyTuple_SetItem (pArgs, 0, py_array);
pFunc = PyDict_GetItemString (pDict, (char*)"pyArray");
if (PyCallable_Check (pFunc))
{
PyObject_CallObject(pFunc, pArgs);
} else
{
cout << "Function is not callable !" << endl;
}
Py_DECREF(pName);
Py_DECREF (py_array);
Py_DECREF (pModule);
Py_DECREF (pDict);
Py_DECREF (pFunc);
Py_Finalize ();
return 0;
}
compile the code:
g++ -g -fPIC c_code.cpp -o runMe -lpython3.5m -I/usr/include/python3.5m/
file: cv_mat_code.cpp
#include
#include
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include
#include
using namespace cv;
using namespace std;
int main (int argc, char *argv[])
{
float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Mat mat1 (cv::Size (5, 2), CV_32F, data, Mat::AUTO_STEP);
int row = 0;
float *p = mat1.ptr(row);
cout << "Mat" << mat1 <
Compile the code:
g++ -g -fPIC cv_mat_code.cpp -o runMe -lpython3.5m -I/usr/include/python3.5m/ -I/usr/include/ -lopencv_core -lopencv_imgproc -lopencv_highgui