from __future__ import annotations from dataclasses import dataclass from PIL import Image from .config import AgePreset from .image_utils import ( contour_length, dedupe_points, find_external_contours, find_relevant_contours, normalize_contour_start, pil_to_cv_gray, preprocess_binary, sample_contour, select_primary_contour, ) @dataclass class DotLayout: points: list[tuple[int, int]] source_size: tuple[int, int] closed: bool = True class DotLayoutGenerator: def generate(self, image: Image.Image, preset: AgePreset) -> DotLayout: gray = pil_to_cv_gray(image) binary = preprocess_binary(gray) contours = find_external_contours(binary) if not contours: contours = find_relevant_contours(binary) if not contours: raise ValueError("Nao foi possivel identificar contornos validos na imagem.") primary_contour = normalize_contour_start(select_primary_contour(contours)) total_target = max( preset.min_dots, min(preset.max_dots, int(contour_length(primary_contour) / 70)), ) points = dedupe_points( sample_contour(primary_contour, total_target, closed=True), preset.min_distance_px, ) if len(points) < preset.min_dots: points = dedupe_points( sample_contour(primary_contour, preset.min_dots + 6, closed=True), max(10, preset.min_distance_px - 8), ) if len(points) > preset.max_dots: step = len(points) / preset.max_dots points = [points[int(i * step)] for i in range(preset.max_dots)] return DotLayout(points=points, source_size=image.size, closed=True)