Behold! A greatly-overengineered version of @Stepeh Rauch's answer that contains an interactive element and accounts for odd-pixel padding.
Usage
# Note: PySide2 can also be replaced by PyQt5, PyQt6, PySide6
# Also note! Any of the above are >100MB
pip install utilitys pyside2 pillow
$ python <file.py> --help
usage: <file>.py [-h] [--folder FOLDER] [--ext EXT]
optional arguments:
-h, --help show this help message and exit
--folder FOLDER Folder of images allowed for viewing. Must have at least one image (default: .)
--ext EXT Image extension to look for (default: png)
$ python <file>.py --folder "./path/to/folder/of/your/image(s).png" --ext "jpg"
file.py
contents
import argparse
from pathlib import Path
from typing import Tuple, Union, Any
import numpy as np
import pyqtgraph as pg
from PIL import Image
from utilitys import fns, widgets, RunOpts
def pad_to_size(
image: Image.Image,
size_wh: Union[int, Tuple[int, int]] = None,
fill_color: Any = 0,
**resize_kwargs,
) -> Image.Image:
"""
Keeps an image's aspect ratio by resizing until the largest side is constrained
by the specified output size. Then, the deficient dimension is padded until
the image is the specified size.
"""
if size_wh is None:
size_wh = max(image.size)
if isinstance(size_wh, int):
size_wh = (size_wh, size_wh)
im_size_wh = np.array(image.size)
ratios = im_size_wh / size_wh
# Resize until the largest side is constrained by the specified output size
im_size_wh = np.ceil(im_size_wh / ratios.max()).astype(int)
# Prefer 1-pixel difference in aspect ratio vs. odd padding
pad_amt = np.array(size_wh) - im_size_wh
use_ratio_idx = np.argmax(ratios)
unused_ratio_idx = 1 - use_ratio_idx
# Sanity check for floating point accuracy: At least one side must match
# user-requested dimension
if np.all(pad_amt != 0):
# Adjust dimension that is supposed to match
im_size_wh[use_ratio_idx] += pad_amt[use_ratio_idx]
# Prefer skewing aspect ratio by 1 pixel instead of odd padding
# If odd, 1 will be added. Otherwise, the dimension remains unchanged
im_size_wh[unused_ratio_idx] += pad_amt[unused_ratio_idx] % 2
image = image.resize(tuple(im_size_wh), **resize_kwargs)
new_im = Image.new("RGB", size_wh, fill_color)
width, height = image.size
new_im.paste(image, (int((size_wh[0] - width) / 2), int((size_wh[1] - height) / 2)))
return new_im
def main(folder=".", ext="png"):
"""
Parameters
----------
folder: str, Path
Folder of images allowed for viewing. Must have at least one image
ext: str, Path
Image extension to look for
"""
folder = Path(folder)
files = fns.naturalSorted(folder.glob(f"*.{ext}"))
err_msg = f"{folder} must have at least one image file with extension `{ext}`"
assert len(files), err_msg
pg.mkQApp()
viewer = widgets.ImageViewer()
def readim(file_index=0, try_pad=False, output_w=512, output_h=512):
if 0 > file_index > len(files):
return
image = Image.open(files[file_index])
if try_pad:
image = pad_to_size(image, (output_w, output_h), fill_color=(255, 255, 255))
viewer.setImage(np.array(image))
viewer.toolsEditor.registerFunc(readim, runOpts=RunOpts.ON_CHANGED)
wc = viewer.widgetContainer()
readim()
wc.show()
pg.exec()
if __name__ == "__main__":
# Print defaults in help signature
fmt = dict(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
cli = fns.makeCli(main, parserKwargs=fmt)
args = cli.parse_args()
main(**vars(args))