[Numpy-discussion] Overriding numpy.ndarray.__getitem__?

Keith Hughitt keith.hughitt@gmail....
Wed Aug 17 14:25:33 CDT 2011


Hi all,

I have a subclass of ndarray which is built using using a stack of images.
Rather than store the image header information separately, I overrode
__getitem__ so that when the user indexes into the image cube a single image
a different object type (which includes the header information) is returned
:

class ImageCube(np.ndarray):
.
.
.
def __getitem__(self, key):
        """Overiding indexing operation"""
        if isinstance(key, int):
            data = np.ndarray.__getitem__(self, key)
            header = self._headers[key]
            return SingleImage(data, header)
        else:
            return np.ndarray.__getitem__(self, key)


Everything seems to work well, however, now when I try to combine that with
indexing into the other dimensions of a single image, errors relating to
numpy's array printing arise, e.g.:


>>> print imagecube[0,0:256,0:256]
.
.
.

/usr/lib/pymodules/python2.7/numpy/core/arrayprint.pyc in _formatArray(a,
format_function, rank, max_line_len, next_line_prefix, separator,
edge_items, summary_insert)
    371             if leading_items or i != trailing_items:
    372                 s += next_line_prefix
--> 373             s += _formatArray(a[-i], format_function, rank-1,
max_line_len,
    374                               " " + next_line_prefix, separator,
edge_items,
    375                               summary_insert)


I think the problem has to do with how I am overriding __getitem__: I check
to see if the input is a single integer, and if it is, I return the new
object instance. This should only occur when something like "imagecube[n]"
is called, however, array2str ends up calling imagecube[x], even if the
original thing you are trying to print is something like
imagecube[0,1:256,1:256].

Any ideas? I apologize if the explanation is not very clear; I'm still
trying to figure out exactly what is going on.

Thanks,
Keith
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110817/8b6d8bf6/attachment.html 


More information about the NumPy-Discussion mailing list