from __future__ import annotations from typing import List import cv2 import numpy as np from PIL import Image def pil_to_cv_gray(image: Image.Image) -> np.ndarray: rgb = image.convert("RGB") arr = np.array(rgb) return cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY) def preprocess_binary(gray: np.ndarray) -> np.ndarray: _, binary = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV) kernel = np.ones((3, 3), np.uint8) opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel) return cv2.dilate(opened, kernel, iterations=1) def find_relevant_contours(binary: np.ndarray) -> List[np.ndarray]: contours, _ = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) height, width = binary.shape[:2] min_area = max(32, int(height * width * 0.00015)) filtered = [cnt for cnt in contours if cv2.contourArea(cnt) >= min_area and len(cnt) >= 20] filtered.sort(key=cv2.contourArea, reverse=True) return filtered[:6] def find_external_contours(binary: np.ndarray) -> List[np.ndarray]: contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) height, width = binary.shape[:2] min_area = max(32, int(height * width * 0.00015)) filtered = [cnt for cnt in contours if cv2.contourArea(cnt) >= min_area and len(cnt) >= 20] filtered.sort(key=cv2.contourArea, reverse=True) return filtered def contour_length(contour: np.ndarray) -> float: return float(cv2.arcLength(contour, closed=True)) def select_primary_contour(contours: list[np.ndarray]) -> np.ndarray: if not contours: raise ValueError("No contours available.") return max(contours, key=lambda contour: (cv2.contourArea(contour), contour_length(contour))) def normalize_contour_start(contour: np.ndarray) -> np.ndarray: points = contour[:, 0, :] if len(points) <= 2: return contour scores = points[:, 0] + (points[:, 1] * 0.25) start_idx = int(np.argmin(scores)) rotated = np.concatenate([points[start_idx:], points[:start_idx]], axis=0) next_point = rotated[1] previous_neighbor = rotated[-1] next_score = (int(next_point[1]), int(-next_point[0])) previous_score = (int(previous_neighbor[1]), int(-previous_neighbor[0])) if previous_score < next_score: rotated = rotated[::-1] start_idx = int(np.argmin(rotated[:, 0] + (rotated[:, 1] * 0.25))) rotated = np.concatenate([rotated[start_idx:], rotated[:start_idx]], axis=0) return rotated.reshape(-1, 1, 2) def sample_contour(contour: np.ndarray, sample_count: int, closed: bool = True) -> list[tuple[int, int]]: points = contour[:, 0, :] path_points = points if closed and len(points) > 1: path_points = np.vstack([points, points[0]]) diffs = np.diff(path_points, axis=0) seg_lengths = np.sqrt((diffs**2).sum(axis=1)) cumulative = np.concatenate([[0.0], np.cumsum(seg_lengths)]) total_length = cumulative[-1] if cumulative.size else 0.0 if total_length == 0: return [(int(path_points[0][0]), int(path_points[0][1]))] targets = np.linspace(0, total_length, num=sample_count, endpoint=False) result = [] for target in targets: idx = np.searchsorted(cumulative, target, side="right") - 1 idx = max(0, min(idx, len(path_points) - 2)) local_start = cumulative[idx] local_end = cumulative[idx + 1] ratio = 0.0 if local_end == local_start else (target - local_start) / (local_end - local_start) point = path_points[idx] + ratio * (path_points[idx + 1] - path_points[idx]) result.append((int(point[0]), int(point[1]))) return result def dedupe_points(points: list[tuple[int, int]], min_distance: int) -> list[tuple[int, int]]: if not points: return [] filtered = [points[0]] for point in points[1:]: last = filtered[-1] if ((point[0] - last[0]) ** 2 + (point[1] - last[1]) ** 2) ** 0.5 >= min_distance: filtered.append(point) return filtered