Find the lowest height and lowest width among all images in a directory
How can I get the lowest height out of all heights and also the lowest width out of all widths given I have about 50k images?
I tried this command, but it only gives the width and height of an image:
identify -format '%w %h' 72028059_11.jpg
600 431
I also got this from IRC Linux channel, but, because I have 50k images, it takes forever to output any result:
find -type f -name \*.jpg -exec identify -format '%w %h %d/%f\n' {} \; | sort -n -k2
Getting the image with min height and width
I don't have any comparing statistics, but I have reasons to believe the script below offers a relatively good option, since:
- python's PIL does not load the image into memory when calling
.open
- The script itself does not store the list of all files, it simply looks per file if the next one has a smaller height or width.
The script
#!/usr/bin/env python3
from PIL import Image
import os
import sys
path = sys.argv[1]
# set an initial value which no image will meet
minw = 10000000
minh = 10000000
for image in os.listdir(path):
# get the image height & width
image_location = os.path.join(path, image)
im = Image.open(image_location)
data = im.size
# if the width is lower than the last image, we have a new "winner"
w = data[0]
if w < minw:
newminw = w, image_location
minw = w
# if the height is lower than the last image, we have a new "winner"
h = data[1]
if h < minh:
newminh = h, image_location
minh = h
# finally, print the values and corresponding files
print("minwidth", newminw)
print("minheight", newminh)
How to use
- Copy the script into an empty file, save it as
get_minsize.py
-
Run it with the directory of images as argument:
python3 /path/to/get_maxsize.py /path/to/imagefolder
Output like:
minwidth (520, '/home/jacob/Desktop/caravan/IMG_20171007_104917.jpg')
minheight (674, '/home/jacob/Desktop/caravan/butsen1.jpg')
NB
The script assumes the image folder is a "flat" directory with (only) images. If that is not the case, a few lines need to be added, just mention.