向Cython函数传递1D numpy数组

2024-09-28 01:26:29 发布

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

我有以下Cython函数

def detect(width, height, np.ndarray[np.uint8_t, ndim=1] frame):
    cdef detection_payload* detection = scan_frame(width, height, frame)
    return DetectionPayload()._setup(detection)

这是scan_frame的签名

^{pr2}$

这就是我试图将数组传递到detect

// test.py
from tag36h11_detector import detect
import numpy as np

a = np.array([1,2,3], dtype=np.uint8)

detect(4, 5, a)

这是我得到的错误。。。在

Traceback (most recent call last): File "test.py", line 6, in detect(4, 5, a) File "tag36h11_detector.pyx", line 67, in tag36h11_detector.detect cdef detection_payload* detection = scan_frame(width, height, frame) TypeError: expected bytes, numpy.ndarray found


Tags: pytestscannpwidthdetectorframepayload
2条回答

虽然NumPy数组的内部数据是uint8_t类型,但数组本身不是指针,因此它与类型uint8_t*不匹配。根据数组的内部数据结构,您需要沿着&frame[0]的行创建一个指向NumPy数组的指针([0]表示数组的第0个元素,&创建指向它的指针)。另外,使用numpy.asarray或类似的方法确保数组是C-连续的。在

示例

cdef detection_payload* detection = scan_frame(width, height, &frame[0])

可以使用Capow提出的方法,但我主张在cython代码中用memoryviews替换numpy数组,这有以下优点:

  1. 该函数可以不使用numpy,也可以与其他支持内存视图的类一起使用
  2. 你可以确保,记忆是连续的
  3. 你的cython模块完全不依赖于numpy

这意味着:

def detect(width, height, unsigned int[::1] frame not None):
    cdef detection_payload* detection = scan_frame(width, height, &frame[0])
    ...

我们仍然使用&frame[0]来获取指针。在

相关问题 更多 >

    热门问题