I have written a C++ code using opencv, I converted the C++ code as a "DLL" and I need to call a method from this dll in python which receives cv::Mat
as datatype. But I am getting error here. The below are the samples of C++ code and python code.
On googling I found we need to use Boost library but am not sure how to convert Python mat
to C++ cv::Mat
and how to make interface between them.
C++ dll code:
DLLEXPORT int FromPython ( cv :: Mat InputSrc) {
imshow ( "FromPython", InputSrc );
return 0;
}
Python Code
import cv2 as cv
from ctypes import cdll
cap = cv.VideoCapture(0)
while(1):
ret, frame = cap.read()
cv.imshow('frame',frame)
mydll = cdll.LoadLibrary('C:\Users\Documents\FromPythonDLL.dll')
i = mydll.FromPython(frame)
print(i)
k = cv.waitKey(1) & 0xff
if k == 27:
break
cap.release()
cv.destroyAllWindows()
You can have a look at the OpenCV Python wrapper. In the OpenCV folder in modules/python/src2/cv2.cpp (depending on the version, I use OpenCV 2.4) there are some functions called pyopencv_to used by the OpenCV Python wrapper. One of those is used to convert PyObject to cv::Mat. Your "FromPython" function needs to get PyObject as input. I personally use boost::python::object to pass the numpy arrays returned by the Python OpenCV functions to the C++ function/class. You should end up having something like this in C++:
Then the function where you can access to cv::Mat will look like:
This function to be accessible from Python needs to be wrapped in a BOOST_PYTHON_MODULE. Soemthing like:
Then in Python you can call your function from the Python module created by the Boost wrapper. I am using Linux so I compile the code above to get an dynamic library (.so). I am not sure how different it is in Windows. I can access to the module from the dynamic library as:
You can probably avoid the use of Boost but I haven't tried other ways and I found Boost convenient to wrap C++ classes. NOTE: I haven't tested this code as I stripped it from a project but I hope it can still be useful.