Skip to content

Instantly share code, notes, and snippets.

@J0s3f
Created October 22, 2025 20:44
Show Gist options
  • Select an option

  • Save J0s3f/b1a48d3bc3ad25abc2c492a6fab551b7 to your computer and use it in GitHub Desktop.

Select an option

Save J0s3f/b1a48d3bc3ad25abc2c492a6fab551b7 to your computer and use it in GitHub Desktop.
Sort images by aspect ratio
import os
import shutil
import pillow_heif
from PIL import Image
# HEIC-Unterstützung aktivieren
pillow_heif.register_heif_opener()
# Verzeichnisse
directory = 'D:\\fotos\\groß'
square_dir = os.path.join(directory, 'square')
nonsquare_dir = os.path.join(directory, 'nonsquare')
# Ausgabeordner erstellen
os.makedirs(square_dir, exist_ok=True)
os.makedirs(nonsquare_dir, exist_ok=True)
# Schwellwert für Seitenverhältnis
aspect_threshold = 1.3
# Zähler
count_square = 0
count_nonsquare = 0
# Alle Dateien im Eingabeverzeichnis durchgehen
for filename in sorted(os.listdir(directory)):
if not filename.lower().endswith((".jpg", ".jpeg", ".png", ".heic")):
continue
try:
path = os.path.join(directory, filename)
img = Image.open(path)
w, h = img.size
ratio = max(w, h) / min(w, h)
# Zielordner wählen
if ratio > aspect_threshold:
dest = nonsquare_dir
count_nonsquare += 1
else:
dest = square_dir
count_square += 1
# Datei kopieren (nicht verschieben)
shutil.copy2(path, os.path.join(dest, filename))
except Exception as e:
print(f'Fehler bei {filename}: {e}')
# Zusammenfassung ausgeben
print(f'Fertig!\n{count_square} quadratische Bilder → {square_dir}')
print(f'{count_nonsquare} nicht-quadratische Bilder → {nonsquare_dir}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment