File size: 4,126 Bytes
119c847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""
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)))