[Numpy-discussion] first recarray steps
Stéfan van der Walt
Tue May 20 10:31:33 CDT 2008
2008/5/20 Vincent Schut <firstname.lastname@example.org>:
> 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:
Maybe someone else comes up with an easier way.
More information about the Numpy-discussion