gpt4 book ai didi

python - 如何在文件中写入字符串和 numpy 数组?

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:25 26 4
gpt4 key购买 nike

我正在为从目录中读取的图像计算特征,我想将图像路径和相应的特征写入文件中,以空格分隔。以这种方式需要输出

/path/to/img1.jpg 1 0 0 1 3.5 0.2 0
/path/to/img2.jpg 0 0 0.5 2.1 0 0.7
...

以下是我的部分代码

features.open('file.txt', 'w')
for fname in fnmatch.filter(fileList, '*.jpg'):
image = '/path/to/image'
# All the operations are here
myarray = [......] # array of dimensions 512x512
myarray.reshape(1, 512*512) # Reshape to make it a row vector
features.write(image + ' '.join(str(myarray)))
features.write('\n')
features.close()

但是输出是这样的

/path/to/img1.jpg[[0 0 1.0 2 3]]
/path/to/img2.jpg[[1.2 0 1.0 2 0.3]]

最佳答案

你的问题出在下面的语句中:

>>> ' '.join(str(np.array([1,2,3])))
'[ 1 2 3 ]'

你先把数组转成字符串格式

>>> str(np.array([1,2,3]))
'[1 2 3]'

然后用空格将字符串的元素(单个字符)连接起来。


相反,您需要将 numpy 数组的各个元素转换为字符串列表,例如使用 map .

>>> map(str, np.array([1,2,3]))
['1', '2', '3']

只有这样,您才应该加入结果字符串列表的元素:

>>> ' '.join(map(str, np.array([1,2,3])))
'1 2 3'

下一个问题将来自于您拥有的 numpy 数组实际上是二维的:

>>> map(str, np.array([[1,2,3]]))
['[1 2 3]']

这很容易解决,因为您已经使用 reshape 将它变成了一行。所以,只需将 map 应用于第一行:

>>> ' '.join(map(str, np.array([[1,2,3]])[0]))
'1 2 3'

关于python - 如何在文件中写入字符串和 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36874776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com