简体   繁体   中英

Converting string to numpy array and vice versa in python

I am having a numpy array which is the image read by open cv and saving it as a string. So I have converted the np array to string and stored the same. Now I wanted to retrieve the value(which is a string) and convert to original numpy array dimension. Could you all please help me in how to do that?

My code is as below:

img = cv2.imread('9d98.jpeg',0)
img.shape    # --> (149,115)
img_str=np.array2string(img,precision=2,separator=',') # to string length 197? which I dont know how
img_numpy=np.fromstring(img_str,dtype=np.uint8) # shape (197,) since this is returning only 1D array

Please help me in resolving the same

The challenge is to save not only the data buffer, but also the shape and dtype. np.fromstring reads the data buffer, but as a 1d array; you have to get the dtype and shape from else where.

In [184]: a=np.arange(12).reshape(3,4)

In [185]: np.fromstring(a.tostring(),int)
Out[185]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [186]: np.fromstring(a.tostring(),a.dtype).reshape(a.shape)
Out[186]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Is going to json an option?

Following the answer here :

import numpy as np
import json

img = np.ones((10, 20))
img_str = json.dumps(img.tolist())
img_numpy = numpy.array(json.loads(img_str))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM