PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

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

 May 06, 2022     image, python, selection     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing