Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIG Python bindings to native code not working with OpenCV 2.1

I have an OpenCV project mixing Python and C. After changing to OpenCV 2.1, my calls to C code are not working any more, probably because OpenCV is no more using SWIG bindings.

From Python, I was used to call a C function with the following prototype:

int fast_support_transform(CvMat * I, CvMat * N,...);

Now, I get the following error:

TypeError: in method 'fast_support_transform', argument 1 of type 'CvMat *'

The C code is from a library created by me that uses SWIG to produces the Python interface. I'm not sure, but I think OpenCV is using ctypes now and this code is unable to send a CvMat pointer to my native code.

Do you know about a fast fix to this problem? Any tips are welcome.

UPDATE: Visitors, note this question is outdated. Python support in OpenCV is very mature now. CvMat is being represented as a Numpy array by default now.

like image 525
TH. Avatar asked Jul 17 '10 15:07

TH.


1 Answers

For work I once wrapped Tesseract (OCR software) using Cython which is a very Python-esque language. You write a mostly-python program which gets compiled into a full-on binary python module. In your .pyx file you can import C/C++ files/libraries instantiate objects, call functions, etc.

http://www.cython.org/

You could define a small Cython project and do something like:

#make sure Cython knows about a CvMat
cdef extern from "opencv2/modules/core/include/opencv2/types_c.h":
    ctypedef struct CvMat

#import your fast_support_transform
cdef extern from "my_fast_support_transform_file.h":
    int fast_support_transform(CvMat * I, CvMat * N, ...)

#this bit is the glue code between Python and C
def my_fast_support_transform(CvMat * I, CvMat * N, ...)
    return fast_support_transform(CvMat * I, CvMat * N, ...)

You'll also need a distutils/Cython build file that looks something like this:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("wrapped_support_transform", ["wrapped_support_transform.pyx"])]
)

The Cython website has an excellent tutorial to making your first Cython project: http://docs.cython.org/src/userguide/tutorial.html

like image 157
Mike Sandford Avatar answered Oct 20 '22 17:10

Mike Sandford