Skip to content

Instantly share code, notes, and snippets.

@martinohanlon
Created July 14, 2020 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinohanlon/6945e0c1a1bffc35840d8c3112c9dcb1 to your computer and use it in GitHub Desktop.
Save martinohanlon/6945e0c1a1bffc35840d8c3112c9dcb1 to your computer and use it in GitHub Desktop.
A utility for padding image files.
"""
A utility for padding image files.
"""
from PIL import Image, ImageOps, UnidentifiedImageError
import os.path
def find_files(path, file_names=[], extensions=[]):
def valid_file(file_path):
# if we arent checking file_names or extension it must be valid
if len(extensions) == 0 and len(file_names) == 0:
return True
if len(extensions) > 0:
ext = os.path.splitext(file_path)
if ext[-1] in extensions:
return True
if len(file_names) > 0:
if os.path.split(file_path)[1] in file_names:
return True
return False
files_found = []
if os.path.isdir(path):
for dir_name, dirs, files in os.walk(path):
for file_name in files:
file_path = os.path.join(dir_name, file_name)
if valid_file(file_path):
files_found.append(file_path)
elif os.path.isfile(path):
if valid_file(path):
files_found.append(path)
return files_found
def img_pad(path, min_width=0, min_height=0, color=None, overwrite=True):
original_image = Image.open(path)
# does it need padding?
if original_image.size[0] < min_width or original_image.size[1] < min_height:
if original_image.size[0] > min_width:
min_width = original_image.size[0]
if original_image.size[1] > min_height:
min_height = original_image.size[1]
padded_image = ImageOps.pad(original_image, (min_width, min_height), color=color)
if overwrite:
new_file_path = path
else:
new_file_path = os.path.splitext(path)[0] + "-padded" + os.path.splitext(path)[1]
padded_image.save(new_file_path)
return new_file_path
# SETUP
# The path of the files
PATH = r"C:\Users\Martin OHanlon\Documents\raspberrypilearning\fl-blocks-to-text"
# The types of image file to pad as a list e.g. [".png", ".jpg"]
IMAGE_FILES = [".png"]
# Overwrite the files, or create a new file named [filename]-padded.ext
OVERWRITE = True
# The color to pad with as a RBG tuple e.g. (255,255,255), None for transparent
COLOR = None
# Minimum width and height of the images
MIN_WIDTH = 648
MIN_HEIGHT = 0
print("Padding files at {}".format(PATH))
files_to_pad = find_files(PATH, extensions=IMAGE_FILES)
for file_to_pad in files_to_pad:
try:
padded_file_path = img_pad(file_to_pad, min_width=MIN_WIDTH, min_height=MIN_HEIGHT, color=COLOR, overwrite=OVERWRITE)
if padded_file_path is not None:
print(" - padded file {}".format(padded_file_path))
except UnidentifiedImageError as e:
print("Error - could not pad image - {}\n".format(e))
print("Finished")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment