Noam Lewis
Email: <jones.noamle AT SPAMFREE gmail DOT com>
I figured a convenient way to experiment with Open CV using Python (on Windows): Since Python 2.5, the ctypes package is included, which allows you to access shared libraries (in Windows - DLLs) and call functions from them.
I used this package to quickly build a simple application with OpenCV's HighGui: The main advantage is that you don't need to compile anything - you simply use the supplied DLL's that you get with the Open CV package.
import ctypes
highgui = ctypes.cdll.LoadLibrary(r'C:\Program Files\OpenCV\bin\highgui100.dll')
# Other dlls you might wanna use:
# cv = ctypes.cdll.LoadLibrary(r'C:\Program Files\OpenCV\bin\cv100.dll')
# cxcore = ctypes.cdll.LoadLibrary(r'C:\Program Files\OpenCV\bin\cxcore100.dll')
class Window(object):
def __init__(self, name="Window"):
self.name = name
highgui.cvNamedWindow(name, 1)
def move(self, x, y):
highgui.cvMoveWindow(self.name, x, y)
def show_frame(self, frame):
highgui.cvShowImage(self.name, frame)
class Capture(object):
capture = None
def __init__(self):
raise NotImplementedError("Virtual class")
def query_frame(self):
return highgui.cvQueryFrame(self.capture)
def __del__(self):
highgui.cvReleaseCapture(self.capture)
class CameraCapture(Capture):
def __init__(self, device = -1):
self.capture = highgui.cvCreateCameraCapture(-1)
def wait_key(delay = 0):
return highgui.cvWaitKey(delay)
def handle_events():
wait_key(1)And now:
capture = CameraCapture()
window = Window("Test")
while True:
frame = capture.query_frame()
window.show_frame(frame)
handle_events()
Note
1. CTypes does NOT automatically supply type information for functions or structures (unlike CInvoke, which is yet to be released...)
- So if you want (or need) to access the internal structures represented by the pointers you receive, you'll have to manually declare them, like this example:
class cvSize(ctypes.Structure):
_fields_ = [('width', ctypes.c_int),
('height', ctypes.c_int),
]
class IplImage(ctypes.Structure):
_fields_ = [('nSize', ctypes.c_int),
('ID' , ctypes.c_int),
('nChannels', ctypes.c_int),
('alphaChannels', ctypes.c_int),
('depth', ctypes.c_int),
('colorModel', ctypes.ARRAY(ctypes.c_char, 4)),
('channelSeq', ctypes.ARRAY(ctypes.c_char, 4)),
('dataOrder', ctypes.c_int),
('origin', ctypes.c_int),
('align', ctypes.c_int),
('width', ctypes.c_int),
('height', ctypes.c_int),
('roi', ctypes.c_int), # actually ptr
('maskROI', ctypes.c_int),
('imageId', ctypes.c_int),
('tileInfo', ctypes.c_int),
('imageSize', ctypes.c_int),
('imageData', ctypes.c_char_p),
('widthStep', ctypes.c_int),
('BorderMode', ctypes.ARRAY(ctypes.c_int, 4)),
('BorderConst', ctypes.ARRAY(ctypes.c_int, 4)),
('imageDataOrigin', ctypes.c_char_p),
]2. CTypes will not supply you with #define'd values - my quick, dirty and simple approach was to parse the .h files and create a python module that contains all the defines.
