将动态c lib.so集成到python中
我试图将用c编写的共享库集成到已经运行的python应用程序中。为此,我创建了一个简单的.so文件,并尝试访问在共享库中编写的函数将动态c lib.so集成到python中,python,image,numpy,Python,Image,Numpy,我试图将用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
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", )
现在看来,这与共享库无关,而与“如何在python中使用图像数据(数组)”无关 谢谢
javed问题在于ctypes不知道共享库中函数的签名。在调用函数之前,必须让ctypes知道它的签名。这对于ctypes来说有点痛苦,因为它有自己的小型语言来实现这一点 我建议使用cffi。Cython也是一种选择,但是如果您只是使用Cython包装c库,通常会有很多烦人的开销,您必须基本上学习一种全新的语言(Cython)。是的,它在语法上类似于python,但是理解和优化cython性能需要实际阅读我的经验中生成的C 使用cffi(文档:),您的代码如下:
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)
如果您想将简单的C代码集成到Python中,那么
ctype
函数需要什么样的数据。简单的意思是只交换简单的类型。我建议使用比C-type更高级的Python/C包装器Cython
(Cython.org)是个不错的选择。此外,它可以很好地与numpy配合使用。对比度拉伸的原型是:int-eContractStretch(unsigned char*pImgData,int-width,int-height,int-low,int-high)与答案无关@hivert是对的,ctype工作得很好,但是使用它会遇到很大的困难,所以请使用cython。。它将您的x.py
文件转换为x.so
,可以直接用作python中的模块导入,例如:import x
。谢谢hivert,我也将使用cython进行尝试。我不知道代码有什么问题?
lib.ContrastStretch(c_uint8(image_data), width ,height, 5,10)
TypeError: only length-1 arrays can be converted to Python scalars
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)