"""Pipeline orchestrator. Calls stage functions in order, collects bundle contours and intermediate stage images for the editor. """ from dataclasses import dataclass, field from time import perf_counter from typing import Any import cv2 import numpy as np from analysis import stages from analysis.params import AnalysisParams @dataclass class Bundle: id: int area: int center: tuple[int, int] contour: list[list[int]] @dataclass class PipelineResult: bundles: list[Bundle] stages: dict[str, np.ndarray] timings_ms: dict[str, float] thresholds_used: dict[str, Any] = field(default_factory=dict) def _contour_to_list(contour: np.ndarray) -> list[list[int]]: return contour.reshape(-1, 2).astype(int).tolist() CANONICAL_MAX_SIDE = 1400 def run(img_bgr: np.ndarray, params: AnalysisParams) -> PipelineResult: timings: dict[str, float] = {} out_stages: dict[str, np.ndarray] = {} orig_h, orig_w = img_bgr.shape[:2] longest = max(orig_h, orig_w) if longest > CANONICAL_MAX_SIDE: scale = CANONICAL_MAX_SIDE / longest new_w = int(round(orig_w * scale)) new_h = int(round(orig_h * scale)) img_bgr = cv2.resize(img_bgr, (new_w, new_h), interpolation=cv2.INTER_AREA) else: scale = 1.0 t = perf_counter() mask, _ = stages.create_circular_mask_v2( img_bgr, hue_range=(params.hue_low, params.hue_high), min_hue_fraction=params.min_hue_fraction, shrink_factor=params.shrink_factor, ) timings["mask"] = (perf_counter() - t) * 1000 out_stages["mask"] = mask t = perf_counter() normalized = stages.normalize_brightness(img_bgr, mask) timings["clahe"] = (perf_counter() - t) * 1000 out_stages["normalized"] = normalized t = perf_counter() if params.use_bilateral: denoised = stages.denoise_jpeg_artifacts( normalized, d=params.bilateral_d, sigmaColor=params.sigma_color, sigmaSpace=params.sigma_space, ) else: denoised = normalized timings["denoise"] = (perf_counter() - t) * 1000 t = perf_counter() binary, _, _, thresholds_used = stages.threshold_fibers_multichannel( denoised, mask, v_mode=params.v_mode, s_mode=params.s_mode, v_threshold=params.v_threshold, s_threshold=params.s_threshold, v_otsu_offset=params.v_otsu_offset, s_otsu_offset=params.s_otsu_offset, use_hue_filter=params.use_hue_filter, hue_low=params.hue_filter_low, hue_high=params.hue_filter_high, max_area_fraction=params.max_area_fraction, bright_keep_threshold=params.bright_keep_threshold, ) timings["threshold"] = (perf_counter() - t) * 1000 out_stages["binary"] = binary t = perf_counter() cleaned = stages.morphological_cleanup_v2( binary, small_kernel=params.small_kernel, large_kernel=params.large_kernel, close_iters=params.close_iters, open_iters=params.open_iters, smooth_kernel=params.smooth_kernel, min_component_area=params.min_component_area, ) timings["morph"] = (perf_counter() - t) * 1000 out_stages["cleaned"] = cleaned t = perf_counter() bundles_raw, markers = stages.segment_bundles_v2( cleaned, denoised, min_area=params.min_area, h=params.h, min_seed_area=params.min_seed_area, ) if params.use_merge and len(bundles_raw) > 1: bundles_raw = stages.merge_fragments( bundles_raw, denoised, merge_area_threshold=params.merge_area_threshold, proximity_threshold=params.proximity_threshold, color_similarity_threshold=params.color_similarity_threshold, ) timings["watershed"] = (perf_counter() - t) * 1000 dist = cv2.distanceTransform(cleaned, cv2.DIST_L2, 5) dist_vis = cv2.normalize(dist, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) out_stages["distance"] = dist_vis out_stages["markers"] = stages.colorize_markers(markers) normalized_rgb = cv2.cvtColor(normalized, cv2.COLOR_BGR2RGB) final_rgb = stages.draw_bundles(normalized_rgb, bundles_raw) out_stages["final"] = cv2.cvtColor(final_rgb, cv2.COLOR_RGB2BGR) inv = 1.0 / scale if scale != 1.0 else 1.0 bundles: list[Bundle] = [] for i, b in enumerate(bundles_raw): contour_orig = (b["contour"].reshape(-1, 2).astype(np.float32) * inv).round().astype(int) cx = int(round(b["center"][0] * inv)) cy = int(round(b["center"][1] * inv)) area_orig = int(round(b["area"] * inv * inv)) bundles.append( Bundle( id=i + 1, area=area_orig, center=(cx, cy), contour=contour_orig.tolist(), ) ) timings["total"] = sum(timings.values()) return PipelineResult( bundles=bundles, stages=out_stages, timings_ms=timings, thresholds_used=thresholds_used, )