While you could use tobytes()
, it isn't the ideal method as it doesn't store shape information of the numpy array.
In cases where you have to send it to another process where you have no information about the shape, you will have to send the shape information explicitly.
A more elegant solution would be saving it to a BytesIO buffer using np.save
and recovering using np.load
. In this, you don't need to specifically store shape information anywhere and can easily recover your numpy array from the byte value.
Example:
>>> import numpy as np
>>> from io import BytesIO
>>> x = np.arange(28*28).reshape(28, 28)
>>> x.shape
(28, 28)
# save in to BytesIo buffer
>>> np_bytes = BytesIO()
>>> np.save(np_bytes, x, allow_pickle=True)
# get bytes value
>>> np_bytes = np_bytes.getvalue()
>>> type(np_bytes)
<class 'bytes'>
# load from bytes into numpy array
>>> load_bytes = BytesIO(np_bytes)
>>> loaded_np = np.load(load_bytes, allow_pickle=True)
# shape is preserved
>>> loaded_np.shape
(28, 28)
# both arrays are equal without sending shape
>>> np.array_equal(x,loaded_np)
True