Skip to content

Instantly share code, notes, and snippets.

@clungzta
Last active August 21, 2018 09:53
Show Gist options
  • Select an option

  • Save clungzta/11670e4c274812ef92e519c7f0d8577b to your computer and use it in GitHub Desktop.

Select an option

Save clungzta/11670e4c274812ef92e519c7f0d8577b to your computer and use it in GitHub Desktop.
Super Simple OpenCV C++ to Python Interface

Compile

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

Run

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment