Skip to content

preprocessing

Image preprocessing module.

This module handles image resizing and cropping for encoding studies.


Result of a crop operation with region metadata.

Attributes:

  • path: Path to the cropped image file.
  • crop_region: The region extracted from the original image as
  • ```{“x”`: int, “y”: int, “width”: int, “height”: int}“.

__init__(path: Path, crop_region: dict[str, int]) → None

Handles image preprocessing operations.

__init__(output_dir: Path) → None

Initialize the image preprocessor.

Args:

  • output_dir: Directory where preprocessed images will be stored

crop_image_around_fragment(
input_path: Path,
fragment: dict[str, int],
target_longest_edge: int,
output_name: str | None = None,
adjust_aspect_ratio: bool = False
) → CropResult

Crop an image to a target size while keeping the analysis fragment.

The crop window is sized so that its longest edge equals target_longest_edge (preserving the original aspect ratio), then positioned to center the analysis fragment as closely as possible. The fragment is guaranteed to be fully contained in the crop window; the window is clamped to image boundaries.

When target_longest_edge is greater than or equal to the original image’s longest edge the original image is returned unchanged with a crop region covering the full image.

Args:

  • input_path: Path to the original image.
  • fragment: Analysis fragment coordinates as
  • ```{“x”`: int, “y”: int, “width”: int, “height”: int}“ in the original image coordinate space.
  • target_longest_edge: Target longest edge of the crop window in pixels.
  • output_name: Optional output filename.
  • adjust_aspect_ratio: When True, if the fragment is larger than the scaled crop dimensions the crop window is expanded (breaking aspect-ratio preservation) so that the fragment fits. When False (default), a
  • :class: ValueError is raised instead.

Returns:

  • :class: CropResult with the cropped image path and the crop region applied (in original image coordinates).

Raises:

  • ValueError: If the fragment cannot fit within the target crop dimensions and adjust_aspect_ratio is False.

resize_image(
input_path: Path,
target_size: tuple[int, int],
output_name: str | None = None,
keep_aspect_ratio: bool = True
) → Path

Resize an image to target dimensions.

Args:

  • input_path: Path to the input image
  • target_size: Target (width, height) in pixels
  • output_name: Optional output filename (with extension)
  • keep_aspect_ratio: If True, maintain aspect ratio and fit within target_size

Returns: Path to the resized image