Skip to content

imagesize

imagesize

Module for ImageSize

Classes

ImageSize

Class to represent the size of images

Functions
__eq__
__eq__(other)

Checks if two ImageSizes are equal

Source code in niceml/utilities/imagesize.py
def __eq__(self, other: "ImageSize"):
    """Checks if two ImageSizes are equal"""
    return (
        other is not None
        and isinstance(other, ImageSize)
        and self.width == other.width
        and self.height == other.height
    )
__le__
__le__(other)

Compares ImageSizes with the same aspect ratio

Source code in niceml/utilities/imagesize.py
def __le__(self, other: "ImageSize") -> bool:
    """Compares ImageSizes with the same aspect ratio"""
    division_factor = self.get_division_factor(other)
    return division_factor <= IDENTITY_SCALE
__lt__
__lt__(other)

Compares ImageSizes with the same aspect ratio

Source code in niceml/utilities/imagesize.py
def __lt__(self, other: "ImageSize") -> bool:
    """Compares ImageSizes with the same aspect ratio"""
    division_factor = self.get_division_factor(other)
    return division_factor < IDENTITY_SCALE
__mul__
__mul__(scale)

Multiplies the ImageSize by a given scale factor

Source code in niceml/utilities/imagesize.py
def __mul__(self, scale: float) -> "ImageSize":
    """Multiplies the ImageSize by a given scale factor"""
    return ImageSize(round(self.width * scale), round(self.height * scale))
__str__
__str__()

string with width, height

Source code in niceml/utilities/imagesize.py
def __str__(self) -> str:
    """string with width, height"""
    return f"[{self.width},{self.height}]"
__truediv__
__truediv__(divider)

Divides the ImageSize by a given division factor

Source code in niceml/utilities/imagesize.py
def __truediv__(self, divider: float) -> "ImageSize":
    """Divides the ImageSize by a given division factor"""
    return ImageSize(round(self.width / divider), round(self.height / divider))
create_with_same_aspect_ratio
create_with_same_aspect_ratio(*, width=None, height=None)

Creates an ImageSize with the same aspect ratio given either width or height of the target ImageSize

Parameters:

  • width (Optional[int], default: None ) –

    width of the target ImageSize

  • height (Optional[int], default: None ) –

    height of the target ImageSize

Returns:

  • ImageSize

    new ImageSize, based on height or width, with the same aspect ratio as the

  • ImageSize

    original Image Size

Source code in niceml/utilities/imagesize.py
def create_with_same_aspect_ratio(  # QUEST: what should be done with both given?
    self, *, width: Optional[int] = None, height: Optional[int] = None
) -> "ImageSize":
    """
    Creates an ImageSize with the same aspect ratio given either width or height
    of the target ImageSize

    Args:
        width: width of the target ImageSize
        height: height of the target ImageSize

    Returns:
        new ImageSize, based on height or width, with the same aspect ratio as the
        original Image Size
    """
    if width is None and height is None:
        raise ValueError("Either width or height must be set")
    if width is not None and height is not None:
        cur_image_size = ImageSize(width, height)
        self.get_division_factor(cur_image_size)
    if width is not None:
        cur_image_size = ImageSize(width, round(width * self.height / self.width))
    else:
        cur_image_size = ImageSize(round(height * self.width / self.height), height)

    return cur_image_size
from_numpy_shape classmethod
from_numpy_shape(shape)

Creates an ImageSize from a numpy shape

Source code in niceml/utilities/imagesize.py
@classmethod
def from_numpy_shape(cls, shape: Tuple[int, int]) -> "ImageSize":
    """Creates an ImageSize from a numpy shape"""
    return cls(shape[1], shape[0])
from_pil_image classmethod
from_pil_image(image)

Creates an ImageSize from a PIL Image

Source code in niceml/utilities/imagesize.py
@classmethod
def from_pil_image(cls, image: Image.Image) -> "ImageSize":
    """Creates an ImageSize from a PIL Image"""
    return cls(image.width, image.height)
from_pil_size classmethod
from_pil_size(size)

Creates an ImageSize from a PIL size

Source code in niceml/utilities/imagesize.py
@classmethod
def from_pil_size(cls, size: Tuple[int, int]) -> "ImageSize":
    """Creates an ImageSize from a PIL size"""
    return cls(size[0], size[1])
get_division_factor
get_division_factor(other)

Calculates the scale factor of two ImageSizes and returns it

Source code in niceml/utilities/imagesize.py
def get_division_factor(self, other: "ImageSize") -> float:
    """Calculates the scale factor of two ImageSizes and returns it"""
    scale = self.width / other.width
    if not isclose(scale, self.height / other.height):
        raise ImageSizeDivisionError(
            f"The ImageSizes have different aspect ratios"
            f"width_ratio: {scale} height_ratio: "
            f"{self.height / other.height}"
        )
    return scale
np_array_has_same_size
np_array_has_same_size(np_array)

Checks if the np_array has the same size as the ImageSize

Source code in niceml/utilities/imagesize.py
def np_array_has_same_size(self, np_array: np.ndarray) -> bool:
    """Checks if the np_array has the same size as the ImageSize"""
    return self.width == np_array.shape[1] and self.height == np_array.shape[0]
to_numpy_shape
to_numpy_shape()

tuple with height, width

Source code in niceml/utilities/imagesize.py
def to_numpy_shape(self) -> Tuple[int, int]:
    """tuple with height, width"""
    return self.height, self.width
to_pil_size
to_pil_size()

tuple with width, height

Source code in niceml/utilities/imagesize.py
def to_pil_size(self) -> Tuple[int, int]:
    """tuple with width, height"""
    return self.width, self.height

ImageSizeDivisionError

Bases: Exception

Error for if two ImageSizes have different aspect ratios

Functions

create_image_size

create_image_size(argument)

Creates an ImageSize with: - a list of two ints [width, height] - a Tuple of two ints (width, height) - a str of form 'width,height, which will be parsed

Parameters:

  • argument (Union[str, List[int], Tuple[int, int], dict]) –

    List, Tuple or String containing width and height information

Returns:

  • ImageSize

    ImageSize with given width and height

Source code in niceml/utilities/imagesize.py
def create_image_size(
    argument: Union[str, List[int], Tuple[int, int], dict]
) -> ImageSize:
    """
    Creates an ImageSize with:
    - a list of two ints [width, height]
    - a Tuple of two ints (width, height)
    - a str of form 'width,height, which will be parsed

    Args:
        argument: List, Tuple or String containing width and height information

    Returns:
        ImageSize with given width and height
    """
    if isinstance(argument, str):
        try:
            width, height = argument.split(",")
        except ValueError as error:
            raise Exception(f"ImageSize couldn't be parsed: {argument}") from error
    elif isinstance(argument, dict):
        width = argument["width"]
        height = argument["height"]
    else:
        width, height = argument
    return ImageSize(int(width), int(height))