1

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

A.Queue
  • 1,549
  • 6
  • 21
python_interest
  • 874
  • 1
  • 9
  • 27
  • Can you give an example `img_str` ? – jpp Aug 24 '18 at 09:14
  • Look at `img_str`. See all the ellipsis (...). That's controlled by the `threshhold` parameter. This is the same sort of condensation we get from a simple `print(img)`. It also includes all the nested [] of a normal print. It's not a good format for saving. – hpaulj Aug 24 '18 at 19:04
  • Where do you intend to 'save' this string? A file? Since it's a 2d array, you could use the `csv` format produced by `savetxt`, and loaded by `loadtxt`. – hpaulj Aug 24 '18 at 19:05
  • There's also a `np.fromstring(img.tostring(),int)` round trip, though that looses shape information. And the non string `np.save/np.load` option. – hpaulj Aug 24 '18 at 19:11
  • Hi @hpaulj.. sorry for the delay. The image numpy array needs to be converted to string to push it to cloud. To access from cloud, I need to get it from cloud and re convert it again to numpy array – python_interest Aug 27 '18 at 03:24

2 Answers2

2

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]])
Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
1

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))
xdze2
  • 3,986
  • 2
  • 12
  • 29