50 lines
2.2 KiB
Python
50 lines
2.2 KiB
Python
"""prod_server 客户端公共:HTTP 调用 + polygons→mask 还原。
|
||
|
||
刻意只放「服务交互」相关的东西——base64 编码、POST、把服务返回的 polygons
|
||
还原成布尔掩码。**渲染 / IO / 路径全部复用 `demos/_common.py`**(overlay_masks /
|
||
draw_points / save_image / load_image / in_path / out_path),与 demos 同源、零漂移;
|
||
因此客户端像 demos 一样在 `sam3` conda env 下跑(需 torch+cv2,但 import 不加载模型)。
|
||
|
||
资产路径统一用 demos/_common 的 in_path/out_path(指向 SAM3_Cloud/assets),不在本模块重复。
|
||
"""
|
||
import base64
|
||
import json
|
||
import os
|
||
import urllib.request
|
||
|
||
import cv2
|
||
import numpy as np
|
||
|
||
SERVER = os.environ.get("SAM3_SERVER", "http://127.0.0.1:8080")
|
||
|
||
|
||
def file_to_data_uri(path):
|
||
"""读文件 → `data:<mime>;base64,...`(服务按首个逗号切分取后半段 base64)。"""
|
||
ext = path.rsplit(".", 1)[-1].lower()
|
||
mime = {"mp4": "video/mp4", "mov": "video/quicktime", "jpg": "image/jpeg",
|
||
"jpeg": "image/jpeg", "png": "image/png", "bmp": "image/bmp"}.get(ext, "application/octet-stream")
|
||
with open(path, "rb") as f:
|
||
s = base64.b64encode(f.read()).decode()
|
||
return f"data:{mime};base64,{s}"
|
||
|
||
|
||
def post(path, payload, timeout=600):
|
||
"""POST JSON,返回解析后的 dict(响应包络 {status,message,data})。"""
|
||
data = json.dumps(payload).encode()
|
||
req = urllib.request.Request(
|
||
f"{SERVER}{path}", data=data, headers={"Content-Type": "application/json"})
|
||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||
return json.loads(r.read().decode())
|
||
|
||
|
||
def polygons_to_mask(polygons, w, h):
|
||
"""把服务返回的 polygons [[x,y], ...] 还原成 (H,W) bool 掩码。
|
||
|
||
服务只给「首条外轮廓」的简化多边形(approxPolyDP),这里 cv2.fillPoly 实心填回——
|
||
与 demos 的掩码语义一致(无孔洞),可直接喂 demos/_common.overlay_masks。
|
||
w,h 为图像宽高(PIL Image.size 顺序);掩码形状按 numpy 习惯为 (H,W)。
|
||
"""
|
||
pts = np.array(polygons, dtype=np.int32)
|
||
mask = cv2.fillPoly(np.zeros((h, w), dtype=np.uint8), [pts], 1)
|
||
return mask.astype(bool)
|