Working OpenCV python bindings
I have long cursed the absence of working python bindings for OpenCV. However, with the recent release of OpenCV 2.0, there are new python bindings in the distribution that not only “just work,” but behave in an unexpected and wonderful way: OpenCV functions can manipulate numpy arrays in-place! It took an afternoon to get things properly compiled and seaworthy, but I can now use OpenCV’s Filter2D method to convolve a numpy array without any memory copies.
Compile OpenCV 2.0
- Download OpenCV from WillowGarage. Resist the temptation to use autotools. Use cmake instead. The INSTALL file has the details. Read the INSTALL file. Learn from my mistakes.
- Run make install. The python bindings will be installed… to the wrong place. If you’re using Ubuntu, you should move the installed module from /usr/local/python2.6/site-packages to /usr/local/python/dist-packages
- run ipython and import cv. If this works, you’re good to proceed. If if fails, you’ll be tempted to import opencv.cv. Resist. This is the old binding… this road ends in tears.
Some sample code
import cv
import numpy
a = numpy.arange(256).reshape((16,16)).astype('u1')
ipl = cv.CreateImageHeader(a.shape, cv.IPL_DEPTH_8U, 1)
cv.SetData(ipl, a, a.shape[1])
cv.Flip(ipl)
Observe the contents of the a array before and after the call to Flip. You’ll see that the OpenCV operation has operated on the underlying numpy data.
Now all I have to do is develop some simple SWIG bindings for PointGrey FlyCap SDK, and I can do much of my computer vision stuff in Python.
Update
Much to my surprise, HighGUI works in a python thread. The following code should be run in ipython. I can test out OpenCV operations on im and see the results live in the HighGUI window. Take that, C++
import cv
import threading
orig = cv.LoadImage("test.png")
im = cv.CloneImage(orig)
def waitkey():
cv.NamedWindow("debug")
while True:
cv.ShowImage("debug", im)
cv.WaitKey(45)
threading.Thread(target=waitkey).start()
Joost
January 6, 2010
thanks, this sounds encouraging and I’m about to follow your example.
Adrian
January 8, 2010
When I tried this, on Ubuntu 9.04, the module (cv.so) which had to be moved, had to be moved from: /usr/local/lib/python2.6/site-packages to /usr/local/lib/python2.6/dist-packages. I assume the omission of /lib/ was just a typo, but I thought the clarification might be useful for folks.