Reputation: 8904
I'm using a API that returns RGB data as strings(*) (for instance I get 'ABC'
for [65, 66, 67]
. Is there a way to have this directly converted to a numpy unint8 array without an explicit comprehension with ord()
? Since this is picture data, I could be processing several million bytes, so any shortcut can help.
Otherwise, any method faster than the comprehension is gladly accepted.
(*) API requires Python 2.7, for the time being
Upvotes: 3
Views: 10151
Reputation: 53029
You can use np.frombuffer
:
np.frombuffer(b'ABC', dtype=np.uint8)
# array([65, 66, 67], dtype=uint8)
Since you are on Python2 this will probably work directly on strings, on Python3 a string would have to be encoded first to yield a bytes object.
Upvotes: 5