[SciPy-dev] New named fields in scipy core --- possible uses in color images
Travis E. Oliphant
oliphant.travis at ieee.org
Thu Dec 15 03:57:37 EST 2005
I know that many people are not aware of the new named fields that are
now an integral part of scipy_core. So, here is a simple example of
their use.
First of all, named fields can be constructed from any data type, not
just records. The only thing the recarray subclass does is to make
construction a bit cleaner, perhaps, and to allow attribute access to
fields.
Consider the following code (works with recent SVN):
image = zeros((256,256),dtype=(uint32,
[('r','u1'),('g','u1'),('b','u1'),('a','u1')]))
This creates an array of zeros (which for math operations can be
interpreted as an unsigned 32-bit integer) but which has named fields
'r', 'g', 'b', and 'a'.
These fields can be accessed (as unsigned 8-bit integers) using
image['r']
image['g']
image['b']
image['a']
or the whole image can be accessed at one time using the image array.
I'm not sure, aside from perhaps code readibility, if there is any
benefit from this approach over the standard representation as
image = zeros((256,256,4), dtype=uint8)
but, it's kind of interesting that such things are now possible.
Note, however, that one thing the records.py module provides over this
simple approach is an "array-scalar" that also can have fields.
In our example:
image['r'][10,20] would work and return a uint8 scalar, but
image[10,20]['r'] would not because image[10,20] is a uint32 scalar (no
fields).
image[10,20].getfield(*image.dtypedescr.fields['r']) would work though.
Have fun...
-Travis
More information about the SciPy-Dev
mailing list