I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started?
You can use the Python Imaging Library (aka PIL) to read the image headers and query the dimensions.
One way to approach it would be to write yourself a function that takes a filename and returns the dimensions (using PIL). Then use the os.path.walk
function to traverse all the files in the directory, applying this function. Collecting the results, you can build a dictionary of mappings filename -> dimensions
, then use a list comprehension (see itertools
) to filter out those that do not match the required size.
One common way is to use PIL, the python imaging library to get the dimensions:
from PIL import Image
import os.path
filename = os.path.join('path', 'to', 'image', 'file')
img = Image.open(filename)
print img.size
Then you need to loop over the files in your directory, check the dimensions against your required dimensions, and move those files that do not match.
If you don't need the rest of PIL and just want image dimensions of PNG, JPEG and GIF then this small function (BSD license) does the job nicely:
http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py