"""Операция extract: изображение → keypoints + дескрипторы SIFT. Пайплайн (docs/04 §4.2): EXIF-ориентация → ресайз ≤ max_image_size → grayscale + CLAHE → SIFT(nfeatures). """ from __future__ import annotations import io import cv2 import numpy as np from PIL import Image, ImageOps from app.cv.exceptions import ImageDecodeFailed, ImageFormatUnsupported, ImageTooSmall from app.cv.params import ExtractionParams MIN_WIDTH = 640 MIN_HEIGHT = 480 ALLOWED_IMAGE_FORMATS = {"JPEG", "PNG", "WEBP"} class Features: """Результат извлечения; координаты — в системе приведённого изображения.""" __slots__ = ("keypoints", "descriptors", "width", "height", "source_width", "source_height") def __init__( self, keypoints: np.ndarray, descriptors: np.ndarray, width: int, height: int, source_width: int, source_height: int, ): self.keypoints = keypoints # float32 (N, 5): x, y, size, angle, response self.descriptors = descriptors # uint8 (N, 128) self.width = width # размеры приведённого изображения self.height = height self.source_width = source_width # размеры оригинала после EXIF-ориентации self.source_height = source_height @property def count(self) -> int: return int(self.keypoints.shape[0]) def decode_image(data: bytes) -> tuple[np.ndarray, int, int]: """Декодирует изображение, применяет EXIF-ориентацию. Возвращает (RGB-массив, width, height) размеры после ориентации. Фактический формат определяется при декодировании, не по расширению (docs/05 §5.5-1). """ try: img = Image.open(io.BytesIO(data)) fmt = img.format if fmt not in ALLOWED_IMAGE_FORMATS: raise ImageFormatUnsupported(fmt) img = ImageOps.exif_transpose(img) except ImageFormatUnsupported: raise except Exception as exc: raise ImageDecodeFailed( f"Файл не декодируется как изображение: {exc.__class__.__name__}" ) from exc arr = np.asarray(img.convert("RGB")) return arr, img.width, img.height def _preprocess(rgb: np.ndarray, params: ExtractionParams) -> tuple[np.ndarray, int, int]: """Grayscale → ресайз длинной стороны ≤ max_image_size → CLAHE.""" gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) h, w = gray.shape[:2] long_side = max(h, w) if long_side > params.max_image_size: scale = params.max_image_size / long_side gray = cv2.resize( gray, (max(1, round(w * scale)), max(1, round(h * scale))), interpolation=cv2.INTER_AREA, ) clahe = cv2.createCLAHE( clipLimit=float(params.clahe_clip_limit), tileGridSize=(int(params.clahe_tile_grid[0]), int(params.clahe_tile_grid[1])), ) return clahe.apply(gray), gray.shape[1], gray.shape[0] def extract(data: bytes, params: ExtractionParams) -> Features: """Полный пайплайн извлечения признаков (docs/04 §4.2).""" rgb, src_w, src_h = decode_image(data) if src_w < MIN_WIDTH or src_h < MIN_HEIGHT: raise ImageTooSmall(src_w, src_h) prepared, width, height = _preprocess(rgb, params) sift = cv2.SIFT_create(nfeatures=int(params.max_keypoints)) keypoints, descriptors = sift.detectAndCompute(prepared, None) n = len(keypoints) if n == 0 or descriptors is None: # «Бедная» текстура деградирует без исключений (UT-07) return Features( np.zeros((0, 5), dtype=np.float32), np.zeros((0, 128), dtype=np.uint8), width, height, src_w, src_h, ) kp_array = np.array( [[kp.pt[0], kp.pt[1], kp.size, kp.angle, kp.response] for kp in keypoints], dtype=np.float32, ).reshape(n, 5) # Значения SIFT-дескрипторов дискретны 0–255: uint8 хранит их без потерь (docs/06 §6.2) desc_u8 = np.clip(np.rint(descriptors), 0, 255).astype(np.uint8) return Features(kp_array, desc_u8, width, height, src_w, src_h)