Send a multidimensional numpy array over a socket

前端 未结 3 1689
萌比男神i
萌比男神i 2021-02-13 21:23

Good day,

I\'ve searched for this but haven\'t come up with any responses. I wish to send a multi dimensional numpy array over a socket. Hence, I decided to convert it t

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 21:36

    Indeed, .tostring only returns the raw data. This means you additionally need to send the shape and dtype of the array if these aren't known on the other side.

    Maybe it's easier to serialize the array using Pickle:

    import numpy as np
    from cPickle import dumps, loads
    
    x = np.array([[1, 2],[3, 4]], np.uint8)
    print loads(dumps(x))
    # [[1 2]
    #  [3 4]]
    

    Though for very small arrays the size overhead could be significant:

    print len(x.tostring()), len(dumps(x))
    # 4 171
    

    For more on using Pickle, see here.

提交回复
热议问题