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

5
  • Can you give an example img_str ? Commented Aug 24, 2018 at 9: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. Commented Aug 24, 2018 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. Commented Aug 24, 2018 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. Commented Aug 24, 2018 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 Commented Aug 27, 2018 at 3:24

2 Answers 2

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]])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.