I have following String that I have put together:
v1fColor = '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'
I am treating it as a vector: Long story short its a forecolor of an image histogram:
I have the following lambda function to calculate cosine similarity of two images, So I tried to convert this is to numpy.array but I failed:
Here is my lambda function
import numpy as NP
import numpy.linalg as LA
cx = lambda a, b : round(NP.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)
So I tried the following to convert this string as a numpy array:
v1fColor = NP.array([float(v1fColor)], dtype=NP.uint8)
But I ended up getting following error:
v1fColor = NP.array([float(v1fColor)], dtype=NP.uint8)
ValueError: invalid literal for float(): 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,
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With