Home > other >  How to convert numpy array to string and vice versa
How to convert numpy array to string and vice versa

Time:08-11

The following code is trying to convert the image array to string, and then regenerate the image from string.

import numpy as np
import matplotlib.pyplot as plt

image = np.ones((28,28))
print("image: {}".format(image.shape))

string = "{}".format(image.tostring())
print("len: {}".format(len(string)))

string_to_image = np.fromstring(string)
print("string_to_image: {}".format(string_to_image.shape))

Here is the output:

image: (28, 28)
len: 22739

/tmp/ipykernel_2794/3542140279.py:7: DeprecationWarning: tostring() is deprecated. Use tobytes() instead.
  string = "{}".format(image.tostring())
/tmp/ipykernel_2794/3542140279.py:10: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
  string_to_image = np.fromstring(string)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_2794/3542140279.py in <cell line: 10>()
      8 print("len: {}".format(len(string)))
      9 
---> 10 string_to_image = np.fromstring(string)
     11 print("string_to_image: {}".format(string_to_image.shape))

ValueError: string size must be a multiple of element size

How to fix the error?

CodePudding user response:

Check Below code, need to use right datatype dtype=np.uint8

string_to_image = np.fromstring(string, dtype=np.uint8)

CodePudding user response:

Alright so the first problem is the DeprecationWarning. With Python 3.2 and onwards, .tostring() and .fromstring have been replaced with .tobytes() and .frombuffer(). They are functionally the same, so you don't lose anything from using them, however for .frombuffer() to work properly we need to make sure we pass a bytes-like object so I removed the "{}".format() part.

The next problem is the shape. When you convert a numpy array to a string (or bytes-like object) it loses it's shape, however we cans imply fix this but using the .reshape() method.

And that's it, the code with all the changes is below and it should work as intended:)

import numpy as np
import matplotlib.pyplot as plt

image = np.ones((28,28))
print("image: {}".format(image.shape))

string = image.tobytes()
print("len: {}".format(str(string)))

string_to_image = np.frombuffer(string, dtype=int).reshape((28,28))
print("string_to_image: {}".format(string_to_image.shape))
  • Related