Questions about creating Python dynamic variables.

Asked 1 years ago, Updated 1 years ago, 108 views

from PIL import Image

from os import listdir

from os.path import isfile, join

filepath = './FACE/'

files = [f for f in listdir(filepath) if isfile(join(filepath, f))]

for i in range(0, files.len()):

im[i] = Image.open(filepath + files[i]).convert('L')

In the same way as above, I want to call all the images in the filepath and stack them in an array called im[].

Can I create an array of PIL Image formats?

python python-3.x

2022-09-22 18:18

1 Answers

It says "arrangement" in the question...Python's builtin does not have an array like c.

Typically, the list is used to represent an array of c.

Of course, you can use the array in the array module to create an array of types similar to c. (There is a fixed type that can be stored. https://docs.python.org/ko/3.7/library/array.html)

However, we usually use list or generator...if list, all images must be loaded into memory. If the number of images is small, it is not burdensome, but if it is large, load large images into memory Out of memory situation. In fact, the meaning of putting it in the array is also intended to be sequenced, so it is better to load the necessary images into memory by doing Lazy loading.

files = [f'{filepath}{f}' for f in listdir(filepath) if isfile(join(filepath, f))]
L = list(map(Image.open, files)) #L is an image list. Ten images of one megabyte would take up at least 10 megabytes of memory.
# Or work as a generator as shown below. At this time, the open function is not executed until next is executed. It can save memory by becoming lazy loading.
L = map(Image.open, files)
next(L)


2022-09-22 18:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.