Issue
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?
Solution
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.
Answered By - Andre
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.