[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),
'g':(numpy.uint8,1),
'b':(numpy.uint8,2),
'a':(numpy.uint8,3)})
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
semantics.
also:
>>> A
array([[4278190080,
...
[4278190080, 4278190080, 4278190080, 4278190080, 4278190080]],
dtype=uint32)
but:
>>> 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
context.
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)
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
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
Chris.Barker@noaa.gov
More information about the Numpy-discussion
mailing list