[Numpy-discussion] first post, simple questions

Zachary Pincus zachary.pincus at yale.edu
Thu Aug 21 14:12:24 EDT 2008


> import numpy
> linsp = numpy.linspace
> red = linsp(0, 255, 50)
> green = linsp(125, 150, 50)
> blue = linsp(175, 255, 50)
>
> array's elements are float. How do I convert them into integer?
>
> I need to build a new array from red, green, blue. like this:
>
> [[ red[0], green[0], blue[0] ],
>  [ red[1], green[1], blue[1] ],
>  [ red[2], green[3], blue[3] ],
>  ....
>  ....
>  [ red[49], green[49], blue[49] ],
> ]
>
> how do I create such an array?

We can convert them to integer and build the array at the same time:

colors = numpy.empty((50, 3), dtype=numpy.uint8)
colors[:,0] = numpy.linspace(0, 255, 50)
colors[:,1] = numpy.linspace(125, 150, 50)
colors[:,2] = numpy.linspace(175, 255, 50)

Or we could use a fancy-dtype record array:

colors = numpy.empty(50, dtype=[('r', numpy.uint8), ('g',  
numpy.uint8), ('b', numpy.uint8)])
colors['r'] = numpy.linspace(0, 255, 50)
colors['g'] = numpy.linspace(125, 150, 50)
colors['b'] = numpy.linspace(175, 255, 50)

To see the array look like the old non-fancy type, use:
colors.view((numpy.uint8, 3))

Zach






More information about the NumPy-Discussion mailing list