如何使用 Python select 并在文件夹中加载特定图像集?

How to select and load specific set of images in a folder using Python?

我有一个包含数千个图像文件(全部为 .jpg)的文件夹。我只想 select 这些图像的特定子集并将它们加载到我的人脸识别应用程序中。我有以下用于此过程的代码片段:

from PIL import Image
import os, os.path

images = []
path = "/path/to/images"
wanted_images = ["What goes in here?"]
for i in os.listdir(path):
    ext = os.path.splitext(i)[1]
    if ext.lower() not in wanted_images:
        continue
    images.append(Image.open(os.path.join(path,i)))

有没有一种聪明的方法来管理“这里有什么?”代码部分?本质上,图像被标记为“1_1.jpg”、...、“1_20.jpg”、“2_1.jpg”、...、“2_20.jpg”、“[=21” =]",...,"3_20.jpg",...,"100_1.jpg",...,"100_20.jpg"。我只想 select 仅标记为“1_11.jpg”、“2_11.jpg”、“3_11.jpg”、...、“100_11.jpg”的图像。

这样的事情可能会奏效。 Glob 可以帮助您 select 基于模式的路径。内置的 pathlib 库很好地支持 glob 模式。

from PIL import Image
from pathlib import Path

images = []
path = "/path/to/images"
for p in Path(path).glob("**/*_11.jpg"):
    images.append(Image.open(str(p)))

要打开所有基本名称以“_11.jpg”结尾的图像,您可以这样做:

from PIL import Image
from glob import glob
from os import path

directory = '<your directory>'

images = [Image.open(jpg) for jpg in glob(path.join(directory, '*_11.jpg'))]

请注意,模式匹配区分大小写,因此它不会识别以 .JPG 等结尾的文件