繁体   English   中英

在python中将字符串转换为numpy数组,反之亦然

[英]Converting string to numpy array and vice versa in python

我有一个numpy数组,这是打开cv读取的图像并将其保存为字符串。 所以我已经将np数组转换为字符串并存储相同的内容。 现在我想检索值(这是一个字符串)并转换为原始的numpy数组维度。 你能帮我解决一下这个问题吗?

我的代码如下:

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

请帮我解决一下

挑战在于不仅要保存数据缓冲区,还要保存形状和dtype。 np.fromstring读取数据缓冲区,但作为1d数组; 你必须得到其他地方的dtype和形状。

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

是json的选择吗?

这里答案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM