I have some images in a folder
. I want to store all these images to a list. There's a lot of images so I want to close image after reading.
I tried to do it like this using pathlib
:
from pathlib import Path
from PIL import Image
import numpy as np
path = Path(<path-to-folder>)
list_of_images = []
for img_path in path.iterdir():
with Image.open(img_path) as img:
list_of_images.append(img)
But then I try to show or do whatever with this image and get this:
list_of_images[0].show()
Leads to an error:
AttributeError: 'NoneType' object has no attribute 'seek'
And trying to convert to numpy array like this:
np.array(list_of_images[0])
Returns this:
array(<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x512 at 0x20E01990250>,
dtype=object)
How can I do it properly?
The above with statement
will automatically close the file after the nested block of code means object in the list have some memory address but actually the data has gone from there so you can create a deep copy
using PIL.Image.copy
method.
from pathlib import Path
from PIL import Image
import numpy as np
path = Path(<path-to-folder>)
list_of_images = []
for img_path in path.iterdir():
with Image.open(img_path) as img:
print(img)
list_of_images.append(img.copy())
Or you can do this thing read all the image object and do you operation and then close those file properly.
from pathlib import Path
from PIL import Image
import numpy as np
path = Path(<path-to-folder>)
img_path = [img_path for img_path in path.iterdir()]
list_of_images = []
for img_path in path.iterdir():
list_of_images.append(Image.open(img_path))
# Do something with the images
# ...
list_of_images[0].show()
# Close the images
for image in list_of_images:
image.close()
Or if we call convert
function to convert this image object to RGB which they might already be it also helps us to solve your problem because PIL.Image.convert
function also return copy of that object even after with context end you have copy of that object
list_of_images.append(img.convert('RGB'))
enter code here