Add unified_pipeline: merged signature-verification synthetic document generator (part 15)
65cc549 verified Download unified_pipeline/src/analysis/geometry_analyzer.py from InternsProgressUpdate/Asyira: direct link, hf CLI and curl.
- Browser
- Download file 19.5 kB
-
https://huggingface.co/InternsProgressUpdate/Asyira/resolve/main/unified_pipeline/src/analysis/geometry_analyzer.py
- Command line
-
hf download hf://InternsProgressUpdate/Asyira/unified_pipeline/src/analysis/geometry_analyzer.py
-
curl -L -o geometry_analyzer.py https://huggingface.co/InternsProgressUpdate/Asyira/resolve/main/unified_pipeline/src/analysis/geometry_analyzer.py
19.5 kB
| """Post-render signature detection and geometry/coverage metric computation. | |
| Rather than searching the entire page (which would pick up printed field | |
| labels like "By:" or "Print Name:"), detection is scoped to the known | |
| signature field location -- exactly as a production pipeline would use the | |
| document's layout annotation to know where to look. A tight pass is tried | |
| first; if no ink is found (e.g. the signature was intentionally misplaced | |
| far from its box) the search window progressively expands, bounded by the | |
| page, before giving up. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| import cv2 | |
| import numpy as np | |
| from src.utils.geometry_utils import ( | |
| Box, box_center, box_to_polygon, centroid_of, containment_pct, | |
| coverage_pct, distance_between, iou, margin_utilization, points_to_polygon, safe_area, | |
| ) | |
| from src.utils.logging_utils import get_logger | |
| logger = get_logger(__name__) | |
| MIN_INK_PIXELS = 12 | |
| class GeometryResult: | |
| """Full geometric + photometric characterization of the detected signature.""" | |
| found: bool | |
| signature_bbox_px: Box | |
| min_rotated_rect: dict | |
| signature_polygon_px: list[list[float]] | |
| convex_hull_px: list[list[float]] | |
| # One (or more, if the ink broke into disjoint blobs) real per-component | |
| # boundary contour(s) -- for VISUALIZATION only (see | |
| # src/visualization/before_after_preview.py), never used in scoring. | |
| # signature_polygon_px/convex_hull_px above are the CONVEX HULL of every | |
| # ink pixel (matches projectA's own computation, including its | |
| # approxPolyDP simplification), correct for coverage/IoU/containment | |
| # math but "bridges" gaps between separate ink blobs (e.g. between | |
| # letters, or a flourish far from the main strokes) with straight | |
| # lines -- confirmed, on direct user feedback, to still visibly fail | |
| # to "hug" a signature with a real gap even after matching projectA's | |
| # exact rendering (that's projectA's own known tradeoff, just not | |
| # visible on a compact signature). These contours hug each real ink | |
| # blob's own boundary instead, so a translucent fill of them only ever | |
| # tints actual ink, never the whitespace between separate strokes. | |
| display_contours: list[list[list[float]]] | |
| centroid_px: tuple[float, float] | |
| orientation_deg: float | |
| ink_pixels: int | |
| target_box: Box | |
| actual_box: Box | |
| search_box: Box | |
| box_coverage_pct: float | |
| containment_pct: float | |
| ink_fill_ratio: float | |
| polygon_overlap_proxy: float | |
| distance_from_box_center_px: float | |
| margin_utilization: float | |
| mean_dark_intensity: float | |
| gray_stddev: float | |
| signature_area_ratio: float | |
| whitespace_ratio: float | |
| def _expand_box(box: Box, canvas_size: tuple[int, int], factor: float, min_pad: float) -> Box: | |
| x1, y1, x2, y2 = box | |
| w, h = canvas_size | |
| bw, bh = (x2 - x1), (y2 - y1) | |
| pad_x = max(bw * (factor - 1.0) / 2.0, min_pad) | |
| pad_y = max(bh * (factor - 1.0) / 2.0, min_pad) | |
| return ( | |
| float(max(x1 - pad_x, 0)), float(max(y1 - pad_y, 0)), | |
| float(min(x2 + pad_x, w)), float(min(y2 + pad_y, h)), | |
| ) | |
| def _union_box(a: Box, b: Box) -> Box: | |
| return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3])) | |
| def _is_printed_rule_line(width: int, height: int, area: int) -> bool: | |
| """Heuristic filter for printed "sign here" guideline rules vs. handwritten ink. | |
| Printed rules are thin (<=3px tall), very wide relative to their height, | |
| and nearly solid (high fill ratio) -- unlike handwriting, which varies in | |
| stroke height and leaves gaps even in a single connected component. | |
| """ | |
| if height > 3: | |
| return False | |
| if width < 8 * max(height, 1): | |
| return False | |
| fill_ratio = area / max(width * height, 1) | |
| return fill_ratio > 0.6 | |
| def _strip_printed_rule_line_pixels(binary: np.ndarray) -> np.ndarray: | |
| """Removes long, unbroken horizontal-line pixels (the template's own | |
| printed "sign here" rule) from an ink mask BEFORE connected-component | |
| analysis groups pixels together. | |
| A pasted signature's ink very often sits directly on top of, and | |
| touches, that printed line -- when it does, plain 8-connectivity merges | |
| the line and the ink into ONE connected component, whose bounding box | |
| then spans the printed line's full width (often the whole box) instead | |
| of just where the ink actually is. `_is_printed_rule_line()` below | |
| (per-component, post-hoc) only catches a line that stayed its own | |
| separate component; it can't un-merge one that's already fused with | |
| real ink. A wide horizontal morphological opening isolates only pixels | |
| that are part of a long, uninterrupted straight run -- true of a | |
| printed rule, essentially never true of handwriting for more than a | |
| few pixels at a time (natural slant/curviness breaks a single-row run | |
| quickly) -- so subtracting it erases the line's own pixels while | |
| leaving the ink's pixels, even where they touched, intact. Deliberately | |
| a small ABSOLUTE width, not a fraction of the crop: once a signature | |
| crosses the middle of the line, the line survives as two SHORTER | |
| sub-segments on either side of the crossing, and a proportionally-sized | |
| kernel could exceed either sub-segment's length, letting both slip | |
| through undetected. | |
| The 1-row-tall opening kernel only checks each row in isolation, so a | |
| genuinely TALL solid block of ink (thick handwriting, or a filled test | |
| fixture) satisfies the same "long unbroken run" test on every one of | |
| its rows and would otherwise be erased in full, row by row -- that's | |
| not what a printed rule looks like (``_is_printed_rule_line()`` | |
| elsewhere in this module defines one as <=3px tall). So candidate line | |
| pixels are re-checked per connected-component afterward: only ones | |
| whose overall bounding height stays <=3px are actually subtracted. | |
| """ | |
| h, w = binary.shape[:2] | |
| kernel_w = 20 | |
| if kernel_w >= w: | |
| return binary | |
| line_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_w, 1)) | |
| line_pixels = cv2.morphologyEx(binary, cv2.MORPH_OPEN, line_kernel, iterations=1) | |
| if line_pixels.sum() == 0: | |
| return binary | |
| n_labels, labels, stats, _ = cv2.connectedComponentsWithStats(line_pixels, connectivity=8) | |
| thin_line_pixels = np.zeros_like(line_pixels) | |
| for label in range(1, n_labels): | |
| if stats[label, cv2.CC_STAT_HEIGHT] <= 3: | |
| thin_line_pixels[labels == label] = 255 | |
| return cv2.bitwise_and(binary, cv2.bitwise_not(thin_line_pixels)) | |
| def _mask_already_dark_in_baseline(binary: np.ndarray, gray_crop: np.ndarray, baseline_crop: np.ndarray) -> np.ndarray: | |
| """Removes pixels that were ALREADY dark in the clean, unsigned template | |
| (printed field labels like "Bank Manager:", box borders, etc.) from an | |
| ink mask -- these sit right next to, and sometimes touch, a short | |
| signature box's search region, and get picked up as "ink" by simple | |
| brightness thresholding otherwise. The clean template image is known in | |
| advance (the same way a real production pipeline knows its own form | |
| layouts, not the specific run's signature placement) so this isn't | |
| using ground truth the way a real verifier couldn't -- it's exactly | |
| what :meth:`_strip_printed_rule_line_pixels` already does for straight | |
| rule lines, generalized to any pre-existing printed content shape.""" | |
| if baseline_crop.shape != gray_crop.shape: | |
| return binary | |
| baseline_background = float(np.percentile(baseline_crop, 90)) | |
| baseline_threshold = baseline_background - max(18.0, baseline_background * 0.15) | |
| baseline_dark = baseline_crop.astype(np.float32) < baseline_threshold | |
| out = binary.copy() | |
| out[baseline_dark] = 0 | |
| return out | |
| def _ink_mask(gray_crop: np.ndarray, baseline_crop: "np.ndarray | None" = None) -> "np.ndarray | None": | |
| if gray_crop.size == 0: | |
| return None | |
| background = float(np.percentile(gray_crop, 90)) | |
| threshold = background - max(18.0, background * 0.15) | |
| binary = (gray_crop.astype(np.float32) < threshold).astype(np.uint8) * 255 | |
| if binary.sum() == 0: | |
| return binary | |
| binary = _strip_printed_rule_line_pixels(binary) | |
| if baseline_crop is not None: | |
| binary = _mask_already_dark_in_baseline(binary, gray_crop, baseline_crop) | |
| kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)) | |
| opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel) | |
| n_labels, labels, stats, _ = cv2.connectedComponentsWithStats(opened, connectivity=8) | |
| cleaned = np.zeros_like(opened) | |
| for label in range(1, n_labels): | |
| area = stats[label, cv2.CC_STAT_AREA] | |
| w = stats[label, cv2.CC_STAT_WIDTH] | |
| h = stats[label, cv2.CC_STAT_HEIGHT] | |
| if area < 2: | |
| continue | |
| if _is_printed_rule_line(w, h, area): | |
| continue | |
| cleaned[labels == label] = 255 | |
| return cleaned | |
| class GeometryAnalyzer: | |
| """Detects the rendered signature within its known field and computes all geometry metrics. | |
| Example: | |
| >>> analyzer = GeometryAnalyzer() | |
| >>> result = analyzer.analyze(final_image, target_box=(100, 100, 300, 160), | |
| ... canvas_size=(1024, 559)) | |
| """ | |
| def analyze( | |
| self, | |
| image_rgb: np.ndarray, | |
| target_box: Box, | |
| canvas_size: tuple[int, int], | |
| placement_hint_bbox: "Box | None" = None, | |
| baseline_image_rgb: "np.ndarray | None" = None, | |
| expect_blank: bool = False, | |
| ) -> GeometryResult: | |
| """Detect the rendered signature and compute every geometry/coverage metric. | |
| Args: | |
| image_rgb: The fully rendered (and augmented) document, ``(H, W, 3)`` uint8. | |
| target_box: The annotated ``(x1, y1, x2, y2)`` signature field. | |
| canvas_size: ``(width, height)`` of the document. | |
| placement_hint_bbox: Optional pre-augmentation placement bounding | |
| box, used to widen the search if a tight pass finds nothing | |
| (e.g. after a large intentional misplacement). | |
| baseline_image_rgb: Optional clean, unsigned template image | |
| (same canvas size, before any signature/cosmetic text was | |
| drawn) -- when given, pixels that were already dark in the | |
| template itself (printed field labels, box borders) are | |
| excluded from ink detection, so a signature box search | |
| region that happens to sit close to printed text doesn't | |
| pick that text up as "ink" (see | |
| :func:`_mask_already_dark_in_baseline`). Not used if the | |
| sample underwent a geometric document-level transform | |
| (rotation/tilt/perspective) that could misalign it against | |
| ``image_rgb`` -- caller's responsibility to omit it then. | |
| expect_blank: Set when the caller already knows (from ground | |
| truth, e.g. a 2a/5a case's target box) that NO signature was | |
| placed here. Skips the second, widened retry pass entirely | |
| -- that retry exists to chase a signature that was | |
| deliberately misplaced far from its own box, not to search | |
| a box we already know is empty. Without this, on a sample | |
| where ``baseline_image_rgb`` had to be omitted (a page-level | |
| geometric transform was applied, so a pixel diff would be | |
| misaligned), the widened pass had nothing to exclude | |
| already-printed content with, and could pick up a nearby | |
| printed caption/label below the blank box as if it were a | |
| wildly misplaced signature. | |
| Returns: | |
| A :class:`GeometryResult` with detection status and every metric. | |
| """ | |
| gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) | |
| baseline_gray = cv2.cvtColor(baseline_image_rgb, cv2.COLOR_RGB2GRAY) if baseline_image_rgb is not None else None | |
| search_box = _expand_box(target_box, canvas_size, factor=1.15, min_pad=6) | |
| mask, offset = self._try_detect(gray, search_box, baseline_gray) | |
| if not expect_blank and (mask is None or int((mask > 0).sum()) < MIN_INK_PIXELS): | |
| union = _union_box(target_box, placement_hint_bbox) if placement_hint_bbox else target_box | |
| search_box = _expand_box(union, canvas_size, factor=2.2, min_pad=50) | |
| mask, offset = self._try_detect(gray, search_box, baseline_gray) | |
| if mask is None or int((mask > 0).sum()) < MIN_INK_PIXELS: | |
| if not expect_blank: | |
| logger.warning("No signature ink detected near target box %s.", target_box) | |
| return self._empty_result(target_box, search_box, canvas_size) | |
| return self._build_result(mask, offset, gray, target_box, search_box, canvas_size) | |
| def _try_detect( | |
| gray: np.ndarray, box: Box, baseline_gray: "np.ndarray | None" = None, | |
| ) -> tuple["np.ndarray | None", tuple[int, int]]: | |
| x1, y1, x2, y2 = (int(round(v)) for v in box) | |
| crop = gray[y1:y2, x1:x2] | |
| baseline_crop = baseline_gray[y1:y2, x1:x2] if baseline_gray is not None else None | |
| mask = _ink_mask(crop, baseline_crop) | |
| return mask, (x1, y1) | |
| def _build_result( | |
| self, mask: np.ndarray, offset: tuple[int, int], full_gray: np.ndarray, | |
| target_box: Box, search_box: Box, canvas_size: tuple[int, int], | |
| ) -> GeometryResult: | |
| ox, oy = offset | |
| ys, xs = np.where(mask > 0) | |
| points = np.column_stack([xs + ox, ys + oy]).astype(np.float32) | |
| ink_pixels = int(len(points)) | |
| x1, y1 = float(points[:, 0].min()), float(points[:, 1].min()) | |
| x2, y2 = float(points[:, 0].max()) + 1.0, float(points[:, 1].max()) + 1.0 | |
| bbox: Box = (x1, y1, x2, y2) | |
| rect = cv2.minAreaRect(points) | |
| (rcx, rcy), (rw, rh), rangle = rect | |
| rotated_rect = { | |
| "center": [round(float(rcx), 2), round(float(rcy), 2)], | |
| "size": [round(float(rw), 2), round(float(rh), 2)], | |
| "angle_deg": round(float(rangle), 2), | |
| } | |
| # Convex hull of every detected ink pixel, simplified with | |
| # approxPolyDP (epsilon = 1% of hull perimeter) -- matches | |
| # projectA's own signature_polygon_px computation exactly | |
| # (geometry_metrics.py::compute_signature_placement_metrics()), | |
| # so this pipeline's polygon behaves the same way projectA's does. | |
| contour_points = points.astype(np.int32) | |
| hull = cv2.convexHull(contour_points) | |
| epsilon = 0.01 * cv2.arcLength(hull, True) | |
| approx = cv2.approxPolyDP(hull, epsilon, True) | |
| hull_xy = [[int(pt[0][0]), int(pt[0][1])] for pt in approx] | |
| # Real per-blob boundary contour(s) -- for the visual preview only | |
| # (see the display_contours field docstring on GeometryResult). | |
| # A small dilation first (on a COPY, never the scoring mask) merges | |
| # adjacent pen-stroke fragments of the same letter into one smooth | |
| # blob instead of a "polka dot" scatter of tiny separate islands -- | |
| # a few px is nowhere near enough to bridge a real gap between | |
| # separate letters or a flourish far from the main strokes, so | |
| # genuine whitespace still stays outside every contour. | |
| dilated = cv2.dilate(mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=1) | |
| raw_contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| display_contours = [ | |
| [[float(pt[0][0] + ox), float(pt[0][1] + oy)] for pt in c] | |
| for c in raw_contours if len(c) >= 3 | |
| ] | |
| mean_pt, eigvecs, eigvals = cv2.PCACompute2(points, mean=None) | |
| orientation_deg = float(np.degrees(np.arctan2(eigvecs[0][1], eigvecs[0][0]))) | |
| orientation_deg = ((orientation_deg + 90) % 180) - 90 | |
| centroid = (float(points[:, 0].mean()), float(points[:, 1].mean())) | |
| bbox_crop = full_gray[int(y1):int(y2), int(x1):int(x2)] | |
| mean_dark_intensity = float(bbox_crop[mask.astype(bool)].mean()) if bbox_crop.shape == mask.shape else float( | |
| full_gray[oy:oy + mask.shape[0], ox:ox + mask.shape[1]][mask.astype(bool)].mean() | |
| ) | |
| gray_stddev = float(bbox_crop.std()) if bbox_crop.size > 0 else 0.0 | |
| target_poly = box_to_polygon(target_box) | |
| signature_poly = points_to_polygon(hull_xy) | |
| bbox_area = max((x2 - x1) * (y2 - y1), 1.0) | |
| ink_fill_ratio = float(np.clip(ink_pixels / bbox_area, 0.0, 1.0)) | |
| canvas_area = max(canvas_size[0] * canvas_size[1], 1) | |
| signature_area_ratio = float(bbox_area / canvas_area) | |
| return GeometryResult( | |
| found=True, | |
| signature_bbox_px=bbox, | |
| min_rotated_rect=rotated_rect, | |
| signature_polygon_px=hull_xy, | |
| convex_hull_px=hull_xy, | |
| display_contours=display_contours, | |
| centroid_px=(round(centroid[0], 2), round(centroid[1], 2)), | |
| orientation_deg=round(orientation_deg, 2), | |
| ink_pixels=ink_pixels, | |
| target_box=target_box, | |
| actual_box=bbox, | |
| search_box=search_box, | |
| box_coverage_pct=round(coverage_pct(target_poly, signature_poly), 3), | |
| containment_pct=round(containment_pct(target_poly, signature_poly), 3), | |
| ink_fill_ratio=round(ink_fill_ratio, 4), | |
| polygon_overlap_proxy=round(iou(target_poly, signature_poly), 4), | |
| distance_from_box_center_px=round(distance_between(box_center(target_box), centroid), 2), | |
| margin_utilization=round(margin_utilization(target_box, signature_poly), 4), | |
| mean_dark_intensity=round(mean_dark_intensity, 2), | |
| gray_stddev=round(gray_stddev, 2), | |
| signature_area_ratio=round(signature_area_ratio, 5), | |
| whitespace_ratio=round(float(np.clip(1.0 - ink_fill_ratio, 0.0, 1.0)), 4), | |
| ) | |
| def _empty_result(target_box: Box, search_box: Box, canvas_size: tuple[int, int]) -> GeometryResult: | |
| return GeometryResult( | |
| found=False, | |
| signature_bbox_px=target_box, | |
| min_rotated_rect={"center": [0.0, 0.0], "size": [0.0, 0.0], "angle_deg": 0.0}, | |
| signature_polygon_px=[], | |
| convex_hull_px=[], | |
| display_contours=[], | |
| centroid_px=(float("nan"), float("nan")), | |
| orientation_deg=0.0, | |
| ink_pixels=0, | |
| target_box=target_box, | |
| actual_box=target_box, | |
| search_box=search_box, | |
| box_coverage_pct=0.0, | |
| containment_pct=0.0, | |
| ink_fill_ratio=0.0, | |
| polygon_overlap_proxy=0.0, | |
| distance_from_box_center_px=float("nan"), | |
| margin_utilization=0.0, | |
| mean_dark_intensity=255.0, | |
| gray_stddev=0.0, | |
| signature_area_ratio=0.0, | |
| whitespace_ratio=1.0, | |
| ) | |