python - Numpy subclass attribute slicing -
myclass
numpy.ndarray
subclass, intended represent set of images change on time. each image there set of metadata, time, ambient temperature , camera temperature. i've stored these metadata in list of dictionaries, each dictionary corresponds layer in array (myclass.metadata[0]
dictionary corresponds image in myclass[0]
).
i've overloaded getattr()
make items in dictionary accessible key, myclass.etemp
yields e.g. [24.9, 25.0, 25.1]
.
when slice myclass-object, how achieve attribute-array gets sliced same way?
now if myobject[1].etemp
, [24.9, 25.0, 25.1]
, want [25.0]
.
this class:
class stack(numpy.ndarray): props= [ 'version', 'width', 'height', 'shotrange', 'calibrange', 'unit', 'irb_fname', 'fidx', 'distance', 'etemp', 'zoom', 'ctemp', 'date', 'recdate', 'rectime', ] def __new__(cls, input_array, mdata=none): obj = numpy.asarray(input_array).view(cls) if isinstance(mdata, collections.iterable): # when reading text file obj.mdata = mdata else: obj.mdata = [arr.mdata[0] arr in input_array] # when combining stack-type objects return obj def __array_finalize__(self, obj): if obj none: return self.mdata = getattr(obj, 'mdata', none) def __getattr__(self, name): print(numpy.shape(self)) if numpy.rank(self) < 3: # we're looking @ single slice pass if name == 'starttime': return self.mdata[0]['date'] elif name == 'time': return [(item['date'] - self.mdata[0]['date']).total_seconds() item in self.mdata] elif name in stack.props: return [item[name] item in self.mdata] else: raise attributeerror
what need implement behavior? or there other better way store metadata?
you need override __getitem__
method.
class foo(object): def __getitem__(self,items): print items f = foo() f[1,2,3] f[1:3] f[1,1:3,2:3]
this returns:
1 (1, 2, 3) slice(1, 3, none) (1, slice(1, 3, none), slice(2, 3, none))
within getitem, you'll need slice attributes appropriately handling above cases.
Comments
Post a Comment