gcc -shared -o libsimpleopencvtest.so -fPIC ./simple_opencv_test.cpp -lopencv_core -lopencv_highgui -lopencv_objdetect -lopencv_imgproc -lopencv_features2d -lopencv_ml -lopencv_calib3d -lopencv_video
python simple_opencv_test.py
| #include <opencv2/opencv.hpp> | |
| /* | |
| C++ program goes here as usual (put whatever you like, can use other libraries or classes etc.) | |
| */ | |
| cv::Mat doStuff(cv::Mat img) | |
| { | |
| // Modify the image in C++ OpenCV | |
| img += 0.1 * 255; | |
| return img; | |
| } | |
| extern "C" void modifyImg(unsigned char *im, int width, int height) | |
| { | |
| // Image gets passed in from external (e.g. Python) as ptr | |
| cv::Mat image = cv::Mat(width, height, CV_8UC3, im); | |
| image = doStuff(image); | |
| // Do not need to return anything because we are using pointers... | |
| } |
| import ctypes as C | |
| import numpy as np | |
| # Must put full path to the '.so' file | |
| my_cpp_opencv_lib = C.cdll.LoadLibrary('/home/alex/opencv_test/libsimpleopencvtest.so') | |
| res = np.ones(dtype=np.uint8, shape=(100, 100, 3)) | |
| # Pass the Numpy array in from Python | |
| img_ptr = res.ctypes.data_as(C.POINTER(C.c_ubyte)) | |
| my_cpp_opencv_lib.modifyImg(img_ptr, res.shape[1], res.shape[0]) | |
| # See how the array has been modified | |
| print(res) |