Python numpy: Convert string in to numpy array
You have to split the string by its commas first:
NP.array(v1fColor.split(","), dtype=NP.uint8)
You can do this without using python string methods -- try numpy.fromstring
:
>>> numpy.fromstring(v1fColor, dtype='uint8', sep=',')array([ 2, 4, 14, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 6, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 9, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 6, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 8, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 0, 0, 0, 3, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 2, 3], dtype=uint8)
You can do this:
lst = v1fColor.split(',') #create a list of strings, splitting on the commas.v1fColor = NP.array( lst, dtype=NP.uint8 ) #numpy converts the strings. Nifty!
or more concisely:
v1fColor = NP.array( v1fColor.split(','), dtype=NP.uint8 )
Note that it is a little more customary to do:
import numpy as np
compared to import numpy as NP
EDIT
Just today I learned about the function numpy.fromstring
which could also be used to solve this problem:
NP.fromstring( "1,2,3" , sep="," , dtype=NP.uint8 )