积分动态clib.so公司到python

2024-10-04 11:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将用c编写的共享库集成到已经运行的python应用程序中。为此,我创建了一个简单的.so文件,并尝试访问在共享库中编写的函数。在

from ctypes import *
import cv2 as cv
import numpy as np
print cv.__version__

so= 'ContrastEnhancement.so'
lib = cdll.LoadLibrary(so)

image = cv.imread('python1.jpg')
image_data = np.array(image)

#calling shared lib function here
lib.ContrastStretch(image_data, width ,height, 5,10)
cv.imwrite("python_result.jpg", )

^{pr2}$

如果我试过这样的话

 lib.ContrastStretch(c_uint8(image_data), width ,height, 5,10)
 TypeError: only length-1 arrays can be converted to Python scalars

现在它似乎与共享库无关,而是“如何在python中使用图像数据(数组)”

谢谢 贾维德


Tags: 文件函数imageimport应用程序datasolib
1条回答
网友
1楼 · 发布于 2024-10-04 11:24:25

问题是ctypes不知道共享库中函数的签名。在调用函数之前,必须让ctypes知道它的签名。这对ctypes来说有点麻烦,因为它有自己的小型语言来实现这一点。在

我建议使用cffi。Cython也是一种选择,但是如果您只是使用Cython包装c库,那么通常会有很多烦人的开销,而且您必须基本上学习一种全新的语言(Cython)。是的,它在语法上类似于python,但是根据我的经验,理解和优化cython性能需要实际阅读生成的C。在

使用cffi(docs:http://cffi.readthedocs.org/en/release-0.7/),您的代码如下:

import cffi
ffi = cffi.FFI()

# paste the function signature from the library header file
ffi.cdef('int ContrastStretch(double* data, int w0 ,int h0, int wf, int hf)

# open the shared library
C = ffi.dlopen('ContrastEnhancement.so')

img = np.random.randn(10,10)

# get a pointer to the start of the image
img_pointer = ffi.cast('double*', img.ctypes.data)
# call a function defined in the library and declared here with a ffi.cdef call
C.ContrastStretch(img_pointer, img.shape[0], img.shape[1], 5, 10)

相关问题 更多 >