[Numpy-discussion] converting a C bytes array to two dimensional numpy array

Omry Levy omrylevy at gmail.com
Tue Jul 16 03:30:22 EDT 2019


I have a question, regarding conversion of C (unsigned char *) buffer to a
two dimensional numpy array

this is what i am doing:
1) I get a C network buffer of unsigned char *  let's call it the source
the size of the source buffer is:
W * H * 2  bytes

2)  I am using PyByteArray_FromStringAndSize() to convert the source buffer
(a C unsigned char *) to python bytes array.
a = PyByteArray_FromStringAndSize(source buffer, W * H * 2)

3) i am using numpy.frombuffer   to convert the python bytes array to a 1
dimensional numpy array of size W *H *2 bytes
b = numpy.frombuffer(a, dtype = np.uint8)

4) i am creating a 2 dimensional numpy array from (3) when each element in
that array is made of 2 bytes from the python bytes array
c = b.view(np.uint16).reshape((H, W))

Is there a way to optimize this some how ?
Can you suggest a faster and better solution ?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20190716/9b2cead2/attachment.html>

More information about the NumPy-Discussion mailing list