Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

前端 未结 7 626
北恋
北恋 2020-12-08 09:52

I\'m having a little trouble here,

I\'m trying to convert a numpy.ndarray to string, I\'ve already done that like this:

randomArray.tostring()


        
相关标签:
7条回答
  • 2020-12-08 10:31

    This is a slightly improvised answer to ajsp answer using XML-RPC.

    On the server-side when you convert the data, convert the numpy data to a string using the '.tostring()' method. This encodes the numpy ndarray as bytes string. On the client-side when you receive the data decode it using '.fromstring()' method. I wrote two simple functions for this. Hope this is helpful.

    1. ndarray2str -- Converts numpy ndarray to bytes string.
    2. str2ndarray -- Converts binary str back to numpy ndarray.
        def ndarray2str(a):
            # Convert the numpy array to string 
            a = a.tostring()
    
            return a
    

    On the receiver side, the data is received as a 'xmlrpc.client.Binary' object. You need to access the data using '.data'.

        def str2ndarray(a):
            # Specify your data type, mine is numpy float64 type, so I am specifying it as np.float64
            a = np.fromstring(a.data, dtype=np.float64)
            a = np.reshape(a, new_shape)
    
            return a
    

    Note: Only problem with this approach is that XML-RPC is very slow while sending large numpy arrays. It took me around 4 secs to send and receive a (10, 500, 500, 3) size numpy array for me.

    I am using python 3.7.4.

    0 讨论(0)
提交回复
热议问题