Files
hfut-bishe/python_server/app/routes/depth.py
T
2026-05-14 17:30:20 +08:00

34 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import numpy as np
from fastapi import APIRouter, HTTPException
from fastapi.responses import Response
from ..schemas import DepthRequest
from ..services.depth_io import depth_to_png16_bytes
from ..services.image_io import b64_to_pil_image
from ..services.predictors import get_depth_predictor
router = APIRouter(tags=["depth"])
@router.post("/depth")
def depth(req: DepthRequest):
"""
计算深度并直接返回二进制 PNG(16-bit 灰度)。
约束:
- 前端不传/不选模型;模型选择写死在后端 config.py
- 成功:HTTP 200 + Content-Type: image/png
- 失败:HTTP 500detail 为错误信息
"""
try:
pil = b64_to_pil_image(req.image_b64).convert("RGB")
w, h = pil.size
predictor = get_depth_predictor()
depth_arr = predictor(pil) # type: ignore[misc]
png_bytes = depth_to_png16_bytes(np.asarray(depth_arr), target_hw=(h, w))
return Response(content=png_bytes, media_type="image/png")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e