如何将numpy数组附加到txt文件

How to append numpy arrays to txt file

有一个图像文件列表,我想将它们转换为 numpy 数组并将它们追加到一个 txt 文件中,每个数组一行接一行。这是我的代码:

from PIL import Image
import numpy as np
import os

data = os.listdir("inputs")
print(len(data))

with open('np_arrays.txt', 'a+') as file:
    for dt in data:
        img = Image.open("inputs\" + dt)
        np_img = np.array(img)
        file.write(np_img)
        file.write('\n')

但是 file.write() 需要一个字符串并且不接受 numpy ndarray。我该如何解决?

write() 函数只允许字符串作为其输入。尝试使用 numpy.array2string.

Numpy 还允许您使用 np.savetxt 直接保存到 .txt 文件。 我仍然不完全确定您希望文本文件采用哪种格式,但解决方案可能类似于:

from PIL import Image
import numpy as np
import os

data = os.listdir("inputs")
print(len(data))

shape = ( len(data), .., .., ) # input the desired shape

np_imgs = np.empty(shape)

for i, dt in enumerate(data):
    img = Image.open("inputs\" + dt)
    np_imgs[i] = np.array(img) # a caveat here is that all images should be of the exact same shape, to fit nicely in a numpy array

np.savetxt('np_arrays.txt', np_imgs) 

请注意 np.savetxt() 有很多参数可以让您微调输出的 txt 文件。