"""Canny sketch + Laplacian fabric patch extraction (aligned with standardized image size).""" from __future__ import annotations from pathlib import Path from typing import Optional, Tuple import cv2 import numpy as np def full_image_mask(hw: Tuple[int, int]) -> np.ndarray: h, w = hw return np.full((h, w), 255, dtype=np.uint8) def sketch_canny_masked( bgr: np.ndarray, mask: np.ndarray, blur_ksize: int = 5, low_ratio: float = 0.66, high_ratio: float = 1.33, ) -> np.ndarray: gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY) if blur_ksize >= 3 and blur_ksize % 2 == 1: gray = cv2.GaussianBlur(gray, (blur_ksize, blur_ksize), 0) med = float(np.median(gray)) low = max(1.0, low_ratio * med) high = max(low + 1.0, high_ratio * med) edges = cv2.Canny(gray, int(low), int(high)) m = (mask > 0).astype(np.uint8) return edges * m def laplacian_energy_map(gray: np.ndarray) -> np.ndarray: lap = cv2.Laplacian(gray, cv2.CV_64F, ksize=3) return lap * lap def best_texture_patch( bgr: np.ndarray, mask: np.ndarray, patch_size: int, stride: int = 8, ) -> np.ndarray: gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY) energy = laplacian_energy_map(gray) m = (mask > 0).astype(np.uint8) h, w = gray.shape[:2] ps = patch_size if h < ps or w < ps: return cv2.resize(bgr, (ps, ps), interpolation=cv2.INTER_AREA) best_score = -1.0 best_y, best_x = 0, 0 for y in range(0, h - ps + 1, stride): for x in range(0, w - ps + 1, stride): mm = m[y : y + ps, x : x + ps] if mm.sum() < (ps * ps * 0.5 * 255): continue patch_e = energy[y : y + ps, x : x + ps] score = float(patch_e.mean()) if score > best_score: best_score = score best_y, best_x = y, x if best_score < 0: y0 = max(0, (h - ps) // 2) x0 = max(0, (w - ps) // 2) patch = bgr[y0 : y0 + ps, x0 : x0 + ps] else: patch = bgr[best_y : best_y + ps, best_x : best_x + ps] if patch.shape[0] != ps or patch.shape[1] != ps: patch = cv2.resize(patch, (ps, ps), interpolation=cv2.INTER_AREA) return patch def process_one_sample( image_path: Path, out_sketch: Path, out_fabric: Path, stem: str, fabric_patch: int, ) -> Tuple[str, Optional[str]]: bgr = cv2.imread(str(image_path), cv2.IMREAD_COLOR) if bgr is None: return stem, f"failed read: {image_path}" h, w = bgr.shape[:2] mask = full_image_mask((h, w)) sketch = sketch_canny_masked(bgr, mask) fabric = best_texture_patch(bgr, mask, patch_size=fabric_patch) out_sketch.mkdir(parents=True, exist_ok=True) out_fabric.mkdir(parents=True, exist_ok=True) cv2.imwrite(str(out_sketch / f"{stem}.png"), sketch) cv2.imwrite(str(out_fabric / f"{stem}.png"), fabric) return stem, None