[Numpy-discussion] recarray fun

Christopher Barker Chris.Barker@noaa....
Wed Apr 30 12:52:55 CDT 2008

Hi folks,

Someone on the wxPython list posted a nifty recarray example that I 
don't quite understand. The idea is to have an array for an RGBA image:

rgbarec = numpy.dtype({'r':(numpy.uint8,0),

A = numpy.zeros(shape, dtype=(numpy.uint32, rgbarec) )

what I don't understand is having BOTH numpy.uint32 and rgbrec as the 
dtype. How does that work?

Actually, with a bit of testing, it's pretty cool -- if you index like:

A[i,j] ==> uint32

A['r'][i,j] ==> uint8

pretty cool really.

it seems that numpy is treating it as both a recarray and a regular 
uint32 array, which makes some sense, but I'm still confused by the 

 >>> A
        [4278190080, 4278190080, 4278190080, 4278190080, 4278190080]], 

 >>> A.dtype
dtype(('>u4', [('r', '|u1'), ('g', '|u1'), ('b', '|u1'), ('a', '|u1')]))

so what is the dtype?

Also, I see advantages and disadvantages to either way. If you do:

A = numpy.zeros(shape, dtype=(numpy.uint32, rgbarec) )

then you can do:

A[i,j]['r'] to get the red value of a pixel
A[i,j] = (red, green, blue, alpha) to set a pixel
A[:,:] = (red, green, blue, alpha) to make the whole image one color

With the "dual dtype" approach:
A = numpy.zeros(shape, dtype=(numpy.uint32, rgbarec) )

You need to set the pixels separately:
A['r'][i,j] = red
B['r'][i,j] = green
or construct uint32 values:

C = numpy.uint32(red)
C += numpy.uint32(green) << 8
C += numpy.uint32(blue) << 16

Which is really ugly! (and I may not even have it right!). Is there a 
better way?

One more idea -- is there a way to have two arrays, each with a 
different dtype, that point to the same data? maybe:

RGBImage = numpy.zeros(shape, dtype=rgbarec )

IntImage = RGBImage.view()
IntImage.dtype = numpy.uint32

That way you could work with it either way, whichever was easier in the 

So -- what are folks' thoughts about how best to deal with images as 
numpy arrays? (I'll put it in a Wiki page if I get some good comments)


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the Numpy-discussion mailing list