"""Resize / letterbox images to a fixed square (default 512×512).""" from __future__ import annotations from pathlib import Path from typing import Optional import cv2 import numpy as np def letterbox_square_bgr(bgr: np.ndarray, size: int) -> np.ndarray: """Fit image inside size×size with padding (preserves aspect).""" h, w = bgr.shape[:2] if h <= 0 or w <= 0: raise ValueError("empty image") scale = min(size / w, size / h) nw = max(1, int(round(w * scale))) nh = max(1, int(round(h * scale))) resized = cv2.resize(bgr, (nw, nh), interpolation=cv2.INTER_AREA) # Padding nền trắng để tránh viền đen ảnh hưởng Canny/edge. out = np.full((size, size, 3), 255, dtype=np.uint8) pad_y = (size - nh) // 2 pad_x = (size - nw) // 2 out[pad_y : pad_y + nh, pad_x : pad_x + nw] = resized return out def read_image_bgr(path: Path) -> Optional[np.ndarray]: img = cv2.imread(str(path), cv2.IMREAD_COLOR) return img def write_jpg(path: Path, bgr: np.ndarray, quality: int = 92) -> None: path.parent.mkdir(parents=True, exist_ok=True) cv2.imwrite(str(path), bgr, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) def write_image(path: Path, bgr: np.ndarray) -> None: """ Write image using file extension. Supports .jpg/.jpeg/.png/.webp (via OpenCV). """ path.parent.mkdir(parents=True, exist_ok=True) suf = path.suffix.lower() if suf in {".jpg", ".jpeg"}: write_jpg(path, bgr) return cv2.imwrite(str(path), bgr)