如何使Python对象的行为像一个numpy数组?(How to make Python object behave like a numpy array?)

编程入门 行业动态 更新时间:2024-10-28 04:30:04
如何使Python对象的行为像一个numpy数组?(How to make Python object behave like a numpy array?)

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

I'm developing a python 2.7 module, that runs compiled function from a dynamic library using ctypes. It contains a class that wraps a C structure from that library, representing an image, and is used to receive data from the C code.

Dynamic library performs deep copy of data, specially for python wrapper.

Further processing in the module is done using numpy arrays, therefore, I should convert data, retrieved from the C code, to numpy.ndarray.

Speed and memory consumption is not an issue for now.

For now, I've implemented a method in that class, that creates and returns numpy.ndarray using numpy.frombuffer function.

I'm wondering, if it can be implemented better.

Here is the python class

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

最满意答案

有数组接口说明https://docs.scipy.org/doc/numpy/reference/arrays.interface.html

There is the Array Interface description https://docs.scipy.org/doc/numpy/reference/arrays.interface.html

更多推荐

本文发布于:2023-08-08 01:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466787.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   numpy   Python   behave

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!