How to convert type of items in Numpy array

You may sometimes receive a Numpy array from external sources where the data type of the items are string or some other non-numeral format. Converting the data type of a Numpy array can be done using the astype method. This method on the array creates a copy of the array where every item has been converted to the destination type.

For example, assume smat is a Numpy array of strings that contain floats. To convert it to Numpy array of floats:

>>> smat
[[ '1.2', '3.4', '5.6']
 [ '7.8', '8.9', '9.0']]
>>> fmat = smat.astype(numpy.float)
>>> fmat
[[ 1.2 3.4 5.6 ]
 [ 7.8 8.9 9.0 ]]

Tried with: Python 2.7.6

Advertisements

How to convert between NumPy array and PIL Image

This example illustrates converting a 3-channel RGB PIL Image to 3D NumPy array and back:

import numpy
import PIL

# Convert PIL Image to NumPy array
img = PIL.Image.open("foo.jpg")
arr = numpy.array(img)

# Convert array to Image
img = PIL.Image.fromarray(arr)

Tried with: Python 2.7.3 and Ubuntu 12.04