Skip to content

Instantly share code, notes, and snippets.

Created December 3, 2020 22:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
A Python script for rotating images recursively through a directory. More information at
#!/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 \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
print("Please enter a valid angle [90, 180 or 270] to proceed.")
# Clean up Windows file paths
if sys.platform.startswith('win'):
target_raw = target_raw.replace('\\', '/')
if not target_raw.endswith('/'):
target = target_raw+"/"
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__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment