Home > Back-end >  How to append numpy arrays to txt file
How to append numpy arrays to txt file

Time:12-10

There are a list of image files I want to convert to numpy arrays and append them to a txt file, each array line after line. This is my code:

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

but file.write() requires a string and does not accept a numpy ndarray. How can I solve this?

CodePudding user response:

The write() function only allows strings as its input. Try using numpy.array2string.

CodePudding user response:

Numpy also allows you to save directly to .txt files with np.savetxt. I'm still not entirely sure what format you want your text file to be in but a solution might be something like:

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) 

Note that np.savetxt() has a lot of parameters that allow you to finetune the outputted txt file.

  • Related