File size: 1,589 Bytes
1003449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Helpers for downscaling images before inference and upscaling results back."""

import cv2
import numpy as np
from PIL import Image

from config.runtime import INFERENCE_MAX_DIMENSION


def downscale_for_inference(
    img: Image.Image,
    img_np: np.ndarray,
) -> tuple[Image.Image, np.ndarray, float]:
    """Downscale image to INFERENCE_MAX_DIMENSION for model inference.

    Returns (resized_pil, resized_np, scale_factor).
    scale_factor is 1.0 if no resizing was needed.
    """
    h, w = img_np.shape[:2]
    largest = max(h, w)
    if largest <= INFERENCE_MAX_DIMENSION:
        return img, img_np, 1.0

    scale = INFERENCE_MAX_DIMENSION / float(largest)
    new_w = max(1, int(round(w * scale)))
    new_h = max(1, int(round(h * scale)))

    resized_pil = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
    resized_np = np.array(resized_pil)
    return resized_pil, resized_np, scale


def upscale_mask(mask: np.ndarray, target_h: int, target_w: int) -> np.ndarray:
    """Upscale a segmentation mask back to original resolution using nearest-neighbor."""
    if mask.shape[0] == target_h and mask.shape[1] == target_w:
        return mask
    return cv2.resize(mask, (target_w, target_h), interpolation=cv2.INTER_NEAREST)


def upscale_depth(depth: np.ndarray, target_h: int, target_w: int) -> np.ndarray:
    """Upscale a depth map back to original resolution using bicubic interpolation."""
    if depth.shape[0] == target_h and depth.shape[1] == target_w:
        return depth
    return cv2.resize(depth, (target_w, target_h), interpolation=cv2.INTER_CUBIC)