Skip to content

Instantly share code, notes, and snippets.

@Tymek
Last active January 27, 2021 23:04
Show Gist options
  • Save Tymek/aa7576764caa34e5955889662f68ed59 to your computer and use it in GitHub Desktop.
Save Tymek/aa7576764caa34e5955889662f68ed59 to your computer and use it in GitHub Desktop.
Sort images by aspect ratio with Python and exiftool
#!/usr/bin/env python3
import sys
import os
import glob
import subprocess
import multiprocessing as mp
import subprocess
# change this
inputDir = "./input"
outputDir = "./output"
def f(inputFile):
process = subprocess.Popen(["exiftool", "-S", "-t", "-q", "-FileName", "-ImageSize", inputFile], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
output = out.decode('utf-8').strip().split('\t')
name = output[0]
size = [ int(x) for x in output[1].split('x') ]
sizes = size.sort()
ratio = round(size[0] / size[1], 2)
print(name.rjust(50, ' ') + " → " + str(ratio))
ratioDir = outputDir + "/" + str(ratio)
if not os.path.exists(ratioDir):
os.makedirs(ratioDir)
os.system('cp ' + inputFile + " " + ratioDir + "/" + name)
if __name__ == '__main__':
print("\nNumber of processors:", str(mp.cpu_count()).rjust(2, " "))
files = glob.glob(inputDir + "/*")
print("Files to process:", str(len(files)).rjust(6, " "))
print ("Output directory: %s\n" % outputDir)
with mp.Pool(mp.cpu_count() + 1) as p:
p.map(f, files)

Sort images by aspect ratio

This script does not care if image is in portrait or landscape ratio. Useful for sorting before developing your pictures.
Did you use it? ⭐ it!

What this should do:

  • find all files in inputDir
  • run exiftool on all files to find sizes (you need to have this installed)
  • copy files to new directory, prefixed by aspect ratio value (ex: ./output/0.67/yourfile.jpg)

And it is using parallel processing, just because I can.

Example output:

Number of processors:  8
Files to process:    342
Output directory: ./output

                                   SCF8510_000.JPG  →  0.75
                                      DSCF7002.JPG  →  0.75
                                      100_0080.JPG  →  0.67
                                      100_7281.JPG  →  0.67
                                      100_7915.JPG  →  0.67
                                      DSCN0161.JPG  →  0.75
                                      100_8480.JPG  →  0.67
...

NO WARRANTY OF ANY KIND. Use at your own risk.

Copyleft 0BSD 2021, Tymek.Cz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment