Issue
I have a folder comprising thousands of image files (all .jpg). I want to select only a specific subset of these images and load them into my program for face recognition application. I have the following code snippet for this process:
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)))
Is there a smart way to manage "What goes in here?" section of the code? Essentially, the images are labeled "1_1.jpg",...,"1_20.jpg", "2_1.jpg",...,"2_20.jpg", "3_1.jpg",...,"3_20.jpg",...,"100_1.jpg",...,"100_20.jpg". I want to select only images labeled "1_11.jpg", "2_11.jpg", "3_11.jpg", ...,"100_11.jpg".
Solution
In order to open all images with a basename ending with '_11.jpg' you could do this:
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'))]
Note that the pattern matching is case sensitive so it won't identify files ending, for example, in .JPG
Answered By - Lancelot du Lac Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.