Created
December 3, 2020 22:28
-
-
Save AdamDimech/58102a6798864f1bc7db17044da55c38 to your computer and use it in GitHub Desktop.
A Python script for rotating images recursively through a directory. More information at https://code.adonline.id.au/selectively-rotating-images-in-python-recursively/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import fnmatch | |
import argparse | |
import sys | |
import cv2 | |
# Intro Text | |
print("\033[1;34;40m\n\nRotate images \033[0m") | |
print("\033[1;36;40mWritten by Adam M. Dimech. \nBased on https://code.adonline.id.au/selectively-rotating-images-in-python-recursively/ \n \n \033[0m") | |
def options(): | |
parser = argparse.ArgumentParser(description="Return a recursive list of files that match a criterion") | |
parser.add_argument("-f", "--folder", help="Target folder of images.", required=True) | |
parser.add_argument("-p", "--pattern", help="String to search for", required=True) | |
parser.add_argument("-d", "--degrees", help="Rotation angle code", required=True) | |
args = parser.parse_args() | |
return args | |
def list_files(): | |
# Get options | |
args = options() | |
# Identify the target directory | |
target_raw = args.folder | |
# Set acceptable extensions | |
ext = (('.png', '.PNG', '.jpg', '.JPG')) | |
# Translate rotation angle into OpenCV command | |
if args.degrees == "270": | |
angle = 0 | |
elif args.degrees == "180": | |
angle = 1 | |
elif args.degrees == "90": | |
angle = 2 | |
else: | |
print("Please enter a valid angle [90, 180 or 270] to proceed.") | |
exit() | |
# Clean up Windows file paths | |
if sys.platform.startswith('win'): | |
target_raw = target_raw.replace('\\', '/') | |
if not target_raw.endswith('/'): | |
target = target_raw+"/" | |
else: | |
target = os.path.join(target_raw, '') # Add trailing slash if missing | |
for root, dirnames, filenames in os.walk(target): | |
if not root.endswith('/'): | |
root = root+"/" | |
for filename in fnmatch.filter(filenames, args.pattern): | |
if filename.endswith(ext): | |
filepath = os.path.join(root, filename) | |
print("Rotating", args.degrees, "degrees:", filepath) | |
# Rotate images | |
image = cv2.imread(filepath) | |
rotated = cv2.rotate(image, angle) | |
cv2.imwrite(filepath, rotated) | |
if __name__ == '__main__': | |
list_files() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment