Compare commits
6
Commits
eaafbc97ea
...
554b64a916
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
554b64a916 | ||
|
|
891bc0da8b | ||
|
|
10488171eb | ||
|
|
9391408088 | ||
|
|
023bb2e6fd | ||
|
|
0eaaf05ac3 |
@@ -10,6 +10,10 @@ gateway/config.json
|
|||||||
# worker 配置(含鉴权密码,不入 git)
|
# worker 配置(含鉴权密码,不入 git)
|
||||||
worker_config.json
|
worker_config.json
|
||||||
|
|
||||||
|
# worker 运行期文件(PID / 日志)
|
||||||
|
worker.pid
|
||||||
|
worker.log
|
||||||
|
|
||||||
# SegFormer 模型权重(~323MB,体积过大,不入 git,见 OFFLINE_ASSETS.md)
|
# SegFormer 模型权重(~323MB,体积过大,不入 git,见 OFFLINE_ASSETS.md)
|
||||||
hairline/models/face-parsing/model.safetensors
|
hairline/models/face-parsing/model.safetensors
|
||||||
|
|
||||||
|
|||||||
+7
-3
@@ -19,10 +19,14 @@
|
|||||||
|------|------|------|
|
|------|------|------|
|
||||||
| model.safetensors | `hairline/models/face-parsing/model.safetensors` | 338,580,732 B (~323MB) |
|
| model.safetensors | `hairline/models/face-parsing/model.safetensors` | 338,580,732 B (~323MB) |
|
||||||
|
|
||||||
下载命令:
|
下载命令(国内用 hf-mirror 镜像,快很多):
|
||||||
```bash
|
```bash
|
||||||
|
# 国内镜像(推荐)
|
||||||
curl -L -o hairline/models/face-parsing/model.safetensors \
|
curl -L -o hairline/models/face-parsing/model.safetensors \
|
||||||
"https://huggingface.co/jonathandinu/face-parsing/resolve/main/model.safetensors"
|
"https://hf-mirror.com/jonathandinu/face-parsing/resolve/main/model.safetensors"
|
||||||
|
# 官方源
|
||||||
|
# curl -L -o hairline/models/face-parsing/model.safetensors \
|
||||||
|
# "https://huggingface.co/jonathandinu/face-parsing/resolve/main/model.safetensors"
|
||||||
```
|
```
|
||||||
|
|
||||||
sha256 校验:
|
sha256 校验:
|
||||||
@@ -77,7 +81,7 @@ model.safetensors https://huggingface.co/jonathandinu/face-parsing/resol
|
|||||||
|
|
||||||
模型已就位,但**内网机还需要 Python 依赖的离线 wheel 包**,否则 `pip install` 在内网无法联网安装。这部分**与目标机的操作系统、Python 版本、CUDA 版本强相关**,需确认后单独打包:
|
模型已就位,但**内网机还需要 Python 依赖的离线 wheel 包**,否则 `pip install` 在内网无法联网安装。这部分**与目标机的操作系统、Python 版本、CUDA 版本强相关**,需确认后单独打包:
|
||||||
|
|
||||||
- **worker(GPU 机)**:`mediapipe` / `opencv-python` / `numpy<2` / `Pillow` / **`torch`+`torchvision` 的 CUDA 版**(按 GPU 的 CUDA 版本选 cu118/cu121 等)+ FastAPI/uvicorn 全家桶。
|
- **worker(GPU 机)**:`mediapipe` / `opencv-python` / `numpy<2` / `Pillow` / **`torch`+`torchvision` 的 CUDA 版**(按 GPU 的 CUDA 版本选 cu118/cu121 等)/ `transformers`(接口2 SegFormer)+ FastAPI/uvicorn 全家桶。
|
||||||
- **网关机**:很轻,只需 FastAPI/uvicorn/httpx 等代理依赖,**不需要 torch/mediapipe**。
|
- **网关机**:很轻,只需 FastAPI/uvicorn/httpx 等代理依赖,**不需要 torch/mediapipe**。
|
||||||
|
|
||||||
> 架构已拆分(见 `docs/系统架构-网关与高性能后端.md`):算法依赖只装在 worker,网关保持轻量。
|
> 架构已拆分(见 `docs/系统架构-网关与高性能后端.md`):算法依赖只装在 worker,网关保持轻量。
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ from fastapi.responses import JSONResponse
|
|||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
logger = logging.getLogger("hair.worker")
|
logger = logging.getLogger("hair.worker")
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -68,6 +70,14 @@ async def lifespan(_app: FastAPI):
|
|||||||
except Exception as e: # noqa: BLE001
|
except Exception as e: # noqa: BLE001
|
||||||
# 方案 B 不可用(如 torch 缺失):降级为方案 A only,不阻塞服务
|
# 方案 B 不可用(如 torch 缺失):降级为方案 A only,不阻塞服务
|
||||||
logger.warning("头发分割不可用,接口1 将走方案A兜底:%s", e)
|
logger.warning("头发分割不可用,接口1 将走方案A兜底:%s", e)
|
||||||
|
# 接口2(C端生发)单例预热:FaceLandmarker + SegFormer + mesh/贴图映射
|
||||||
|
try:
|
||||||
|
from hairline.service import get_landmarker, get_parser, get_texture_map
|
||||||
|
from hairline.render import load_ext_mesh
|
||||||
|
get_landmarker(); get_parser(); load_ext_mesh(); get_texture_map()
|
||||||
|
logger.info("接口2 发际线管线就绪")
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
logger.warning("接口2 发际线管线初始化失败(该接口将返回错误):%s", e)
|
||||||
_STATE["ready"] = True
|
_STATE["ready"] = True
|
||||||
yield
|
yield
|
||||||
|
|
||||||
@@ -415,10 +425,11 @@ async def face_measure(
|
|||||||
summary="接口2 C端生发",
|
summary="接口2 C端生发",
|
||||||
tags=["生发"],
|
tags=["生发"],
|
||||||
description=f"""
|
description=f"""
|
||||||
输入用户正面照,返回多个生发方案,每个方案包含:
|
输入用户正面照 + **性别**,返回该性别对应的多张「建议发际线预览图」(本期为
|
||||||
- 生发后效果图 URL
|
**发际线曲线叠加在原照片上的预览图**,非最终文生图生发图)。每个方案包含:
|
||||||
- 对应的发际线形(如花瓣形、波浪形)
|
- 预览图(worker 返回 `image_base64`,网关落盘后改写为 `image_url`)
|
||||||
- 合适度排序(order=1 最优)
|
- 发际线类型 `hairline_type`(英文 key)
|
||||||
|
- 顺序 `order`(本期固定 `1..N`,不排序)
|
||||||
|
|
||||||
{_image_fields_desc}
|
{_image_fields_desc}
|
||||||
|
|
||||||
@@ -426,7 +437,12 @@ async def face_measure(
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**beauty_enabled**:是否对生发后图片开启美颜,默认 `false`。
|
- **gender**(必填):`male` / `female`。决定返回的贴图集合(female 5 张 / male 4 张)。
|
||||||
|
非法或缺失返回 `1004`。
|
||||||
|
- **beauty_enabled**:本期保留但不生效。
|
||||||
|
|
||||||
|
`hairline_type` 取值:`ellipse` / `flower` / `heart` / `straight` / `wave`(female),
|
||||||
|
`ellipse` / `m` / `straight` / `inverse_arc`(male)。
|
||||||
""",
|
""",
|
||||||
responses={
|
responses={
|
||||||
200: {
|
200: {
|
||||||
@@ -439,8 +455,8 @@ async def face_measure(
|
|||||||
"request_id": "mock-request-id",
|
"request_id": "mock-request-id",
|
||||||
"data": {
|
"data": {
|
||||||
"results": [
|
"results": [
|
||||||
{"image_url": SAMPLE_IMAGE_URL, "hairline_type": "花瓣形", "order": 1},
|
{"image_base64": "iVBORw0KGgo...", "hairline_type": "ellipse", "order": 1},
|
||||||
{"image_url": SAMPLE_IMAGE_URL, "hairline_type": "波浪形", "order": 2},
|
{"image_base64": "iVBORw0KGgo...", "hairline_type": "flower", "order": 2},
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -464,15 +480,48 @@ async def hair_grow(
|
|||||||
image_file: Optional[UploadFile] = File(default=None, description="上传图片文件(JPG/PNG,≤ 1 MB)"),
|
image_file: Optional[UploadFile] = File(default=None, description="上传图片文件(JPG/PNG,≤ 1 MB)"),
|
||||||
image_url: Optional[str] = Form(default=None, description="图片 URL"),
|
image_url: Optional[str] = Form(default=None, description="图片 URL"),
|
||||||
image_base64: Optional[str] = Form(default=None, description="图片 base64(需带 data:image/...;base64, 前缀)"),
|
image_base64: Optional[str] = Form(default=None, description="图片 base64(需带 data:image/...;base64, 前缀)"),
|
||||||
beauty_enabled: bool = Form(default=False, description="是否开启美颜效果,默认 false"),
|
gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"),
|
||||||
|
beauty_enabled: bool = Form(default=False, description="是否开启美颜(本期不生效)"),
|
||||||
):
|
):
|
||||||
data = {
|
# 1. gender 必填校验(非法/缺失 → 1004)
|
||||||
"results": [
|
if gender not in ("male", "female"):
|
||||||
{"image_url": SAMPLE_IMAGE_URL, "hairline_type": "花瓣形", "order": 1},
|
return err(1004, "gender 必填且只能为 male / female")
|
||||||
{"image_url": SAMPLE_IMAGE_URL, "hairline_type": "波浪形", "order": 2},
|
|
||||||
]
|
# 2. 三选一取图
|
||||||
}
|
raw, e = await resolve_image_bytes(image_file, image_url, image_base64)
|
||||||
return ok(data)
|
if e is not None:
|
||||||
|
return e
|
||||||
|
if len(raw) > MAX_FILE_BYTES:
|
||||||
|
return err(1006, "文件超出 1 MB 限制")
|
||||||
|
|
||||||
|
image = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR)
|
||||||
|
if image is None:
|
||||||
|
return err(1008, "图片格式不支持(仅 JPG / PNG)")
|
||||||
|
|
||||||
|
h, w = image.shape[:2]
|
||||||
|
short_side, long_side = min(w, h), max(w, h)
|
||||||
|
if short_side < MIN_SHORT_SIDE or long_side < MIN_LONG_SIDE:
|
||||||
|
return err(1002, "人像分辨率过低")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from hairline.service import generate_previews
|
||||||
|
|
||||||
|
previews = generate_previews(image, gender) # 无人脸 → None
|
||||||
|
if previews is None:
|
||||||
|
return err(1001, "无法识别人像")
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for p in previews:
|
||||||
|
ok_enc, png = cv2.imencode(".png", p["image_bgr"])
|
||||||
|
results.append({
|
||||||
|
"image_base64": base64.b64encode(png.tobytes()).decode(),
|
||||||
|
"hairline_type": p["hairline_type"],
|
||||||
|
"order": p["order"],
|
||||||
|
})
|
||||||
|
return ok({"results": results})
|
||||||
|
except Exception as ex: # noqa: BLE001
|
||||||
|
logger.exception("接口2 处理异常")
|
||||||
|
return err(1007, f"处理失败:{ex}")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
+98
-37
@@ -44,6 +44,29 @@ def draw_gradient_horizontal_line(buf, cx, cy, color=LINE_COLOR, half_length=Non
|
|||||||
row[mask, 3] = np.maximum(row[mask, 3], alpha[mask].astype(np.uint8))
|
row[mask, 3] = np.maximum(row[mask, 3], alpha[mask].astype(np.uint8))
|
||||||
|
|
||||||
|
|
||||||
|
def draw_gradient_vertical_line(buf, cx, y0, y1, color=LINE_COLOR, fade=None):
|
||||||
|
"""在 RGBA numpy 缓冲 buf 上画一条竖线,两端渐变消失(中间实、上下淡)。"""
|
||||||
|
h, w = buf.shape[:2]
|
||||||
|
cx = int(round(cx))
|
||||||
|
if not (0 <= cx < w):
|
||||||
|
return
|
||||||
|
y0, y1 = int(round(y0)), int(round(y1))
|
||||||
|
y0, y1 = max(0, min(y0, y1)), min(h - 1, max(y0, y1))
|
||||||
|
if y1 <= y0:
|
||||||
|
return
|
||||||
|
ys = np.arange(y0, y1 + 1)
|
||||||
|
span = y1 - y0
|
||||||
|
fade = fade or max(1, span // 5) # 仅两端 ~1/5 段渐隐
|
||||||
|
d = np.minimum(ys - y0, y1 - ys) # 到最近端点的距离
|
||||||
|
alpha = np.clip(d / fade, 0.0, 1.0) * color[3]
|
||||||
|
col = buf[y0:y1 + 1, cx]
|
||||||
|
m = alpha > 0
|
||||||
|
col[m, 0] = color[0]
|
||||||
|
col[m, 1] = color[1]
|
||||||
|
col[m, 2] = color[2]
|
||||||
|
col[m, 3] = np.maximum(col[m, 3], alpha[m].astype(np.uint8))
|
||||||
|
|
||||||
|
|
||||||
def draw_dashed_line_with_arrows(draw, x1, y1, x2, y2, color=LINE_COLOR,
|
def draw_dashed_line_with_arrows(draw, x1, y1, x2, y2, color=LINE_COLOR,
|
||||||
dash_len=6, gap_len=4, arrow_size=5):
|
dash_len=6, gap_len=4, arrow_size=5):
|
||||||
"""两点间画虚线,两端带箭头(等腰三角)。"""
|
"""两点间画虚线,两端带箭头(等腰三角)。"""
|
||||||
@@ -69,58 +92,96 @@ def draw_dashed_line_with_arrows(draw, x1, y1, x2, y2, color=LINE_COLOR,
|
|||||||
draw.line([p2, (ex, ey)], fill=color, width=LINE_WIDTH)
|
draw.line([p2, (ex, ey)], fill=color, width=LINE_WIDTH)
|
||||||
|
|
||||||
|
|
||||||
|
def _text_size(draw, text, font):
|
||||||
|
bbox = draw.textbbox((0, 0), text, font=font)
|
||||||
|
return bbox[2] - bbox[0], bbox[3] - bbox[1]
|
||||||
|
|
||||||
|
|
||||||
|
_LINE_NAMES = {
|
||||||
|
"hair_top": "头顶",
|
||||||
|
"hairline": "发际线",
|
||||||
|
"brow_center": "眉心",
|
||||||
|
"nose_bottom": "鼻翼下缘",
|
||||||
|
"chin_tip": "下巴尖",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def create_annotated_image(image_bgr, measure_result):
|
def create_annotated_image(image_bgr, measure_result):
|
||||||
"""生成标注图层 PNG(透明底 RGBA,尺寸同原图)。返回 PIL.Image。"""
|
"""生成标注图层 PNG(透明底 RGBA,尺寸同原图)。返回 PIL.Image。
|
||||||
|
|
||||||
|
布局:
|
||||||
|
- 线条只覆盖人脸范围(横线=脸宽,竖线=脸高),渐变消失。
|
||||||
|
- 横向 5 条分界线:头顶/发际线/眉心/鼻翼下缘/下巴尖,**线名在右侧**;
|
||||||
|
四庭 cm 数值(顶庭/上庭/中庭/下庭)在左侧各段中点。
|
||||||
|
- 纵向 6 条线:左脸颊/左眼外角/左眼内角/右眼内角/右眼外角/右脸颊,把脸宽切 5 段;
|
||||||
|
每段宽度在脸的**上端和下端**各标一次(只标 `X.XXcm`,不写名)。
|
||||||
|
"""
|
||||||
h, w = image_bgr.shape[:2]
|
h, w = image_bgr.shape[:2]
|
||||||
v = measure_result.vertical
|
v = measure_result.vertical
|
||||||
|
pc = measure_result.px_per_cm
|
||||||
|
|
||||||
# --- 1. 四庭水平分界线(numpy 渐变) ---
|
|
||||||
buf = np.zeros((h, w, 4), dtype=np.uint8)
|
buf = np.zeros((h, w, 4), dtype=np.uint8)
|
||||||
|
|
||||||
order = ["hair_top", "hairline", "brow_center", "nose_bottom", "chin_tip"]
|
order = ["hair_top", "hairline", "brow_center", "nose_bottom", "chin_tip"]
|
||||||
ys = [v[name][1] for name in order]
|
ys = [v[name][1] for name in order]
|
||||||
cx_line = v["brow_center"][0]
|
|
||||||
|
pts = measure_result.eyes["points"]
|
||||||
|
seven_keys = ["left_cheek", "left_outer", "left_inner",
|
||||||
|
"right_inner", "right_outer", "right_cheek"]
|
||||||
|
xs = sorted(pts[k][0] for k in seven_keys) # 自左向右
|
||||||
|
|
||||||
|
# 人脸包围盒:x 为脸宽(左右脸颊),y 为脸高(头顶→下巴)
|
||||||
|
fx0, fx1 = xs[0], xs[-1]
|
||||||
|
fy0, fy1 = ys[0], ys[-1]
|
||||||
|
face_cx = (fx0 + fx1) / 2
|
||||||
|
face_half = (fx1 - fx0) / 2 * 1.08 # 略放大确保横线覆盖到脸颊
|
||||||
|
|
||||||
|
# --- 1. 横向 5 条分界线(渐变,覆盖脸宽) ---
|
||||||
for cy in ys:
|
for cy in ys:
|
||||||
draw_gradient_horizontal_line(buf, cx_line, cy)
|
draw_gradient_horizontal_line(buf, face_cx, cy, half_length=face_half)
|
||||||
|
|
||||||
|
# --- 2. 纵向 6 条线(渐变,覆盖脸高 头顶→下巴) ---
|
||||||
|
for vx in xs:
|
||||||
|
draw_gradient_vertical_line(buf, vx, fy0, fy1)
|
||||||
|
|
||||||
canvas = Image.fromarray(buf, mode="RGBA")
|
canvas = Image.fromarray(buf, mode="RGBA")
|
||||||
draw = ImageDraw.Draw(canvas)
|
draw = ImageDraw.Draw(canvas)
|
||||||
font = _load_font()
|
font = _load_font()
|
||||||
|
|
||||||
# --- 2. 四庭 cm 数值(左侧) ---
|
# --- 3a. 横线右侧:线名(头顶/发际线/眉心/鼻翼下缘/下巴尖) ---
|
||||||
court_labels = [
|
name_x = fx1 + 8
|
||||||
("顶庭", measure_result.top_cm),
|
for i, name in enumerate(order):
|
||||||
("上庭", measure_result.upper_cm),
|
text = _LINE_NAMES[name]
|
||||||
("中庭", measure_result.middle_cm),
|
tw, _ = _text_size(draw, text, font)
|
||||||
("下庭", measure_result.lower_cm),
|
x = min(name_x, w - 2 - tw) # 右侧越界时回收
|
||||||
]
|
draw.text((x, ys[i] - FONT_SIZE / 2), text, fill=LINE_COLOR, font=font)
|
||||||
left_margin = 16
|
|
||||||
for i, (label, cm_val) in enumerate(court_labels):
|
# --- 3b. 横线左侧:四庭 cm 数值(各段中点,右对齐到脸盒左缘) ---
|
||||||
|
court_cm = [measure_result.top_cm, measure_result.upper_cm,
|
||||||
|
measure_result.middle_cm, measure_result.lower_cm]
|
||||||
|
court_name = ["顶庭", "上庭", "中庭", "下庭"]
|
||||||
|
for i in range(4):
|
||||||
|
text = f"{court_name[i]} {court_cm[i]:.2f}cm"
|
||||||
|
tw, _ = _text_size(draw, text, font)
|
||||||
|
x = max(2, fx0 - 8 - tw) # 贴脸盒左缘,右对齐
|
||||||
y_mid = (ys[i] + ys[i + 1]) / 2 - FONT_SIZE / 2
|
y_mid = (ys[i] + ys[i + 1]) / 2 - FONT_SIZE / 2
|
||||||
draw.text((left_margin, y_mid), f"{label} {cm_val:.2f}cm",
|
draw.text((x, y_mid), text, fill=LINE_COLOR, font=font)
|
||||||
fill=LINE_COLOR, font=font)
|
|
||||||
|
|
||||||
# --- 3. 七眼标注(虚线箭头 + 上下穿插标签) ---
|
# --- 4. 七眼每段宽度:脸的上端 + 下端各标一次(相邻段上下错行防重叠) ---
|
||||||
pts = measure_result.eyes["points"]
|
row_h = FONT_SIZE + 2
|
||||||
pc = measure_result.px_per_cm
|
y_top_a = max(1, fy0 - row_h - 2) # 上端:头顶线上方两行
|
||||||
eye_y = (pts["left_inner"][1] + pts["right_inner"][1]) / 2
|
y_top_b = max(1, fy0 - 2 * row_h - 2)
|
||||||
|
y_bot_a = min(h - FONT_SIZE - 1, fy1 + 2) # 下端:下巴线下方两行
|
||||||
def hline(p_left, p_right, label, cm_val, above):
|
y_bot_b = min(h - FONT_SIZE - 1, fy1 + row_h + 2)
|
||||||
y = eye_y
|
for i in range(len(xs) - 1):
|
||||||
draw_dashed_line_with_arrows(draw, p_left[0], y, p_right[0], y)
|
seg_cm = (xs[i + 1] - xs[i]) / pc
|
||||||
text = f"{label} {cm_val:.2f}cm"
|
cx_seg = (xs[i] + xs[i + 1]) / 2
|
||||||
tx = (p_left[0] + p_right[0]) / 2
|
text = f"{seg_cm:.2f}cm"
|
||||||
ty = y - FONT_SIZE - 4 if above else y + 4
|
tw, _ = _text_size(draw, text, font)
|
||||||
bbox = draw.textbbox((0, 0), text, font=font)
|
ty_top = y_top_a if i % 2 == 0 else y_top_b
|
||||||
tw = bbox[2] - bbox[0]
|
ty_bot = y_bot_a if i % 2 == 0 else y_bot_b
|
||||||
draw.text((tx - tw / 2, ty), text, fill=LINE_COLOR, font=font)
|
draw.text((cx_seg - tw / 2, ty_top), text, fill=LINE_COLOR, font=font)
|
||||||
|
draw.text((cx_seg - tw / 2, ty_bot), text, fill=LINE_COLOR, font=font)
|
||||||
# 眼宽(左眼,标签在上)、两眼间距(标签在下)、脸宽(标签在上)—— 上下穿插
|
|
||||||
hline(pts["left_outer"], pts["left_inner"],
|
|
||||||
"眼宽", measure_result.eye_width_cm, above=True)
|
|
||||||
hline(pts["left_inner"], pts["right_inner"],
|
|
||||||
"间距", measure_result.inter_eye_cm, above=False)
|
|
||||||
hline(pts["left_cheek"], pts["right_cheek"],
|
|
||||||
"脸宽", measure_result.face_width_cm, above=True)
|
|
||||||
|
|
||||||
return canvas
|
return canvas
|
||||||
|
|
||||||
|
|||||||
@@ -162,4 +162,9 @@ PARSE_NECK_L = 16
|
|||||||
PARSE_NECK = 17
|
PARSE_NECK = 17
|
||||||
PARSE_CLOTH = 18
|
PARSE_CLOTH = 18
|
||||||
|
|
||||||
HF_FACE_PARSER_MODEL = "jonathandinu/face-parsing"
|
# 内网/离线:指向本地权重目录(transformers from_pretrained 支持本地路径)。
|
||||||
|
# 在线 id 为 "jonathandinu/face-parsing",权重已放到 hairline/models/face-parsing/。
|
||||||
|
import os as _os
|
||||||
|
HF_FACE_PARSER_MODEL = _os.path.join(
|
||||||
|
_os.path.dirname(_os.path.abspath(__file__)), "models", "face-parsing"
|
||||||
|
)
|
||||||
|
|||||||
@@ -11,8 +11,9 @@ from __future__ import annotations
|
|||||||
import os
|
import os
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
# 模型在 hairline/models/ 下(模块即在 hairline/ 根),故只取一层 dirname。
|
||||||
DEFAULT_MODEL_PATH = os.path.join(
|
DEFAULT_MODEL_PATH = os.path.join(
|
||||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
os.path.dirname(os.path.abspath(__file__)),
|
||||||
"models", "face_landmarker.task",
|
"models", "face_landmarker.task",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""接口2 渲染器:把发际线类型贴图按 502 点 mesh 贴到照片上(OpenCV 逐三角仿射 warp)。
|
||||||
|
|
||||||
|
原理(技术方案 §4):face_ext.obj 的 502 顶点里,[468..485) 中间行 + [485..502) 发际线行
|
||||||
|
与 17 个 MP 顶部锚点连成 ~64 个 ribbon 三角形,其 UV 落在贴图顶部条带(发际线曲线所在)。
|
||||||
|
只 warp 这些扩展三角形,即可把贴图里的发际线曲线贴到额头/发际线区域,且天然只画在 ribbon 区。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import os
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from .obj_io import read_obj
|
||||||
|
from ._index_map_data import INDEX_MAP_468
|
||||||
|
|
||||||
|
_MESH_PATH = os.path.join(os.path.dirname(__file__), "mesh", "face_ext.obj")
|
||||||
|
_N_MP = 468
|
||||||
|
|
||||||
|
_mesh_cache = None
|
||||||
|
_INDEX_MAP = np.asarray(INDEX_MAP_468, dtype=np.int64) # OBJ顶点i → MP点索引
|
||||||
|
|
||||||
|
|
||||||
|
def mp_order_to_obj_order(points502_mp: np.ndarray) -> np.ndarray:
|
||||||
|
"""把 MP 顺序的 502 点重排成 face_ext.obj 的顶点顺序。
|
||||||
|
|
||||||
|
extract_hairline 输出为 MP 顺序:[0..468) MP / [468..485) middle / [485..502) hairline。
|
||||||
|
而 face_ext.obj 的前 468 顶点经 INDEX_MAP_468 重排(obj_i → mp_i);扩展顶点
|
||||||
|
[468..502) 两侧同序,直接对应。
|
||||||
|
"""
|
||||||
|
out = np.empty_like(points502_mp)
|
||||||
|
out[:_N_MP] = points502_mp[_INDEX_MAP] # obj[0..468) = mp[INDEX_MAP]
|
||||||
|
out[_N_MP:] = points502_mp[_N_MP:] # 扩展行同序
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def load_ext_mesh(obj_path: str = _MESH_PATH):
|
||||||
|
"""解析 face_ext.obj,返回 (uv502, ext_faces)。结果缓存。
|
||||||
|
|
||||||
|
- uv502: (502, 2) float32,每个顶点的 UV(V_raw,V=1 对应贴图顶部)。
|
||||||
|
- ext_faces: list[(i,j,k)],仅保留顶点索引含 ≥468 的扩展三角形(ribbon)。
|
||||||
|
obj 中 v 与 vt 一一对应(face 用相同索引),故按位置索引取 UV。
|
||||||
|
"""
|
||||||
|
global _mesh_cache
|
||||||
|
if _mesh_cache is not None:
|
||||||
|
return _mesh_cache
|
||||||
|
|
||||||
|
mesh = read_obj(obj_path)
|
||||||
|
n_v = len(mesh.positions)
|
||||||
|
uv = np.zeros((n_v, 2), dtype=np.float32)
|
||||||
|
for face in mesh.faces:
|
||||||
|
for pi, ti, _ni in face:
|
||||||
|
if ti >= 0 and pi >= 0:
|
||||||
|
uv[pi] = mesh.texcoords[ti]
|
||||||
|
|
||||||
|
ext_faces = []
|
||||||
|
for face in mesh.faces:
|
||||||
|
idx = [pi for (pi, _t, _n) in face]
|
||||||
|
if max(idx) >= _N_MP: # 含扩展顶点 → ribbon 三角形
|
||||||
|
ext_faces.append(tuple(idx))
|
||||||
|
|
||||||
|
_mesh_cache = (uv, ext_faces)
|
||||||
|
return _mesh_cache
|
||||||
|
|
||||||
|
|
||||||
|
def load_texture_rgba(path: str) -> np.ndarray:
|
||||||
|
"""读发际线贴图为 (H, W, 4) uint8 RGBA。"""
|
||||||
|
return np.array(Image.open(path).convert("RGBA"))
|
||||||
|
|
||||||
|
|
||||||
|
def render_hairline_overlay(photo_bgr: np.ndarray,
|
||||||
|
points502_norm: np.ndarray,
|
||||||
|
ext_faces,
|
||||||
|
uv502: np.ndarray,
|
||||||
|
texture_rgba: np.ndarray) -> np.ndarray:
|
||||||
|
"""把 texture_rgba 的发际线曲线渲染到 photo_bgr 上,返回 BGR 预览图。
|
||||||
|
|
||||||
|
points502_norm: (502, 3) 归一化坐标(x,y ∈ [0,1]),**MP 顺序**(extract_hairline 输出)。
|
||||||
|
"""
|
||||||
|
H, W = photo_bgr.shape[:2]
|
||||||
|
TH, TW = texture_rgba.shape[:2]
|
||||||
|
pts_obj = mp_order_to_obj_order(points502_norm) # MP序 → OBJ序
|
||||||
|
img_xy = pts_obj[:, :2] * np.array([W, H], dtype=np.float32) # (502,2)
|
||||||
|
|
||||||
|
overlay = np.zeros((H, W, 4), np.float32) # 累积曲线层 RGBA
|
||||||
|
tex = texture_rgba.astype(np.float32)
|
||||||
|
for (i, j, k) in ext_faces:
|
||||||
|
dst = img_xy[[i, j, k]].astype(np.float32)
|
||||||
|
# UV → 贴图像素;flipY:贴图 y = (1 - v_raw) * TH(与 head3d Three.js flipY=true 一致)
|
||||||
|
src = np.array([[uv502[v][0] * TW, (1.0 - uv502[v][1]) * TH] for v in (i, j, k)],
|
||||||
|
dtype=np.float32)
|
||||||
|
# 退化三角形(投影到一条线)跳过,避免 getAffineTransform 奇异
|
||||||
|
if cv2.contourArea(dst.astype(np.int32)) < 1.0:
|
||||||
|
continue
|
||||||
|
M = cv2.getAffineTransform(src, dst)
|
||||||
|
warped = cv2.warpAffine(tex, M, (W, H), flags=cv2.INTER_LINEAR,
|
||||||
|
borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0, 0))
|
||||||
|
tri_mask = np.zeros((H, W), np.uint8)
|
||||||
|
cv2.fillConvexPoly(tri_mask, dst.astype(np.int32), 255)
|
||||||
|
sel = tri_mask > 0
|
||||||
|
overlay[sel] = warped[sel]
|
||||||
|
|
||||||
|
# alpha 合成(RGBA→BGR:贴图 RGB 顺序需反成 BGR)
|
||||||
|
a = overlay[:, :, 3:4] / 255.0
|
||||||
|
rgb = overlay[:, :, :3][..., ::-1] # RGB→BGR
|
||||||
|
out = photo_bgr.astype(np.float32) * (1.0 - a) + rgb * a
|
||||||
|
return np.clip(out, 0, 255).astype(np.uint8)
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""接口2 服务层:模型单例 + 性别贴图映射 + 「照片→N 张发际线预览图」管线。
|
||||||
|
|
||||||
|
把 head3d 的 extract_hairline 步骤包成单例复用(避免每请求重建模型),再按性别
|
||||||
|
对每张贴图调 render.render_hairline_overlay 生成预览图。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from . import constants as C
|
||||||
|
from .face_landmarks import FaceLandmarker
|
||||||
|
from .face_parsing import FaceParser
|
||||||
|
from .hairline_2d import sample_hairline, smooth_hairline
|
||||||
|
from .lift_3d import lift_hairline_to_3d, build_middle_row, assemble_full
|
||||||
|
from .render import load_ext_mesh, load_texture_rgba, render_hairline_overlay
|
||||||
|
|
||||||
|
_TEXTURE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "hairline_texture")
|
||||||
|
|
||||||
|
# ⚠️ 本 worker 是 RTX 5090(sm_120),torch 2.2.2(cu121) 只编到 sm_90,CUDA 跑算子会报
|
||||||
|
# "no kernel image"。SegFormer 默认走 CPU(~2.5s/张)。换 torch cu128 后可设 SEG_DEVICE=cuda。
|
||||||
|
_SEG_DEVICE = os.getenv("SEG_DEVICE", "cpu")
|
||||||
|
|
||||||
|
_landmarker = None
|
||||||
|
_parser = None
|
||||||
|
_texture_map = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_landmarker() -> FaceLandmarker:
|
||||||
|
global _landmarker
|
||||||
|
if _landmarker is None:
|
||||||
|
_landmarker = FaceLandmarker(static_image_mode=True)
|
||||||
|
return _landmarker
|
||||||
|
|
||||||
|
|
||||||
|
def get_parser() -> FaceParser:
|
||||||
|
global _parser
|
||||||
|
if _parser is None:
|
||||||
|
_parser = FaceParser(device=_SEG_DEVICE)
|
||||||
|
return _parser
|
||||||
|
|
||||||
|
|
||||||
|
def _gender_key(stem: str):
|
||||||
|
"""文件名 stem → (gender, key);非 girl_/man_ 前缀返回 (None, None)。"""
|
||||||
|
if stem.startswith("girl_"):
|
||||||
|
return "female", stem[5:].replace(" ", "").strip()
|
||||||
|
if stem.startswith("man_"):
|
||||||
|
return "male", stem[4:].replace(" ", "").strip()
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
|
||||||
|
def get_texture_map() -> dict:
|
||||||
|
"""扫描 hairline_texture/ 建 {gender: [(key, path)]},按 key 排序、缓存。
|
||||||
|
|
||||||
|
文件名规范化去空格(如 `man_ inverse_arc.png` → key `inverse_arc`)。
|
||||||
|
"""
|
||||||
|
global _texture_map
|
||||||
|
if _texture_map is not None:
|
||||||
|
return _texture_map
|
||||||
|
mapping: dict[str, list] = {"female": [], "male": []}
|
||||||
|
for path in sorted(glob.glob(os.path.join(_TEXTURE_DIR, "*.png"))):
|
||||||
|
stem = os.path.splitext(os.path.basename(path))[0]
|
||||||
|
gender, key = _gender_key(stem)
|
||||||
|
if gender:
|
||||||
|
mapping[gender].append((key, path))
|
||||||
|
for g in mapping:
|
||||||
|
mapping[g].sort(key=lambda kp: kp[0])
|
||||||
|
_texture_map = mapping
|
||||||
|
return _texture_map
|
||||||
|
|
||||||
|
|
||||||
|
def extract_502(image_bgr: np.ndarray):
|
||||||
|
"""照片(BGR) → (points502 MP序, valid17)。无人脸返回 (None, None)。"""
|
||||||
|
rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
||||||
|
landmarks = get_landmarker().detect(rgb)
|
||||||
|
if landmarks is None:
|
||||||
|
return None, None
|
||||||
|
parse_map = get_parser().parse(rgb)
|
||||||
|
hairline_2d, valid = sample_hairline(landmarks, parse_map)
|
||||||
|
hairline_2d = smooth_hairline(hairline_2d, valid)
|
||||||
|
hairline_3d = lift_hairline_to_3d(landmarks, hairline_2d)
|
||||||
|
middle_3d = build_middle_row(landmarks, hairline_3d)
|
||||||
|
points = assemble_full(landmarks, middle_3d, hairline_3d)
|
||||||
|
return points, valid
|
||||||
|
|
||||||
|
|
||||||
|
def generate_previews(image_bgr: np.ndarray, gender: str):
|
||||||
|
"""生成该性别全部发际线预览图。
|
||||||
|
|
||||||
|
Returns: list[dict],每项 {"hairline_type": key, "image_bgr": ndarray, "order": 1..N}。
|
||||||
|
无人脸返回 None。gender 必须是 male/female。
|
||||||
|
"""
|
||||||
|
if gender not in ("male", "female"):
|
||||||
|
raise ValueError(f"gender 必须是 male/female,收到 {gender!r}")
|
||||||
|
points, _valid = extract_502(image_bgr)
|
||||||
|
if points is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
uv, ext_faces = load_ext_mesh()
|
||||||
|
results = []
|
||||||
|
for order, (key, path) in enumerate(get_texture_map()[gender], start=1):
|
||||||
|
tex = load_texture_rgba(path)
|
||||||
|
preview = render_hairline_overlay(image_bgr, points, ext_faces, uv, tex)
|
||||||
|
results.append({"hairline_type": key, "image_bgr": preview, "order": order})
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import sys
|
||||||
|
g = sys.argv[2] if len(sys.argv) > 2 else "female"
|
||||||
|
img = cv2.imread(sys.argv[1] if len(sys.argv) > 1 else "tests/fixtures/frontal.jpg")
|
||||||
|
os.makedirs("tests/output", exist_ok=True)
|
||||||
|
print("texture map:", {k: [kp[0] for kp in v] for k, v in get_texture_map().items()})
|
||||||
|
res = generate_previews(img, g)
|
||||||
|
if res is None:
|
||||||
|
print("无人脸")
|
||||||
|
sys.exit(1)
|
||||||
|
for r in res:
|
||||||
|
out = f"tests/output/preview_{g}_{r['hairline_type']}.png"
|
||||||
|
cv2.imwrite(out, r["image_bgr"])
|
||||||
|
print(f" order={r['order']} type={r['hairline_type']} -> {out}")
|
||||||
@@ -18,5 +18,9 @@ numpy==1.26.4 # 必须 <2,否则 mediapipe 0.10.x import 崩溃
|
|||||||
torch==2.2.2 # 当前在 5090 上仅 CPU 可用;GPU 需 cu128(≥2.7)
|
torch==2.2.2 # 当前在 5090 上仅 CPU 可用;GPU 需 cu128(≥2.7)
|
||||||
torchvision==0.17.2
|
torchvision==0.17.2
|
||||||
|
|
||||||
|
# 接口2:C端生发(发际线预览)
|
||||||
|
# MediaPipe Tasks(FaceLandmarker) 用已装的 mediapipe;新增 SegFormer 人脸分割:
|
||||||
|
transformers==4.45.2 # SegFormer 人脸分割(jonathandinu/face-parsing,本地权重)
|
||||||
|
|
||||||
# 测试
|
# 测试
|
||||||
pytest==8.3.3
|
pytest==8.3.3
|
||||||
|
|||||||
@@ -1,4 +1,67 @@
|
|||||||
#!/bin/bash
|
#!/usr/bin/env bash
|
||||||
# worker 启动脚本:监听 0.0.0.0:8187(防火墙仅放行网关 IP)。
|
# worker 服务手动开关(接口1 四庭七眼测量)。
|
||||||
|
#
|
||||||
|
# 用法:
|
||||||
|
# ./start.sh # = start,后台启动
|
||||||
|
# ./start.sh start
|
||||||
|
# ./start.sh stop
|
||||||
|
# ./start.sh restart
|
||||||
|
# ./start.sh status
|
||||||
|
# HOST=127.0.0.1 PORT=8187 ./start.sh # 用环境变量覆盖监听地址
|
||||||
|
#
|
||||||
|
# 后台运行:日志写 worker.log,PID 写 worker.pid(均已 gitignore)。
|
||||||
|
# 开发时若想前台+热重载,用 ./run_worker.sh。
|
||||||
|
set -uo pipefail
|
||||||
cd "$(dirname "$0")"
|
cd "$(dirname "$0")"
|
||||||
exec ./venv/bin/uvicorn app:app --host 0.0.0.0 --port 8187
|
|
||||||
|
HOST="${HOST:-0.0.0.0}"
|
||||||
|
PORT="${PORT:-8187}"
|
||||||
|
PIDFILE="worker.pid"
|
||||||
|
LOGFILE="worker.log"
|
||||||
|
UVICORN="./venv/bin/uvicorn"
|
||||||
|
|
||||||
|
is_running() {
|
||||||
|
[ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
if is_running; then
|
||||||
|
echo "已在运行 (PID $(cat "$PIDFILE")),监听 ${HOST}:${PORT}"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
rm -f "$PIDFILE"
|
||||||
|
if [ ! -x "$UVICORN" ]; then
|
||||||
|
echo "找不到 $UVICORN,请先创建 venv 并安装依赖" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
nohup "$UVICORN" app:app --host "$HOST" --port "$PORT" >> "$LOGFILE" 2>&1 &
|
||||||
|
echo $! > "$PIDFILE"
|
||||||
|
echo "已启动 (PID $!),监听 ${HOST}:${PORT}"
|
||||||
|
echo "日志: tail -f $LOGFILE 就绪后 /health 返回 200"
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
if is_running; then
|
||||||
|
kill "$(cat "$PIDFILE")" && rm -f "$PIDFILE"
|
||||||
|
echo "已停止"
|
||||||
|
else
|
||||||
|
echo "未在运行"
|
||||||
|
rm -f "$PIDFILE"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
status() {
|
||||||
|
if is_running; then
|
||||||
|
echo "运行中 (PID $(cat "$PIDFILE")),监听 ${HOST}:${PORT}"
|
||||||
|
else
|
||||||
|
echo "未运行"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
case "${1:-start}" in
|
||||||
|
start) start ;;
|
||||||
|
stop) stop ;;
|
||||||
|
restart) stop; sleep 1; start ;;
|
||||||
|
status) status ;;
|
||||||
|
*) echo "用法: $0 {start|stop|restart|status}"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""标注图生成测试:RGBA 透明底 + 尺寸 + 有内容(不重叠由人工目视核验)。"""
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from conftest import fixture
|
||||||
|
|
||||||
|
from face_analysis.detector import detector
|
||||||
|
from face_analysis.measure import measure_face
|
||||||
|
from face_analysis.annotation import create_annotated_image
|
||||||
|
|
||||||
|
|
||||||
|
def test_annotation_rgba_transparent():
|
||||||
|
img = cv2.imread(fixture("frontal.jpg"))
|
||||||
|
h, w = img.shape[:2]
|
||||||
|
lms = detector.detect(img)
|
||||||
|
r = measure_face(lms, None, w, h) # 方案A,确定性
|
||||||
|
canvas = create_annotated_image(img, r)
|
||||||
|
assert canvas.mode == "RGBA"
|
||||||
|
assert canvas.size == (w, h)
|
||||||
|
arr = np.asarray(canvas)
|
||||||
|
assert (arr[:, :, 3] == 0).any() # 存在透明像素
|
||||||
|
assert (arr[:, :, 3] > 0).any() # 存在不透明像素(线/字)
|
||||||
|
|
||||||
|
|
||||||
|
def test_annotation_runs_on_hard_sample():
|
||||||
|
img = cv2.imread(fixture("hard_longhair.jpg"))
|
||||||
|
h, w = img.shape[:2]
|
||||||
|
lms = detector.detect(img)
|
||||||
|
r = measure_face(lms, None, w, h)
|
||||||
|
canvas = create_annotated_image(img, r)
|
||||||
|
assert canvas.size == (w, h)
|
||||||
+25
-1
@@ -7,8 +7,11 @@ from conftest import fixture
|
|||||||
|
|
||||||
import app as app_module
|
import app as app_module
|
||||||
|
|
||||||
|
# 测试自带固定密码,避免依赖 worker_config.json 的实际值(中间件运行期读模块全局)
|
||||||
|
app_module.ACCEPT_PASSWORDS = ["testpass"]
|
||||||
|
|
||||||
URL = "/api/v1/face/measure"
|
URL = "/api/v1/face/measure"
|
||||||
H = {"X-Internal-Token": "testpass"} # 与 worker_config.json 一致
|
H = {"X-Internal-Token": "testpass"}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
@@ -69,6 +72,27 @@ def test_corrupt_1008(client):
|
|||||||
assert r.json()["code"] == 1008
|
assert r.json()["code"] == 1008
|
||||||
|
|
||||||
|
|
||||||
|
GROW = "/api/v1/hair/grow"
|
||||||
|
|
||||||
|
|
||||||
|
def test_grow_missing_gender_1004(client):
|
||||||
|
files = {"image_file": ("frontal.jpg", open(fixture("frontal.jpg"), "rb"), "application/octet-stream")}
|
||||||
|
r = client.post(GROW, headers=H, files=files)
|
||||||
|
assert r.json()["code"] == 1004
|
||||||
|
|
||||||
|
|
||||||
|
def test_grow_female_returns_5(client):
|
||||||
|
files = {"image_file": ("frontal.jpg", open(fixture("frontal.jpg"), "rb"), "application/octet-stream")}
|
||||||
|
r = client.post(GROW, headers=H, files=files, data={"gender": "female"})
|
||||||
|
body = r.json()
|
||||||
|
assert body["code"] == 0, body
|
||||||
|
results = body["data"]["results"]
|
||||||
|
assert [x["hairline_type"] for x in results] == ["ellipse", "flower", "heart", "straight", "wave"]
|
||||||
|
assert [x["order"] for x in results] == [1, 2, 3, 4, 5]
|
||||||
|
assert base64.b64decode(results[0]["image_base64"])[:8] == b"\x89PNG\r\n\x1a\n"
|
||||||
|
assert "image_url" not in results[0]
|
||||||
|
|
||||||
|
|
||||||
def test_success_structure(client):
|
def test_success_structure(client):
|
||||||
r = _post(client, "frontal.jpg")
|
r = _post(client, "frontal.jpg")
|
||||||
body = r.json()
|
body = r.json()
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""接口2 单元测试:mesh 解析 / MP→OBJ 重排 / 性别贴图映射(不需 SegFormer)。"""
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from hairline.render import load_ext_mesh, mp_order_to_obj_order
|
||||||
|
from hairline.service import get_texture_map
|
||||||
|
from hairline import constants as C
|
||||||
|
|
||||||
|
|
||||||
|
def test_ext_mesh():
|
||||||
|
uv, ext_faces = load_ext_mesh()
|
||||||
|
assert uv.shape == (502, 2)
|
||||||
|
assert len(ext_faces) == 64 # ribbon 扩展三角形
|
||||||
|
# 扩展面至少含一个 ≥468 的顶点
|
||||||
|
assert all(max(f) >= 468 for f in ext_faces)
|
||||||
|
|
||||||
|
|
||||||
|
def test_mp_to_obj_anchor_mapping():
|
||||||
|
"""OBJ 序重排后,ribbon 引用的 obj 锚点应映射回 MP_TOP_ANCHORS。"""
|
||||||
|
pts = np.zeros((502, 3), np.float32)
|
||||||
|
pts[:468, 0] = np.arange(468) # 用 x 编码 MP 索引
|
||||||
|
obj = mp_order_to_obj_order(pts)
|
||||||
|
_uv, ext_faces = load_ext_mesh()
|
||||||
|
obj_anchor_ids = sorted({pi for f in ext_faces for pi in f if pi < 468})
|
||||||
|
mapped = sorted(int(obj[i, 0]) for i in obj_anchor_ids) # 还原成 MP 索引
|
||||||
|
assert mapped == sorted(C.MP_TOP_ANCHORS)
|
||||||
|
|
||||||
|
|
||||||
|
def test_texture_map():
|
||||||
|
m = get_texture_map()
|
||||||
|
assert [k for k, _ in m["female"]] == ["ellipse", "flower", "heart", "straight", "wave"]
|
||||||
|
assert [k for k, _ in m["male"]] == ["ellipse", "inverse_arc", "m", "straight"]
|
||||||
Reference in New Issue
Block a user