我有一个问题。问题是:我想创建一个 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/