Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from os import path
- from PIL import Image
- from enum import Enum
- import shutil
- import time
- # Disable decompression bomb check
- Image.MAX_IMAGE_PIXELS = None
- class Orientation(Enum):
- UNDEFINED = 0
- HORIZONTAL = 1
- VERTICAL = 2
- SQUARE = 3
- class ImageAndOrientation(object):
- file = object
- orientation = Orientation.UNDEFINED
- # Get Directory
- dir = r"G:\SKEN"
- while not path.exists(dir) and not os.path.isdir(dir):
- dir = input("Invalid Path, try again: ")
- # Scan directory for files and images
- print()
- print('Scanning the directory for files...')
- images = []
- for file in os.scandir(dir):
- try:
- # Try to open the file as an image
- with Image.open(file.path) as img:
- # If successfully opened as an image, add to the list
- image = ImageAndOrientation()
- image.file = file
- images.append(image)
- except IOError:
- # If not an image, skip the file
- pass
- # Processing and sorting images
- print()
- print("{} images found".format(len(images)))
- start_time = time.time()
- processed_count = 0
- for i in range(len(images)):
- try:
- with Image.open(images[i].file.path) as img:
- width, height = img.size
- if width > height:
- images[i].orientation = Orientation.HORIZONTAL
- elif width < height:
- images[i].orientation = Orientation.VERTICAL
- elif width == height:
- images[i].orientation = Orientation.SQUARE
- except Exception as e:
- print(f"Error processing {images[i].file.path}: {e}")
- images[i].orientation = Orientation.UNDEFINED
- processed_count += 1
- elapsed_time = time.time() - start_time
- print(f"Processed: {processed_count} images ({elapsed_time:.2f}s)", end="\r")
- # Create directories for each orientation if they don't exist
- if not os.path.exists(os.path.join(dir, Orientation.HORIZONTAL.name)):
- os.makedirs(os.path.join(dir, Orientation.HORIZONTAL.name))
- if not os.path.exists(os.path.join(dir, Orientation.VERTICAL.name)):
- os.makedirs(os.path.join(dir, Orientation.VERTICAL.name))
- if not os.path.exists(os.path.join(dir, Orientation.SQUARE.name)):
- os.makedirs(os.path.join(dir, Orientation.SQUARE.name))
- # Move images to their respective orientation folders
- for image in images:
- if image.orientation != Orientation.UNDEFINED:
- shutil.move(image.file.path, os.path.join(
- dir, image.orientation.name, image.file.name))
- print()
- print("Finished! The images are moved to separate folders based on their orientation.")
- print("These folders can be found in: \"{}\"".format(dir))
- input()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement