Created
May 30, 2022 05:48
-
-
Save pauljacobson/2724cf0b43e1bd79eeddda6e1790830d to your computer and use it in GitHub Desktop.
Script to take in TIFF images and reformat them as JPEG images using Pillow
This file contains hidden or 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 python3 | |
from pathlib import Path | |
from PIL import Image | |
from rich.console import Console | |
from rich.traceback import install | |
# Add support for Rich traceback formatting | |
install(show_locals=True) | |
# Add support for Rich formatted output in terminal | |
console = Console() | |
SOURCE_PATH = Path.cwd() / "images" | |
OUTPUT_PATH = "reformatted_images" | |
SOURCE_IMAGES = [] | |
def list_images(): | |
"""List the files in the images directory""" | |
for filename in SOURCE_PATH.iterdir(): | |
if ".DS_Store" in str(filename): | |
continue | |
# Add the file name to the list of images | |
SOURCE_IMAGES.append(filename) | |
console.print(len(SOURCE_IMAGES)) | |
def check_output_path(): | |
"""Check if the output_path is a directory""" | |
if not OUTPUT_PATH.is_dir(): | |
# If not, create the directory | |
OUTPUT_PATH.mkdir() | |
def main(): | |
list_images() | |
check_output_path() | |
"""Convert images from TIFF into JPEG""" | |
# Loop over images in the images directory with Path | |
for image in SOURCE_IMAGES: | |
# Extract just the file name from the path | |
# Variable for the reformatted file format | |
# Using original file name base and adding .jpg | |
reformatted_im = str(image.stem) + ".jpeg" | |
out_path = OUTPUT_PATH + "/" + reformatted_im | |
# Check that file name is not the same as the reformatted file name | |
if image != reformatted_im: | |
with Image.open(image).convert("RGB") as im: | |
# rotate image by -90 degrees and resize images | |
im = im.resize((128, 128)).rotate(90) | |
# save edited reformatted_im image to the output_path | |
im.save(out_path, "JPEG") | |
# console.print(reformatted_im) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment