agrovia-detection-api / app /services /preprocessing_service.py
Kaaado's picture
feat: migrate full production detection service architecture with 8-model hub sync
119c847
Raw History Blame Contribute Delete
4.13 kB
"""
Detection Service — Image Preprocessing Service
Handles resizing, cropping, normalization for both YOLO and CNN pipelines.
SHA256 fingerprinting for cache keying.
"""
from __future__ import annotations
import hashlib
from io import BytesIO
from typing import Tuple
import numpy as np
from PIL import Image
from app.core.logging import get_logger
logger = get_logger(__name__)
class PreprocessingService:
"""Stateless image preprocessing utility."""
@staticmethod
def compute_image_hash(image_bytes: bytes) -> str:
"""SHA256 hash of raw image bytes for cache keying."""
return hashlib.sha256(image_bytes).hexdigest()
@staticmethod
def load_image(image_bytes: bytes) -> Image.Image:
"""Load an image from raw bytes. Converts to RGB."""
try:
img = Image.open(BytesIO(image_bytes)).convert("RGB")
return img
except Exception as exc:
logger.error("image_load_failed", error=str(exc))
raise ValueError(f"Failed to load image: {exc}")
@staticmethod
def validate_aspect_ratio(image: Image.Image, tolerance: float = 0.3) -> bool:
"""Check if image is approximately square."""
w, h = image.size
if h == 0 or w == 0:
return False
ratio = w / max(h, 1)
return abs(ratio - 1.0) <= tolerance
@staticmethod
def resize_for_yolo(image: Image.Image, target_size: int = 640) -> np.ndarray:
"""
Resize image for YOLO inference with letterbox padding.
Returns float32 array [1, 3, H, W] normalized to [0, 1].
"""
w, h = image.size
scale = min(target_size / max(w, 1), target_size / max(h, 1))
new_w, new_h = int(w * scale), int(h * scale)
resized = image.resize((new_w, new_h), Image.BILINEAR)
# Letterbox canvas
canvas = Image.new("RGB", (target_size, target_size), (114, 114, 114))
pad_x = (target_size - new_w) // 2
pad_y = (target_size - new_h) // 2
canvas.paste(resized, (pad_x, pad_y))
# HWC → CHW, normalize
arr = np.array(canvas, dtype=np.float32) / 255.0
arr = arr.transpose(2, 0, 1)
arr = np.expand_dims(arr, axis=0)
return arr
@staticmethod
def resize_for_cnn(
image: Image.Image,
target_size: int = 224,
center_crop: bool = True,
) -> np.ndarray:
"""
Resize and normalize image for CNN inference.
1. Resize shortest side → target_size
2. Center crop → target_size x target_size
3. Normalize with ImageNet mean/std
Returns float32 array [1, 3, H, W].
"""
w, h = image.size
if center_crop:
scale = target_size / max(min(w, h), 1)
new_w, new_h = int(w * scale), int(h * scale)
image = image.resize((new_w, new_h), Image.BILINEAR)
left = (new_w - target_size) // 2
top = (new_h - target_size) // 2
image = image.crop((left, top, left + target_size, top + target_size))
else:
image = image.resize((target_size, target_size), Image.BILINEAR)
arr = np.array(image, dtype=np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
arr = (arr - mean) / std
arr = arr.transpose(2, 0, 1)
arr = np.expand_dims(arr, axis=0)
return arr
@staticmethod
def crop_detection(
image: Image.Image,
bbox: Tuple[float, float, float, float],
padding: float = 0.1,
) -> Image.Image:
"""Crop detected region with padding."""
w, h = image.size
x1, y1, x2, y2 = bbox
bw, bh = x2 - x1, y2 - y1
x1 = max(0, x1 - bw * padding)
y1 = max(0, y1 - bh * padding)
x2 = min(w, x2 + bw * padding)
y2 = min(h, y2 + bh * padding)
# Ensure valid crop dimensions
if x2 <= x1 or y2 <= y1:
return image
return image.crop((int(x1), int(y1), int(x2), int(y2)))