我试图将用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", )
如果我试过这样的话
lib.ContrastStretch(c_uint8(image_data), width ,height, 5,10)
TypeError: only length-1 arrays can be converted to Python scalars
现在它似乎与共享库无关,而是“如何在python中使用图像数据(数组)”
谢谢 贾维德
问题是ctypes不知道共享库中函数的签名。在调用函数之前,必须让ctypes知道它的签名。这对ctypes来说有点麻烦,因为它有自己的小型语言来实现这一点。在
我建议使用cffi。Cython也是一种选择,但是如果您只是使用Cython包装c库,那么通常会有很多烦人的开销,而且您必须基本上学习一种全新的语言(Cython)。是的,它在语法上类似于python,但是根据我的经验,理解和优化cython性能需要实际阅读生成的C。在
使用cffi(docs:http://cffi.readthedocs.org/en/release-0.7/),您的代码如下:
相关问题 更多 >
编程相关推荐