python_interest
python_interest

Reputation: 874

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

Upvotes: 1

Views: 797

Answers (2)

xdze2
xdze2

Reputation: 4151

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))

Upvotes: 1

Ishara Dayarathna
Ishara Dayarathna

Reputation: 3601

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]])

Upvotes: 2

Related Questions