2011-08-09 37 views
1

我使用OpenCV 2.3的Python接口。我有一个用C语言编写的库,期望OpenCV对象,例如IplImage。像这样:OpenCV Python接口和ctypes库之间的互操作性

void MyFunction(IplImage* image); 

我希望从我的Python代码中调用这个函数。我已经试过:

library.MyFunction(image) 

但它给我一个错误:

ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1 

我还试图用byref但它仍然不工作:

TypeError: byref() argument must be a ctypes instance, not 'cv.iplimage' 

如何我要这样做吗?

回答

2

cv.iplimage是由iplimage_t定义的CPython对象。它包装您需要的IplImage指针。有几种方法可以获得这个指针。我将使用CPython id返回对象基地址的事实。

import cv, cv2 
from ctypes import * 

你可以使用c_void_p而不是定义IplImage。我在下面定义它以证明指针是正确的。

class IplROI(Structure): 
    pass 

class IplTileInfo(Structure): 
    pass 

class IplImage(Structure): 
    pass 

IplImage._fields_ = [ 
    ('nSize', c_int), 
    ('ID', c_int), 
    ('nChannels', c_int),    
    ('alphaChannel', c_int), 
    ('depth', c_int), 
    ('colorModel', c_char * 4), 
    ('channelSeq', c_char * 4), 
    ('dataOrder', c_int), 
    ('origin', c_int), 
    ('align', c_int), 
    ('width', c_int), 
    ('height', c_int), 
    ('roi', POINTER(IplROI)), 
    ('maskROI', POINTER(IplImage)), 
    ('imageId', c_void_p), 
    ('tileInfo', POINTER(IplTileInfo)), 
    ('imageSize', c_int),   
    ('imageData', c_char_p), 
    ('widthStep', c_int), 
    ('BorderMode', c_int * 4), 
    ('BorderConst', c_int * 4), 
    ('imageDataOrigin', c_char_p)] 

的CPython的对象:

class iplimage_t(Structure): 
    _fields_ = [('ob_refcnt', c_ssize_t), 
       ('ob_type', py_object), 
       ('a', POINTER(IplImage)), 
       ('data', py_object), 
       ('offset', c_size_t)] 

负载的示例作为iplimage

data = cv2.imread('lena.jpg') # 512 x 512 
step = data.dtype.itemsize * 3 * data.shape[1] 
size = data.shape[1], data.shape[0] 
img = cv.CreateImageHeader(size, cv.IPL_DEPTH_8U, 3) 
cv.SetData(img, data, step) 

在CPython中的imgid是它的基地址。使用ctypes,您可以直接访问该对象的a字段,即您需要的IplImage *

>>> ipl = iplimage_t.from_address(id(img)) 
>>> a = ipl.a.contents 
>>> a.nChannels 
3 
>>> a.depth 
8 
>>> a.colorModel 
'RGB' 
>>> a.width 
512 
>>> a.height 
512 
>>> a.imageSize 
786432 
+0

在Ubuntu 14.04的cv2中,图像不会作为C风格的IplImage返回。它作为numpy.ndarray()返回。通过使用my_array.data_as(c_void_p)将ndarray()值传递给C函数相对比较容易。 –