from typing import Tuple from PIL import Image from loguru import logger from cv_analysis.utils.image_operations import compute_pasting_coordinates from cv_analysis.utils.rectangle import Rectangle from synthesis.segment.content_rectangle import ContentRectangle def shrink_rectangle(rectangle: Rectangle, factor: float) -> Rectangle: x1, y1, x2, y2 = compute_scaled_coordinates(rectangle, (1 - factor)) logger.trace(f"Shrinking {rectangle} by {factor} to ({x1}, {y1}, {x2}, {y2}).") assert x1 >= rectangle.x1 assert y1 >= rectangle.y1 assert x2 <= rectangle.x2 assert y2 <= rectangle.y2 shrunk_rectangle = Rectangle(x1, y1, x2, y2) if isinstance(rectangle, ContentRectangle): # TODO: Refactor shrunk_rectangle = ContentRectangle(*shrunk_rectangle.coords, rectangle.content) return shrunk_rectangle def compute_scaled_coordinates(rectangle: Rectangle, factor: float) -> Tuple[int, int, int, int]: # FIXME: Refactor: Using image to compute coordinates is not clean image = Image.new("RGBA", (rectangle.width, rectangle.height)) scaled = image.resize((int(rectangle.width * factor), int(rectangle.height * factor))) x1, y1 = compute_pasting_coordinates(scaled, image) x1 = rectangle.x1 + x1 y1 = rectangle.y1 + y1 x2, y2 = x1 + scaled.width, y1 + scaled.height return x1, y1, x2, y2