Created
January 2, 2021 22:57
-
-
Save mertsalik/a9aef30e9fc1f6c243fa90114f1ee0c2 to your computer and use it in GitHub Desktop.
Batch crop multiple images of the same size #batchcrop #imagecrop
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
# -*- coding: utf-8 -*- | |
__author__ = "mertsalik" | |
__copyright__ = "Copyright 2021" | |
__credits__ = ["mertsalik", ""] | |
__license__ = "Private" | |
__email__ = "" | |
import os | |
import pathlib | |
from argparse import ArgumentParser | |
import imghdr | |
from PIL import Image | |
parser = ArgumentParser("Batch Image Crop arguments") | |
parser.add_argument('--images', type=pathlib.Path, required=True) | |
parser.add_argument('--width', type=float) | |
parser.add_argument('--height', type=float) | |
def validate_folder(folder_path: str = None) -> pathlib.Path: | |
if not os.path.exists(os.path.dirname(folder_path)): | |
raise ValueError(f"{folder_path} is not a valid path.") | |
print(f"Directory: {folder_path}. OK") | |
return pathlib.Path(folder_path) | |
def get_centered_crop_box( | |
image_width: float, | |
image_height: float, | |
crop_width: float = None, | |
crop_height: float = None | |
) -> (float, float, float, float): | |
crop_width = crop_width or image_width | |
crop_height = crop_height or image_height | |
return ( | |
(image_width - crop_width) / 2, | |
(image_height - crop_height) / 2, | |
((image_width - crop_width) / 2) + crop_width, | |
((image_height - crop_height) / 2) + crop_height | |
) | |
def process_image_file(file_path: pathlib.Path, **kwargs): | |
im = Image.open(file_path) | |
im_width, im_height = im.size | |
crop_box = get_centered_crop_box( | |
image_width=im_width, | |
image_height=im_height, | |
crop_width=kwargs.get('width'), | |
crop_height=kwargs.get('height') | |
) | |
cropped_image = im.crop(box=crop_box) | |
out_file = file_path.with_stem(file_path.stem + "_cropped") | |
cropped_image.save(out_file) | |
def process_image_files(directory: pathlib.Path, **kwargs): | |
for pth in directory.iterdir(): | |
info = imghdr.what(pth) | |
if info in ['jpeg', 'jpg', 'png']: | |
try: | |
process_image_file(pth, **kwargs) | |
except Exception as exc: | |
print(exc) | |
break | |
if __name__ == '__main__': | |
args = parser.parse_args() | |
images_path = validate_folder(folder_path=args.images) | |
width = args.width | |
height = args.height | |
process_image_files(directory=images_path, width=width, height=height) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment