import cv2 import numpy as np from typing import Dict, Tuple def analyze_defect(contour: np.ndarray, image_shape: Tuple[int, int, int]) -> Dict: """ Analyze geometric properties of a defect contour. Args: contour: Contour of detected defect image_shape: Shape of the image (H, W, C) Returns: Dictionary containing geometric features """ if contour is None or len(contour) == 0: return { "area_pixels": 0.0, "length_pixels": 0.0, "width_pixels": 0.0, "area_ratio": 0.0, "angle": 0.0 } # Area area = float(cv2.contourArea(contour)) # Rotated bounding box (better than axis-aligned) rect = cv2.minAreaRect(contour) (cx, cy), (w, h), angle = rect length = float(max(w, h)) width = float(min(w, h)) # Image area height, width_img = image_shape[:2] image_area = height * width_img area_ratio = (area / image_area) if image_area > 0 else 0.0 return { "area_pixels": area, "length_pixels": length, "width_pixels": width, "area_ratio": area_ratio, "angle": float(angle) }