prevision / apps /renderer /services /pipeline /inference_utils.py
github-actions[bot]
Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd
1fe7075
Raw History Blame Contribute Delete
1.59 kB
"""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)