【问题标题】:How to make Python object behave like a numpy array?如何使 Python 对象表现得像一个 numpy 数组?
【发布时间】:2016-11-03 10:08:49
【问题描述】:

我正在开发一个 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-2.7 numpy ctypes


    【解决方案1】:
    猜你喜欢
    • 2010-09-09
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2010-10-20
    • 2022-01-26
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多