[Numpy-discussion] Creating a RGB-image from BW
Johannes Bauer
dfnsonfsduifb at gmx.de
Tue Apr 28 02:36:57 EDT 2009
Hello group,
I've been redicted from usenet ("Convert numpy.ndarray into "normal"
array", <75dgm1F16hqntU1 at mid.dfncis.de>) here and hope this is the right
place.
Basically, what I have is a numpy-Array which I got from a FITS-file
(it's black/white). I want to display that using GTK. Therefore every
color needs to appear three times (to make it look gray R = G = B).
The basic framework looks like
[...]
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
pb_pixels = pb.get_pixels_array()
print(type(pb_pixels), pb_pixels.shape, pb_pixels.typecode())
print(type(fits_pixels), fits_pixels.shape, fits_pixels.dtype)
which gives
(<type 'array'>, (480, 640, 3), 'b')
(<type 'numpy.ndarray'>, (480, 640), dtype('uint8'))
so now I need to assign values. Naively I started out with
for x in range(width):
for y in range(height):
pb_pixels[y, x] = fits_pixels[y, x]
which was horribly slow (around 3 seconds). Thanks to the usenet help, I
now got somewhat better:
fits_colors = numpy.zeros((height, width, 3), dtype="uint8")
for y in range(height):
for x in range(width):
fits_colors[height - y - 1, x] = fits_pixels[y, x]
pb_pixels[:, :] = fits_colors
This also works, and is a lot faster (around 0.7 seconds). However,
there seems to be a better way to do it. I played around with
fits_colors = numpy.fromfunction(lambda y, x, z: fits_pixels[y, x],
(height, width, 3), dtype="uint8")
pb_pixels[:, :] = fits_colors
Which worked somewhat - but gives weird results: The picture is
rotatated 90° to the right and the lower left part is displayed
repeatedly after 256 pixels... (I can make a screenshot if that's
easier). The fromfunction Function is quite fast in my context (around
0.2 second).
How should I solve this problem the right way?
Kind regards,
Johannes
More information about the NumPy-Discussion
mailing list