4

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

1
  • can you give a little more of a minimal reproducible example? Like what's the shape of the data array? Commented Dec 4, 2017 at 12:12

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what the doctor ordered... And yes, in Python2 it works directly on strings (I assume that in Python3, the API will give bytes and not strings). In addition, I figured out that I could use reshape() to get an array of RGB triplets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.