stouputils.image module

image_resize(image: ~PIL.Image.Image | ~numpy.ndarray[~typing.Any, ~numpy.dtype[~numpy.uint8]], max_result_size: int, resampling: ~PIL.Image.Resampling = Resampling.LANCZOS, min_or_max: ~typing.Callable[[int, int], int] = <built-in function max>, return_type: type[~PIL.Image.Image | ~numpy.ndarray[~typing.Any, ~numpy.dtype[~numpy.uint8]]] = <class 'PIL.Image.Image'>, keep_aspect_ratio: bool = True) Any[source]

Resize an image while preserving its aspect ratio by default. Scales the image so that its largest dimension equals max_result_size.

Parameters:
  • image (Image.Image | np.ndarray) – The image to resize.

  • max_result_size (int) – Maximum size for the largest dimension.

  • resampling (Image.Resampling) – PIL resampling filter to use.

  • min_or_max (Callable) – Function to use to get the minimum or maximum of the two ratios.

  • return_type (type) – Type of the return value (Image.Image or np.ndarray).

  • keep_aspect_ratio (bool) – Whether to keep the aspect ratio.

Returns:

The resized image with preserved aspect ratio.

Return type:

Image.Image | np.ndarray[Any, np.dtype[np.uint8]]

Examples

>>> # Test with (height x width x channels) numpy array
>>> import numpy as np
>>> array: np.ndarray = np.random.randint(0, 255, (100, 50, 3), dtype=np.uint8)
>>> image_resize(array, 100).size
(50, 100)
>>> image_resize(array, 100, min_or_max=max).size
(50, 100)
>>> image_resize(array, 100, min_or_max=min).size
(100, 200)
>>> # Test with PIL Image
>>> from PIL import Image
>>> pil_image: Image.Image = Image.new('RGB', (200, 100))
>>> image_resize(pil_image, 50).size
(50, 25)
>>> # Test with different return types
>>> resized_array = image_resize(array, 50, return_type=np.ndarray)
>>> isinstance(resized_array, np.ndarray)
True
>>> resized_array.shape
(50, 25, 3)
>>> # Test with different resampling methods
>>> image_resize(pil_image, 50, resampling=Image.Resampling.NEAREST).size
(50, 25)