Boost::Python with OpenCV

In my previous post Configuring Boost::Python and Hello Boost, I have shown how to configure Boost::Python. I have managed to use OpenCV C++ with Python, using Boost::Python. I have been able to load and show an image successfully.

OpenCV C++:

First, write a simple function which will load and if required show an image using opencv. I have named it opencvtest.cpp

using namespace cv;
using namespace std;

int load(string filename)

    Mat img = imread(filename,CV_LOAD_IMAGE_COLOR);
    return 1;


Wrap the above function using Boost::Python.

using namespace boost::python;

Boost::Python wrapping is successfully done. I tried using bjam, but there were many complications. So, I am sticking to make.


PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)

# location of the Boost Python include files and library

BOOST_INC = /usr/include
BOOST_LIB = /usr/lib

# your filename here
TARGET = opencvtest

$(TARGET).so: $(TARGET).o
	g++ -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so `pkg-config --libs opencv` `pkg-config --cflags opencv`

$(TARGET).o: $(TARGET).cpp

Notice `pkg-config` added in the Makefile.

$ make

opencvtest.o and binaries will be created.

Now, use the wrapper with Python.


import time
def timetest():
    image = "filename.jpg"
    t0 = time.time()
    from import LoadImage
    img = LoadImage(image)
    t1 = time.time()
    from opencvtest import load
    img2 = load(image)
    t2 = time.time()
    print "Time taken to load image using module:",
    print t1-t0
    print "Time taken to load image using boost wrapper:",
    print t2-t1


Notice the significant difference between run time span of both the methods.
Here’s the complete gist.
Even I couldn’t believe that I could easily wrap OpenCV functions using Boost::Python. Now, I am planning to use Boost::Python to wrap OpenTLD and make a python port as well as wrap some important and time consuming iterations, functions using boost so that run-time speed of SimpleCV can be increased.
P.S. Going to Hyderabad to meet my brother. This is going to be exciting.


One thought on “Boost::Python with OpenCV

  1. I haven’t tried this yet but I searched every where for a tutorial on just this about a year ago, thanks!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s