[Numpy-discussion] first recarray steps
Stéfan van der Walt
stefan at sun.ac.za
Tue May 20 11:31:33 EDT 2008
Hi Vincent
2008/5/20 Vincent Schut <schut at sarvision.nl>:
> Hi, I'm trying to get into recarrays. Unfortunately documentation is a
> bit on the short side...
>
> Lets say I have a rgb image of arbitrary size, as a normal ndarray
> (that's what my image reading lib gives me). Thus shape is
> (3,ysize,xsize), dtype = int8. How would I convert/view this as a
> recarray of shape (ysize, xsize) with the first dimension split up into
> 'r', 'g', 'b' fields? No need for 'x' and 'y' fields.
First, you need to flatten the array so you have one (r,g,b) element
per row. Say you have x with shape (3, 4, 4):
x = x.T.reshape((-1,3))
Then you can view it with your new dtype:
dt = np.dtype([('r',np.int8),('g',np.int8),('b',np.int8)])
x = x.view(dt)
Then you must reshape it back to your original pixel arrangement:
x = x.reshape((4,4)).T
Or you can do it all in one go:
x.T.reshape((-1,x.shape[0])).view(dt).reshape(x.shape[1:]).T
Maybe someone else comes up with an easier way.
Cheers
Stéfan
More information about the NumPy-Discussion
mailing list