【问题标题】:Converting string to numpy array and vice versa in python在python中将字符串转换为numpy数组,反之亦然
【发布时间】:2019-01-30 17:42:20
【问题描述】:

我有一个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

请帮我解决同样的问题

【问题讨论】:

  • 你能举个例子img_str吗?
  • img_str。查看所有省略号 (...)。这由threshhold 参数控制。这与我们从简单的print(img) 中得到的凝结相同。它还包括普通打印的所有嵌套 []。这不是一种很好的保存格式。
  • 你打算在哪里“保存”这个字符串?一份文件?由于它是一个二维数组,您可以使用savetxt 生成的csv 格式,并由loadtxt 加载。
  • 还有一个np.fromstring(img.tostring(),int) 往返,虽然这会丢失形状信息。还有非字符串np.save/np.load 选项。
  • 嗨@hpaulj..抱歉耽搁了。需要将图像 numpy 数组转换为字符串才能将其推送到云端。要从云端访问,我需要从云端获取它并再次将其重新转换为 numpy 数组

标签: python pandas numpy


【解决方案1】:

挑战在于不仅要保存数据缓冲区,还要保存形状和数据类型。 np.fromstring 读取数据缓冲区,但作为一维数组;您必须从其他地方获取 dtype 和 shape。

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

【讨论】:

    【解决方案2】:

    json 是一种选择吗?

    关注答案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))
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多