从csv字符串加载numpy.ndarray [英] load numpy.ndarray from csv string
问题描述
我将图像转换为numpy数组并保存到csv文件
I converted images to numpy array and saved to csv file
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
make_test_set()
and make_answer()
return numpy.ndarray
但是当我想使用这些数据时,就像这样
But when I want to use this data, like this
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()
类型是字符串,所以我不能使用任何numpy函数
如何转换为numpy.ndarray?还是有什么好的方法来保存numpy.ndarray? type of The 没有将 There isn't a convenient way of converting that 保存这2个数组的一种好方法是使用 A good way of saving these 2 arrays would be with 这篇关于从csv字符串加载numpy.ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!currnet_img
is string so I can't use any numpy functions
how can I convert to numpy.ndarray? or are there any good method to save numpy.ndarray? 推荐答案
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
表示形式,并用多行引号引起来:DictWriter
has written the str
representation of the 2 values, and quoted the multiline one:In [31]: str(X)
Out[31]: '[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]'
str(X)
转换回X
的简便方法.str(X)
back into X
.savez
: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])