Recursively find all images above a minimum width in a directory, with Python

In Software Engineering, Snippet

Objective: Finds all images above a minimum width, recursively, within a directory.

# References
# 1. http://mayankjohri.wordpress.com/2008/07/02/create-list-of-files-in-a-dir-tree/
# 2. http://forums.devshed.com/python-programming-11/recursive-file-search-for-given-extension-519562.html
# 3. http://code.hammerpig.com/search-files-directories-recursively-python.html

import sys
import os
import fnmatch
from PIL import Image

# Uses a generator
def locate_generator(root, pattern):
    for rootpath, subdirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(rootpath, filename).replace('\\','/')

if __name__ == "__main__":
    parent = sys.argv[1]
    pattern = sys.argv[2]
    minwidth = int(sys.argv[3])

    for image in locate_generator(parent, pattern):
        try:
            img = Image.open(image)
            (width, height) = img.size
            if width > minwidth:
                print image, img.size
        except:
            e = sys.exc_info()[0]
            print image, " | Error: ", e

Usage

python find-images-minwidth.py "D:/Photos" "*.jpg" 972


Alternative Code

This function can be substituted for the locator_generator function above, with some modifications (since the function below returns an array of filenames instead).

# Outputs an array -- NOT USED
def locate(root, pattern):
    matches = []   
    for rootpath, subdirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            matches.append(os.path.join(rootpath, filename).replace('\\','/'))
    return matches

Leave a Reply