stouputils.image.resize module#

image_resize(image: T, max_result_size: int, resampling: Image.Resampling | None = None, min_or_max: ~collections.abc.Callable[[int, int], int] = <built-in function max>, return_type: type[T] | str = 'same', 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 | NDArray) – The image to resize.

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

  • resampling (Image.Resampling | None) – PIL resampling filter to use (default: Image.Resampling.LANCZOS).

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

  • return_type (type | str) – Type of the return value (Image.Image, np.ndarray, or “same” to match input type).

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

Returns:

The resized image with preserved aspect ratio.

Return type:

Image.Image | NDArray[np.number]

Examples

>>> # Test with (height x width x channels) numpy array
>>> import numpy as np
>>> array = np.random.randint(0, 255, (100, 50, 3), dtype=np.uint8)
>>> image_resize(array, 100).shape
(100, 50, 3)
>>> image_resize(array, 100, min_or_max=max).shape
(100, 50, 3)
>>> image_resize(array, 100, min_or_max=min).shape
(200, 100, 3)
>>> # 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)