c - 如何使 Python 对象表现得像 numpy 数组?

标签 c python-2.7 numpy ctypes

我正在开发一个 python 2.7 模块,它使用 ctypes 从动态库运行编译函数。它包含一个类,该类包装该库中的 C 结构,表示图像,并用于从 C 代码接收数据。

动态库执行数据的深度复制,特别适用于Python包装器。

模块中的进一步处理是使用 numpy 数组完成的,因此,我应该将从 C 代码检索的数据转换为 numpy.ndarray

速度和内存消耗目前不是问题。

目前,我已经在该类中实现了一个方法,该方法使用 numpy.frombuffer 函数创建并返回 numpy.ndarray

我想知道是否可以更好地实现。

这是Python类

import ctypes as ct
import numpy as np

class C_Mat(ct.Structure):
    _fields_ = [("rows", ct.c_int),
                ("cols", ct.c_int),
                ("data", ct.c_char_p),
                ("step", ct.ARRAY(ct.c_int64, 2)),
                ("data_type", ct.c_int)]

    _dtypes = { 0: np.uint8,
                1: np.int8,
                2: np.uint16,
                3: np.int16,
                4: np.int32,
                5: np.float32,
                6: np.float64 }


    def image(self):
        r = np.frombuffer(self.data,
                          dtype=self._dtypes[self.data_type], 
                          count=self.cols*self.step[1]*self.step[0])
        r.shape = (self.cols, self.rows)
        r.strides = (self.step[0], self.step[1])

        return r

最佳答案

关于c - 如何使 Python 对象表现得像 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40398768/

相关文章:

将 4 个整数的结构转换为 float

python - 如果我只有几个子列表元素,如何从列表中删除整个子列表? Python

python - numpy - 如何舍入数组的最后两列

android - 如何在 linux 内核模式下将 '\n' 传递到文件中

c - K&R书的练习1.9

python - 从 np.array 的行索引、列索引和最大值(值)填充矩阵的快速方法

python - 在 numpy 中构造此数组的有效方法?

python - 嵌套 numpy 运算

c++ - 从自定义构建的 Python 导入自定义模块失败

python - 为什么装饰类会破坏描述符协议(protocol),从而阻止 staticmethod 对象按预期运行?