Starting from the work of Michael Otto, I have hacked together the beginnings of a ctypes-based wrapper for OpenCV. You may download the code and examples here code and examples from UNC Python Tools on SourceForge. If there is enough interest I’ll move it to sourceforge.
I have heard rumors of other efforts to wrap OpenCV with ctypes but couldn’t find any code other than Michael’s. Wanting to get on with my work, I spent a couple of days bashing this together. If someone else comes out with a better wrapper, I’ll gladly switch. In the meantime this one gets the job done.
You’ll, of course, need to download OpenCV and get the dll’s on your path. Then you can use this module like this:
from CVtypes import cv
win = 'Show Cam'
cv.NamedWindow(win)
cap = cv.CreateCameraCapture(0)
while cv.WaitKey(1) != 27:
img = cv.QueryFrame(cap)
cv.ShowImage(win, img)
I prefer wxPython to the old-school highgui included with OpenCV so I included a couple of functions to make that easy. Here is an example using wx:
import wx
from CVtypes import cv
class myFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Try CV')
self.SetClientSize((320,240))
self.cap = cv.CreateCameraCapture(0)
self.Bind(wx.EVT_IDLE, self.onIdle)
def onIdle(self, event):
img = cv.QueryFrame(self.cap)
self.displayImage(img)
event.RequestMore()
def displayImage(self, img, offset=(0,0)):
bitmap = cv.ImageAsBitmap(img)
dc = wx.ClientDC(self)
dc.DrawBitmap(bitmap, offset[0], offset[1], False)
class myApp(wx.App):
def OnInit(self):
self.frame = myFrame()
self.frame.Show(True)
return True
app = myApp(0)
app.MainLoop()
Most of the functions have exactly the same prototype in Python as in C. Using the amazing power of the prototypes in ctypes I’ve got it type checking most of the arguments and it allows defaults where they are defined in the C prototypes. OpenCV uses lots of type puns, I worry that this is going to bite me sooner or later.
Ctypes allows for output arguments that are returned rather than passing in a pointer. So for functions like GetMinMaxHistValue instead of allocating and passing in pointers you instead call it like:
min_val, max_val, min_idx, max_idx = cv.GetMinMaxHistValue(hist)
Many of the structured values have __repr__ methods so they can be printed.
Another amazing ctypes feature is the ability to specify types with class objects that have a from_param method. I used this to allow calling functions that expect a C array with a Python list or tuple. So, for example, this bit creates a 2D histogram
hist = cv.CreateHist(2, [18,16], cv.HIST_ARRAY, [[0,180][0,255]]) cv.CalcHist([hue,sat], hist)
Check out the code around cv.HaarDetectObjects for another great ctypes feature. I’m using the errcheck function to hide the ugly casting necessary to extract the list of cv.Rect from the cv.Seq that gets returned. This should serve as a model for other functions with ugly results.
Also, check out the cv.ImageAsBuffer function to see how to make a Python buffer object from an image. I haven’t tried it yet but I’m guessing this is a route to making numpy arrays from images.
For documentation you’ll have to use the source, Luke. The code needs lots more work and is likely rife with bugs. I have only used a tiny fraction of the functions. But ctypes is so easy to use, I expect you’ll be able to figure out what is going wrong and fix it.
I’m using this daily to experiment with web-cams as replacements for mechanical switches for kids with movement disorders. As I find bugs I’ll add them to the archive. If you find a bug, fix it, and let me know.
82 comments
Thank you so much for doing this! I’ve been waiting forever for an OpenCV Python wrapper that I could actually get to work.
Just FYI, you need 1.0 or later of ctypes; it failed to run until I upgraded.
I’m glad you find it useful. And yes, it depends on 1.0 of ctypes. If you find problems or make enhancements let me know. So far, everything I need seems to just be working.
Wow! Very cool. Thanks!
I’m trying to access the cvAux library, which doesn’t have default Python bindings. I’m amazed that it’s actually starting to work.
Do you know if this was generated somehow? Or was it a manual process?
I’m glad you find it useful. Michael generated the original, as I understand it, by processing the documentation with some simple regular expressions. I then hacked his output with more regular expressions and some manual editing.
I would be very pleased to get your changes if you are successful wrapping cvAux.
Here’s some code for nonblocking camera capture:
http://www.connellybarnes.com/code/python/nonblocking_showcam.zip
Thanks Connelly!
This is great! Nice work. I fussed around for a while trying to get the included SWIG version working but no luck. Getting this working was a snap.
Dumb question – why no ports of the constants, like CV_THRESH_BINARY? It is a tad annoying to locate them. Any tips?
Not dumb at all. The answer is, neither Michael nor I caught it. I look for that kind of stuff in the OpenCV .h files. Send me some values and I’ll get them into the code.
Do you know a good way of converting back and forth between OpenCV image types and PIL types?
I haven’t needed to do that yet, but I see the IM package claims to include it: http://members.tripod.com/~edcjones/pycode.html (says it is in mrquery now).
ohh, going to try right now on ubuntu feisty. There’s a wrapper in feisty distribution based on swig, and I am messing with it for weeks to go over the errors. So I hope in this one the functions i missed will work…
stupid me.. of course it’s for win only, and i don’t know how to modify it at all… will try to explore deeper…
Very little of this code is win dependent. ctypes works on Linux and Mac. I think only the linkage specs at the very top has to change.
managed to run it…! Anybody tried something with larger data sets/files with the wrapper? I wouldn’t really be happy if i rewrite my whole noobish project and then just read again: segmentation fault (core dumped).
I have processed minutes of video at 15fps with no problems. I don’t think python or the thin wrapper is introducing any limitations on the capabilities of OpenCV with respect to dataset size.
I tried this on a fresh install on Ubuntu Feisty, python 2.5.c1, but I’m encountering:
OSError: cxcore100: cannot open shared object file: No such file or directory
Can you post your mods to get this to work on Linux? I have OpenCV installed, and the path to the libraries /usr/local/lib is on my path. I’ve successfully built the samples and run them using Eclipse, just having Python/ctypes hiccups.
Thanks!
Ok, solved my problem. In CVtypes.py: (1) import os, (2) for each _xxDLL = cdll.mmm, replace with
if os.name == “posix”:
_xxDLL = cdll.LoadLibrary(”libcvxyz.so.1″)
elif: os.name == “nt”:
_xxDLL = cdll.mmm
Make sure you add the libraries to your path.
good solution. I did similar, but not flexible, just replaced the library names.
Hi, the solution is nice, but I’m a bit unclear on what it solves that the SWIG interface doesn’t.
Wrt to converting between numpy arrays and cvImages, isn’t it possible to use the adaptors.py file with the ctypes interface?
I couldn’t get the SWIG interface to work properly.
I’m not familiar with adaptors.py so I can’t help you there. Conversion to and from various representations shouldn’t be too complicated.
Tarjel Huse:
the SWIG python wrapper is very unfinished, so you can’t count on some features, and have to be very carefull with the memory managment(in Python!). But i still continue my project with the SWIG version, since I hope the situation with it will get much better in future, since it’s part of the official opencv cvs and there seem to be some attempts to make it better. But if this ctypes wrapper would get in the cvs, i would probably rewrite my project…
Thanks a lot. This works great on Mac OS X too (Had to compile ctypes from source. DarwinPorts version crashed!). As someone else also pointed out above, you just need to point to the correct *.dylib in CVtypes.py
You should consider making this a SourceForge project. This should definitely be very useful to a lot of people.
[...] modified my former post Python OpenCV wrapper using ctypes to reflect the new version available on SourceForge. This update includes lots of constants from [...]
Harish, if you send me the change required for Mac OS X, I’ll get it in the release.
Hello, thanks for the update in cvtypes by 17th May.
I want to try using ctypes because some SWIG interface functions like cvCalibrateCamera2 crash when I try to call it. By the way, anyone has got this function working in Python?
I have another question. I think its a stupid thing but, how can I access cvMat type elements? (class LP_cvMat as I’ve seen in cvtypes). For example, with swig python interface I can do:
>>> matrix_a=cvCreateMat(2,3,CV_32FC1)
>>> matrix_a[0,0]=10
>>> print matrix_a[0,0]
10.0
——–
But with cvtypes it gives an error:
>>> matrix_b=cv.CreateMat(2,3,CV_32FC1)
>>> matrix_b[0,0]=10
Traceback (most recent call last):
File “”, line 1, in -toplevel-
matrix_b[0,0]=10
TypeError: sequence index must be integer
I’ve seen I can access a cvMat object by matrix_b.contents, since:
>>> print matrix_b.contents.__class__
——–
But If I also try:
>>> matrix_b.contents[0,0]=10
Traceback (most recent call last):
File “”, line 1, in -toplevel-
matrix_b.contents[0,0]=10
TypeError: object does not support item assignment
>>> matrix_b.contents(0,0)=10
SyntaxError: can’t assign to function call
———-
I’ve also noted that something in contents method is wrong because:
>>> print matrix_a.cols
3
>>> print matrix_b.contents.cols
2
——
‘rows’ value is even more incorrect.
Any clues about how can I do this properly with ctypes?
Thanks in advance
Cheers,
Jorge
Jorge,
First, let me say I haven’t used any of that stuff yet.
The first issue is because CreateMat returns a POINTER(CvMat) instead of a CvMat. I bet with a trick in the prototype we could make it deference the pointer. For the moment, calling it like cv.CreateMat(2,3,CV_32FC1)[0] will give you the CvMat instead of a pointer.
The second issue you point out is because of a missing field in the declaration. A look at the .h file reveals they have another int in there. The correct declaration of CvMat should be:
class CvMat(Structure): _fields_ = [("type", c_int), ("step", c_int), ("refcount", c_void_p), ("hdr_refcount", c_int), ("data", c_void_p), ("rows", c_int), ("cols", c_int)]I’ll fix it in CVS and get out a new release soon.
Jorge,
One more thing. You may well know, but Numpy has very nice matrix support. I’d use that over the stuff in OpenCV.
Hello Gary, thanks a lot for the quick response. Yes, now It returns a CvMat type, but:
>>> matrix_a=cv.CreateMat(2,3,CV_32FC1)[0]
>>> print matrix_a.__class__
>>> matrix_a[0,0]=10
Traceback (most recent call last):
File “”, line 1, in -toplevel-
matrix_a[0,0]=10
TypeError: object does not support item assignment
—-
I still cant make an assignment to the cvMat matrix. I already know the Numpy thing, but I really need to use cvMat objects since the OpenCv functions I want to use need to be feed with cvMat data types, and I dont want to make an intermediate conversion. I want to do something like this, as Ive said in my first post:
>>> matrix_b=cvCreateMat(2,3,CV_32FC1)
>>> matrix_b[0,0]=10
>>> print matrix_b[0,0]
10.0
>>>
—-
I’ve corrected CVtypes.py and the rows/cols thing is still wrong…
>>> print matrix_a.rows
10944256
>>> print matrix_a.cols
2
…
>>> print matrix_b.rows
2
>>> print matrix_b.cols
3
——
Thanks a lot for your help, if I can get running ctypes for opencv and using the functions I need, it will be really useful.
Cheers.
Email me. The corrected version reports the correct number of rows and columns for me. I’ve updated the .zip at SourceForge, download it again.
The wrapper is NOT the swig version. The swig version does a bunch of stuff we’re not yet doing. If it works for you, go for it. In order to accomplish what you want, you/we need to add some methods to CvMat to enable subscripting with Python syntax or use the OpenCV methods like cv.Set1D and friends. The great thing about open source and ctypes is you’re free to add features yourself. Good luck.
I have updated the CVS repository at sourceforge with the updates sent by Viji Periapoilan and Sim Harbert of GaTech. Thanks guys.
I didnt see anyone post it, though i might have missed it, but to get this to work on OS X you need to change the ‘.so.1′ to ‘.dylib’ for all three libraries.
Thanks for the reminder to fix that, it was mentioned once before. I have modified the source in CVS to (I think) handle OS X. Please check it out and let me know.
Hey gb. Its working now.
Is it possible to mix the SWIG wrapper with your CVtypes? I also need to be able to put data into a cvMat for a camera calibration, however the cvCameraCalibration seems to thing a Nx1 cvMat is not a vector so i would like to try yours. Will it give proper results?
Kfir, I don’t know. I haven’t tried that. I think it should work.
Im getting the following error:
a = cvtype.cvCalibrateCamera2(object_points, image_points, points_count, self._images[0]._image_size, intrinsic_matrix, distortion_coeffs, rotation_vectors, translation_vectors)
ctypes.ArgumentError: argument 1: : expected LP_CvMat instance instead of CvMat
the first 3 are cvMat made with opencv.cv the last 4 are made with CVtypes.
The error says it expects a POINTER(CvMat) and you are giving it a CvMat. Try byref(object_points). I don’t know if that will work. Just grasping at straws. I haven’t used any of that stuff.
didnt work, but thaks anyway. Ill guess ill have to figure out why cvCalibrateCamera refuses to accept a Nx1 or 1xN matrix as a vector
I’m trying to use the ctypes python extension with Python 2.4 in windows. When I run the “from CVtypes import cv”, I get the following error:
exceptions.TypeError Traceback (most recent call
last)
C:\Program Files\OpenCV\samples\python\
C:\Python24\lib\CVtypes.py
921 # Releases header
922 cvReleaseImageHeader = cfunc(’cvReleaseImageHeader’, _cxDLL, None,
–> 923 (’image’, ByRefArg(POINTER(IplImage)), 1), ## IplImage** image
924 )
925
C:\Python24\lib\CVtypes.py in cfunc(name, dll, result, *args)
375 atypes.append(arg[1])
376 aflags.append((arg[2], arg[0]) + arg[3:])
–> 377 return CFUNCTYPE(result, *atypes)((name, dll), tuple(aflags))
378
379 class ListPOINTER(object):
C:\Python24\lib\site-packages\ctypes\__init__.py in CFUNCTYPE(restype, *argtypes
)
88 return _c_functype_cache[(restype, argtypes)]
89 except KeyError:
—> 90 class CFunctionType(_CFuncPtr):
91 _argtypes_ = argtypes
92 _restype_ = restype
TypeError: Error when calling the metaclass bases
item 1 in _argtypes_ is not a valid C type
Do I need to use python 2.5 in order to use the ctypes extension? Thanks,
Neil Johnson
Neil, It works fine for me under Python 2.4.4
The problem you’re having seems do be down in ctypes initialization. Make sure the version of ctypes you have is the latest.
gb
[...] is opencv going in the direction of ctypes (as was previously mentioned, and like gary bishop: http://wwwx.cs.unc.edu/~gb/wp/blog/2007/02/04/python-opencv-wrapper-using-ctypes/) or is swig still [...]
Can anybody tell How to use cvaux module in python . Please help me. I need it urgently.
Thanks in advance.
[...] was developed by UNC undergraduate student Arthur Greenside using python, wxPython, and CVtypes a ctypes-based wrapper for OpenCV. This project was supported by a grant from the Mozilla [...]
Can any body post a example using “cvaux”
Looks great! I could run it and tried to convert some of the samples coming with OpenCV 1.0 in the samples/python folder. If I write some samples using CVtypes, I would like to share them soon. Thank you very much for your effort and sharing knowledge.
[...] http://wwwx.cs.unc.edu/~gb/wp/blog/2007/02/04/python-opencv-wrapper-using-ctypes/ [...]
Use ctypes.cast to address element in CvMat
just like this:
m=cv.CreateMat(2,10,CV_32FC1)
ddm=ctypes.cast(m.data,POINTER(c_float*10))
ddm[0][0]=10.1
sorry ,the previous method is wrong, the following solution is good
m=cv.CreateMat(200,100,CV_32FC1)
cv.ShowImage(”show”,m)
ddm=ctypes.cast(m.contents.data,POINTER(c_char))
ddm[1232]=255
ddm[232]=255
cv.ShowImage(”show”,m)
I made a Linux Version…
import opencv
from opencv import highgui
import Image
import wx
class myFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, ‘Try CV’)
self.SetClientSize((320,240))
self.cap = highgui.cvCreateCameraCapture(0)
self.Bind(wx.EVT_IDLE, self.onIdle)
def onIdle(self, event):
img = highgui.cvQueryFrame(self.cap)
self.displayImage(img)
event.RequestMore()
def displayImage(self, img, offset=(0,0)):
pilImage = opencv.adaptors.Ipl2PIL(img)
mywximage = wx.EmptyImage(pilImage.size[0],pilImage.size[1])
mywximage.SetData(pilImage.convert(’RGB’).tostring())
bitmap = wx.BitmapFromImage(mywximage)
dc = wx.ClientDC(self)
dc.DrawBitmap(bitmap, offset[0], offset[1], False)
class myApp(wx.App):
def OnInit(self):
self.frame = myFrame()
self.frame.Show(True)
return True
app = myApp(0)
app.MainLoop()
I have some CvMat matrices stored in individual .yml files (they were saved there using the cvSave function in c-opencv.
Now, I need to load these matrices in python …
Does anyone can tell me a way to do that??
thanks in advance
the python-opencv function cvLoad will return me a pointer to void (c_void_p) … how do I cast that to CvMat in Python??
[...] had some fun with Gary Bishop’s OpenCV Python wrapper this morning. I wanted to try out OpenCV for detecting faces using a web cam. This could be used [...]
Albino, use cvGetMat(*)
I am a novice in programming.
someone can help me to calculate the optical flow
between two images with pyOpenCV?
class WebCamSnap(Thread):
imgPil=None
imgIpl=None
def __init__(self):
Thread.__init__(self)
self.camara=highgui.cvCreateCameraCapture (0)#Device()
#threading.Thread.__init__(self)
self.imgIpl=highgui.cvQueryFrame(self.camara)
imgPil=[]
highgui.cvNamedWindow (’TESTECAM’, highgui.CV_WINDOW_AUTOSIZE)
#print “!!!window OK”
#fps = 30
#frame_size = cv.cvGetSize (self.camara)
def snap(self):
self.imgIpl=highgui.cvQueryFrame(self.camara)
frame=self.imgIpl
highgui.cvShowImage (’TESTECAM’, frame)
self.imgPil=adaptors.Ipl2PIL(self.imgIpl)
self.imgPil=list(self.imgPil.getdata())
Thanks for this nice work. I’m very happy about using it but I’ve encountered a problem.
Do you know how to initialize fonts? If I give FONT_HERSHEY_PLAIN for font face and 1.0 for both hscale and vscale, it just throws out segmentation fault.
I gave:
font=cv.InitFont(cv.FONT_HERSHEY_PLAIN, 1.0, 1.0)
Any ideas? Thanks.
thanks for doing this. anybody have any insights into this error:
user-0ccen60:~/Documents/python martinzahra$ python test_face_cvtypes.py
Traceback (most recent call last):
File “test_face_cvtypes.py”, line 1, in ?
from CVtypes import cv
File “/Users/martinzahra/Documents/python/CVtypes.py”, line 598
@classmethod
^
SyntaxError: invalid syntax
——
i’m on os x tiger w/ python 2.3.5
that could be a very dumb question…is it just a comment that got changed?
The @ decorator was introduced in Python 2.4.
got it. have updated. thanks.
i have another question, though. i have no .so* files in my /usr/local/lib but do have files like libcxcore.dylib and libcxcore.la . neither of these file types works, when I refer to it (by full path) in Cvtypes.py. e.g., with dylib:
Traceback (most recent call last):
File “test_face_cvtypes.py”, line 3, in
from CVtypes import cv
File “/Users/username/Documents/python/CVtypes.py”, line 4170, in
(’dst’, POINTER(CvMat), 1), # CvMat* dst
File “/Users/username/Documents/python/CVtypes.py”, line 378, in cfunc
return CFUNCTYPE(result, *atypes)((name, dll), tuple(aflags))
AttributeError: dlsym(0×10c880, cvConvertPointsHomogenious): symbol not found
——-
obviously i don’t know what i’m doing. i would appreciate help getting off the ground, though. i’m on python 2.5.3 w/ the included ctypes installation. thanks for any advice.
this was already addressed in comments. sorry for the redundancy.
I also encountered the cvConvertPointsHomogenious missing problem described by Martin (#58). It appears to be a CVTypes spelling error. Making the genious suffix into geneous seems to work nicely. Now appears to be working on Max OS X 10.5 with system stock Python.
Thanks Sean,
That is now fixed in CVS.
Thanks Christian!
[...] Recent public urls tagged “ctypes” → By: Gabriel Quintero [...]
Net solution Gary!
Using linux (ubuntu) as 4ev pointed out, 3 lines must be modified. Just the deal about the CONSTANTS will be very nice to add in some next versions. Thanks!!
Linux (Ubuntu)
————–
first, install opencv in your path, usually /usr/local/lib:
_cxDLL = cdll.cxcore100
changes to
_cxDLL = cdll.LoadLibrary(”libcxcore.so.1″)
_cvDLL = cdll.cv100
changes to
_cvDLL = cdll.LoadLibrary(”libcv.so.1″)
_hgDLL = cdll.highgui100
changes to
_hgDLL = cdll.LoadLibrary(”libhighgui.so.1″)
A face detection example (Haar Classifier):
http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/
I’m not using CVtypes in any of my projects right now. It seems that many of your are. I suggest some of you take it over. I won’t be offended at all. In fact I will cheer you on and link to whatever new home you create.
mmm, any one else interested?, I’m still testing but until one is the most serious attempt I have seem to have opencv in python
Hi,
I am trying to bind with ctypes some of the stuff in the cvAux library. Specifically the CvBGStatModel, CvFGDStatModelParams structures and the cvCreateFGDStatModel function. I am having trouble however trying to get cvReleaseBGStateModel and cvUpdateBGStatModel to work. Because I don’t know how to complete the CvBGStatModel structure. I am missing the CvReleaseBGStatModel release; CvUpdateBGStatModel update; variables. I would appreciate any help as I am new to ctypes.
Here is the python code so far:
class CvBGStatModel(Structure):
_fields_ = [('type', c_int),
('background', POINTER(IplImage)),
('foreground', POINTER(IplImage)),
('layers', POINTER(POINTER(IplImage))),
('layer_count', c_int),
('foreground_regions', POINTER(CvSeq)),
('storage', POINTER(CvMemStorage))]
class CvFGDStatModelParams(Structure):
_fields_ = [('Lc', c_int),
('N1c', c_int),
('N2c', c_int),
('Lcc', c_int),
('N1cc', c_int),
('N2cc', c_int),
('is_obj_without_holes', c_int),
('perform_morphing', c_int),
('alpha1', c_float),
('alpha2', c_float),
('alpha3', c_float),
('delta', c_float),
('T', c_float),
('minArea', c_float)]
#cvReleaseBGStateModel = cfunc(’cvReleaseBGStatModel’, _cvauxDLL, None,
# (’bg_model’, ByRefArg(POINTER(CvBGStatModel)), 1),
#)
#
#cvUpdateBGStatModel = cfunc(’cvUpdateBGStatModel’, _cvauxDLL, c_int,
# (’current_frame’, POINTER(IplImage), 1),
# (’bg_model’, POINTER(CvBGStatModel), 1),
#)
#def cvUpdateBGStatModel(current_frame, bg_model):
# return bg_model.update( current_frame, bg_model )
cvCreateFGDStatModel = cfunc(’cvCreateFGDStatModel’, _cvauxDLL, POINTER(CvBGStatModel),
(’first_frame’, POINTER(IplImage), 1),
(’parameters’, POINTER(CvFGDStatModelParams), 1, None),
)
Also wondering if anyone knew how to display fonts with cvtypes. I can’t seem to figure out how to use cv.InitFont. Any examples?
Thanks!
[...] from intel which is FOSS and has a python-binding. Either using swig, or a ctypes-version: http://wwwx.cs.unc.edu/~gb/wp/blog/2…-using-ctypes/ With that, you can approach your problem. What is usually done is that a sequence of background [...]
[...] a face detector example that should work out of the box. Better yet, there are now some decent Python bindings for OpenCV that come pre-packaged with OpenCV for Ubuntu and Debian. You can install them with: [...]
I am still sort of new at python. So hopefully I am not wasting your time. Windows XP Python 2.5 IDLE downloaded from sourceforge today.
>>> from CVtypes import cv
Traceback (most recent call last):
File “”, line 1, in
from CVtypes import cv
File “C:\Python25\CVtypes.py”, line 42, in
_cxDLL = cdll.cxcore100
File “C:\Python25\lib\ctypes\__init__.py”, line 387, in __getattr__
dll = self._dlltype(name)
File “C:\Python25\lib\ctypes\__init__.py”, line 312, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 22] The specified module could not be found
============================================
Open CV is installed in my Python 25 folder (and I can get things like PIL and wx to work). I tried the following code from #14 ev above
for each _xxDLL = cdll.mmm, replace with if os.name == “posix”:
SyntaxError: invalid syntax “_xxDLL”
Any help greatly appreciated.
[...] haven’t used CVtypes recently so it hasn’t gotten any of my (very limited) attention. I see that Minh-Tri Pham has [...]
See my post about the status of CVtypes at http://wwwx.cs.unc.edu/~gb/wp/blog/2009/02/25/cvtypes-status/
[...] has python bindings, these often leak memory. So to directly use the C libraries, Gary Bishop wrote CVtypes – a ctypes based binding for OpenCV. It supports much of the OpenCV libraries by calling the C [...]
Hi there,
I got this working on mac os x Leopard… However, I had to explicitly include the paths to the dylib files as per below:
if os.name == ‘posix’:
#_cxDLL = cdll.LoadLibrary(’libcxcore.dylib’)
_cxDLL = cdll.LoadLibrary(’/opt/local/lib/libcxcore.1.dylib’)
_cvDLL = cdll.LoadLibrary(’/opt/local/lib/libcv.1.dylib’)
_hgDLL = cdll.LoadLibrary(’/opt/local/lib/libhighgui.dylib’)
This works but what do I need to do so that the full path names can be omitted?
Thanks in advance,
Ric
Thank it’s great…
I have a question.
How can I use cvFindStereoCorrespondence in Python?
Thank you very much
Hi,
I’m having trouble getting a successful return value for cv.HoughCircles. Here is my code, img is an passed from cv.QueryFrame(capture):
def find_circles(img):
gray = cv.CreateImage(cv.GetSize(img), 8, 1)
storage = cv.CreateMemStorage(0)
cv.CvtColor(img, gray, cv.BGR2GRAY)
cv.Smooth(gray, gray, cv.GAUSSIAN, 9, 9)
circles = cv.HoughCircles(gray, storage, cv.HOUGH_GRADIENT, 2, int(gray['height'])/4, 200, 100)
—
Traceback (most recent call last):
File “/home/liveuser/Desktop/bot/CVtypes/vision.py”, line 63, in
find_circles(src)
File “/home/liveuser/Desktop/bot/CVtypes/vision.py”, line 37, in find_circles
circles = cv.HoughCircles(gray, storage, cv.HOUGH_GRADIENT, 2, gray['height']/4, 200, 100)
TypeError: sequence index must be integer, not ’str’
—
I think it has something to do with when it is trying to store results to a list, but I’m not sure where to start in solving the problem.
what a fascinating module!
has anyone worked with the cvCreateStructuringElementEx function? its sixth argument, the “mask,” is supposed to be a “pointer to the structuring element data, a plane array, representing row-by-row scanning of the element matrix.”
But OpenCV (and cvtypes) expect a pointer to an int…how can that capture that a multidimensional list of integers? I tried passing byref this kind of array but no luck.
mask = (c_int * 3 * 3)((0, 0, 0), (0, 0, 0), (0, 0, 0))
Any help is greatly appreciated.
Please disregard that question. I worked it out.
Hi!
Can you explain to me what this step means:
“You’ll, of course, need to download OpenCV and get the dll’s on your path.”
Moreover, can you give a detailed instruction on how I am supposed to make this work. I installed OpenCV in windows, I have the path to the dll, I’ve downloaded your CVtypes.py but I can’t make it work.
Please be gentle. Python newbie here.
Thanks.
Please ignore my previous post.
I’ve worked it out but I am getting this error when I am trying to import the modules.
>>> from CVtypes import cv
Traceback (most recent call last):
File “”, line 1, in
from CVtypes import cv
File “E:\Charles\DownThemAll\CVtypes sf (23-53)\CVtypes.py”, line 4169, in
(’dst’, POINTER(CvMat), 1), # CvMat* dst
File “E:\Charles\DownThemAll\CVtypes sf (23-53)\CVtypes.py”, line 377, in cfunc
return CFUNCTYPE(result, *atypes)((name, dll), tuple(aflags))
AttributeError: function ‘cvConvertPointsHomogenious’ not found
Please ignore my recent posts AGAIN.
I’ve figured it out. I think ‘cvConvertPointsHomogenious’ should be ‘cvConvertPointsHomogeneous’. Thanks for this tool!
Leave a Comment