Last active
November 5, 2019 09:35
-
-
Save pluscubed/7f883c23c9dadd99c27ea82d20a80d5a to your computer and use it in GitHub Desktop.
Rotate images based on EXIF
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
from PIL import Image, ImageOps | |
import sys | |
import glob | |
import os | |
import piexif | |
if len(sys.argv) != 3: | |
print("usage: rotate.py [input-dir] [output-dir]") | |
exit(1) | |
inputDir = os.path.normpath(sys.argv[1]) | |
outputDir = os.path.normpath(sys.argv[2]) | |
print(f"inputDir: {inputDir}\noutput: {outputDir}") | |
for filepath in glob.iglob(inputDir+"/**/*.jpg", recursive=True): | |
try: | |
outputPath = outputDir + filepath[len(inputDir):] | |
if os.path.isfile(outputPath): | |
print(f"already exists {outputPath}") | |
continue | |
print(f"saving {outputPath}") | |
image = Image.open(filepath) | |
exif_dict = piexif.load(image.info["exif"]) | |
if piexif.ImageIFD.Orientation in exif_dict["0th"]: | |
exif_dict["0th"].pop(piexif.ImageIFD.Orientation) | |
exif_bytes = piexif.dump(exif_dict) | |
image = ImageOps.exif_transpose(image) | |
os.makedirs(os.path.dirname(outputPath), exist_ok=True) | |
image.save(outputPath, exif=exif_bytes) | |
image.close() | |
except Exception as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment