'How to convert string formed by numpy.array2string back to array?
I have a string of numpy array which is converted by using numpy.array2string
Now, I want back my numpy array.
Any suggestions for how I can achieve it?
My Code:
img = Image.open('test.png')
array = np.array(img)
print(array.shape)
array_string = np.array2string(array, precision=2, separator=',',suppress_small=True)
P.S My array is a 3D array not 1D and I am using , separators, not the default blank
Solution 1:[1]
Update: I just tried this and it worked for me:
import numpy as np
from PIL import Image
img = Image.open('2.jpg')
arr = np.array(img)
# get shape and type
array_shape = arr.shape
array_data_type = arr.dtype.name
# converting to string
array_string = arr.tostring()
# converting back to numpy array
new_arr = np.frombuffer(array_string, dtype=array_data_type).reshape(array_shape)
print(new_arr)
For converting numpy array to string, I used arr.tostring() instead of arr.array2string(). After that converting back to numpy array works with np.frombuffer().
Solution 2:[2]
This is kind of a hack, but may be the simplest solution.
import numpy as np
array = np.array([[[1,2,3,4]]]) # create a 3D array
array_string = np.array2string(array, precision=2, separator=',', suppress_small=True)
print(array_string) #=> [[[1,2,3,4]]]
# Getting the array back to numpy
new_array = eval('np.array(' + array_string + ')')
Since the string representation of the array matches the argument we pass to build such array, using eval successfully creates the same array.
Probably is best if you enclose this in a try except in case the string format isn't valid.
Solution 3:[3]
numpy.array2string() gives output string as : '[1, 2]' so you need to remove the braces to get to the elements just separated by some separator.
Here is a small example to extract the list elements from the string by removing the braces and then using np.fromstring(). As you have used ',' as the separator when creating the string, I am using the same to delimit the string for conversion.
import numpy as np
x = '[1, 2]'
x = x.replace('[','')
x = x.replace(']','')
a = np.fromstring(x, dtype=int, sep=",")
print(a)
#Output: [1 2]
Solution 4:[4]
import numpy as np
def fromStringArrayToFloatArray(stringArray):
array = [float(s) for s in stringArray[1:-1].split(' ')]
return np.array(array)
x = np.array([1.1, 2.2, 3.3, 4.4])
y = np.array2string(x)
z = fromStringArrayToFloatArray(y)
x == z
You can use a list comprehension to split your array into different strings and then, convert them to float (or whatever)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Alejandro Aristizábal |
| Solution 3 | Yash |
| Solution 4 | Art_Arnaud |
