python - 将动态c lib.so集成到python

标签 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.array(image)

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

Traceback (most recent call last):
File "test1.py", line 21, in <module>
  lib.ContrastStretch(image_data, width ,height, 5,10)



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

如果我试过这样

 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(文档: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)

关于python - 将动态c lib.so集成到python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17852219/

相关文章:

python - 如何进一步优化计算所有交叉和?

python - PyQt5 QDialog在后续线程中

python - Django 1.4 中的时区以 UTC 格式从数据库返回

html - img 标签超出行高

windows - 如何在 Windows 上使用 ImageMagick 命令行?

Python Pandas 数据透视表如何处理 '\xc2\xa0' ?

python - 使用 Python Turtle 生成重叠三角形

java - 如何计算图像中的矩形

python - 对 numpy 数组进行子采样?

python - numpy.distutils 对架构的奇怪选择