从csv字符串加载numpy.ndarray

时间:2018-05-10 12:42:54

标签: python python-3.x csv numpy

我将图像转换为numpy数组并保存到csv文件

back_ground = Back_ground()
X = make_test_set('back_ground.csv',back_ground,3500)
Y = back_ground.make_answer()

with open('background.csv','w',newline='') as csvfile:
    fieldnames = ['image','answer']
    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'image': X, 'answer':Y})

make_test_set()make_answer()返回numpy.ndarray

但是当我想使用这个数据时,就像这样

with open('background.csv','r') as csvfile:
    reader = csv.DictReader(csvfile)
    for number,value in enumerate(reader):
        print(number)
        current_img = value['image']
        print(type(current_img))
        plt.imshow(current_img)
        plt.show()

currnet_img的类型是字符串,所以我不能使用任何numpy函数 我该如何转换为numpy.ndarray?还是有什么好方法来保存numpy.ndarray?

1 个答案:

答案 0 :(得分:0)

In [26]: import csv
In [27]: X = np.arange(12).reshape(3,4)
In [28]: Y = np.arange(12)
In [29]: with open('background.csv','w',newline='') as csvfile:
    ...:     fieldnames = ['image','answer']
    ...:     writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
    ...: 
    ...:     writer.writeheader()
    ...:     writer.writerow({'image': X, 'answer':Y})
    ...:     
In [30]: cat background.csv
image,answer
"[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]",[ 0  1  2  3  4  5  6  7  8  9 10 11]

DictWriter已写出2个值的str表示,并引用了多行1:

In [31]: str(X)
Out[31]: '[[ 0  1  2  3]\n [ 4  5  6  7]\n [ 8  9 10 11]]'

没有一种方便的方式将str(X)转换回X

保存这两个数组的好方法是使用savez

In [40]: np.savez('background.npz', image=X, answer=Y)
In [42]: data = np.load('background.npz')
In [43]: list(data.keys())
Out[43]: ['image', 'answer']
In [44]: data['image']
Out[44]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [45]: data['answer']
Out[45]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])