python - numpy 子类的数组

标签 python arrays numpy subclassing multidimensional-array

我有一个问题。问题是:我想创建一个 numpy 数组的子类,然后创建一个该类型的对象数组。当我引用该数组中的一个项目时,我希望它仍然是该子类的一个实例。相反,它是 numpy 数组的一个实例。

这是一个失败的测试:

import numpy as np


class ImageWrapper(np.ndarray):

    def __new__(cls, image_data):
        assert image_data.ndim in (2, 3)
        return image_data.view(cls)

    @property
    def n_colours(self): 
        return 1 if self.ndim==2 else self.shape[2]


n_frames = 10
frames = [ImageWrapper(np.random.randint(255, size = (20, 15, 3)).astype('uint8')) for _ in xrange(n_frames)]
video = np.array(frames)
assert video[0].n_colours == 3

给我:AttributeError: 'numpy.ndarray' object has no attribute 'n_colours'

我怎样才能让它工作?

已经尝试过的事情:

  • 在构建视频时设置 subok=True - 这仅在从子类对象的单个实例而非列表构建数组时有效。
  • 设置 dtype=object 或 dtype=ImageWrapper 不起作用

我知道我可以将视频设为列表,但出于其他原因最好将其保留为 numpy 数组。

最佳答案

无论您要实现什么目标,都可能有比继承 ndarray 更好的方法。但考虑到这一点,您可以将数组设为 object 类型,尽管在创建它时必须小心。这有效:

>>> video = np.empty((len(frames),), dtype=object)
>>> video[:] = frames
>>> video[0].n_colours
3

但这不是:

>>> video = np.array(frames, dtype=object)
>>> video[0].n_colours
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'n_colours'

关于python - numpy 子类的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24899289/

相关文章:

javascript - JS : find lowest/highest number from array within a specific range

python - 使用索引列表的列表对 numpy 矩阵的行进行求和

python - 如何修复:- libmxnet.所以:无法打开共享对象文件:没有这样的文件或目录

python - 在 Pandas python 中使用 nrow 跳过第一行时出现意外结果

python - 如何将列表插入 Python 中的 f 字符串?

arrays - bash $FUNCNAME 数组没有被清除

C 指针和数组

python - 如何量化添加到图像中的噪声量

python - 在 SciPy 中将复杂函数的根存储在数组中

Python 多处理 : socket error timeout while remote connection to a Manager