Author SHA1 Message Date
xsl 688472706d save 2026-08-04 22:37:14 +08:00
xsl a3e13c804a save code 2026-08-04 22:37:04 +08:00
xsl a2243266db save 2026-08-04 22:37:04 +08:00
xslandCursor fe0e74ece8 feat: 接口1/6 标注层字号上调一档 + 眉心改用 9 号点定位
- annotation: 自适应字号系数 0.017→0.020(下限 8→9),标注文字更大更清晰
- measure: _brow_center 只取 FaceMesh 9 号点(眉间上点),不再与 151 取中点

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 23:03:33 +08:00
xsl 52913c94fc fix: 删除 MeasureResult.__init__ 中重复的七眼厘米赋值块 2026-07-27 23:17:22 +08:00
xsl 13526cb5b8 feat: 接口1/5/6 发际线弃用逻辑(顶庭<0.7cm)
发际线离头顶<0.7cm时判定分割不可靠,弃用发际线:
顶/上庭字段置null、face_total只算中下庭、标注图保留头顶线去掉发际线、
只标中/下庭。eye1/7竖向范围改用眉心。
2026-07-27 23:10:54 +08:00
60 changed files with 395 additions and 97 deletions
+194 -30
View File
@@ -401,21 +401,36 @@ def _run_face_measure_data(image, variant="v1"):
logger.warning("头发/耳朵分割失败,回退方案A%s", seg_e) logger.warning("头发/耳朵分割失败,回退方案A%s", seg_e)
result = measure_face(landmarks, hair_mask, w, h, head_pose=head_pose) result = measure_face(landmarks, hair_mask, w, h, head_pose=head_pose)
discarded = result.hairline_discarded
data = result.to_response() data = result.to_response()
vd = result.vertical
if variant == "v6": if variant == "v6":
vd = result.vertical if discarded:
base_px = vd["upper_court_px"] + vd["middle_court_px"] + vd["lower_court_px"] # 发际线弃用:接口6 的上庭也依赖发际线,一并置 null;只保留中/下庭。
# 接口6 是三庭:去掉顶庭相关字段(top_court_cm / ratios.top_court / landmarks.hair_top base_px = vd["middle_court_px"] + vd["lower_court_px"]
data["four_courts"]["ratios"] = { data["four_courts"]["upper_court_cm"] = None
"upper_court": round(vd["upper_court_px"] / base_px, 3), data["four_courts"]["ratios"] = {
"middle_court": round(vd["middle_court_px"] / base_px, 3), "upper_court": None,
"lower_court": round(vd["lower_court_px"] / base_px, 3), "middle_court": round(vd["middle_court_px"] / base_px, 3),
} "lower_court": round(vd["lower_court_px"] / base_px, 3),
data["four_courts"].pop("top_court_cm", None) }
data["face_total_height_cm"] = round( data["four_courts"].pop("top_court_cm", None)
result.upper_cm + result.middle_cm + result.lower_cm, 2) data["face_total_height_cm"] = round(
# 注:landmarks.hair_top 保留返回(供前端/下游定位头顶),但顶庭数值、 result.middle_cm + result.lower_cm, 2)
# 占比、标注图仍按三庭处理,显示效果不变。 data["landmarks"]["hairline"] = None
else:
base_px = vd["upper_court_px"] + vd["middle_court_px"] + vd["lower_court_px"]
# 接口6 是三庭:去掉顶庭相关字段(top_court_cm / ratios.top_court / landmarks.hair_top
data["four_courts"]["ratios"] = {
"upper_court": round(vd["upper_court_px"] / base_px, 3),
"middle_court": round(vd["middle_court_px"] / base_px, 3),
"lower_court": round(vd["lower_court_px"] / base_px, 3),
}
data["four_courts"].pop("top_court_cm", None)
data["face_total_height_cm"] = round(
result.upper_cm + result.middle_cm + result.lower_cm, 2)
# 注:landmarks.hair_top 保留返回(供前端/下游定位头顶),但顶庭数值、
# 占比、标注图仍按三庭处理,显示效果不变。
# 七眼段宽度(cm)。eye1=左耳外段 eye2=左脸颊 eye3=左眼 eye4=两眼间距 eye5=右眼 eye6=右脸颊 eye7=右耳外段。 # 七眼段宽度(cm)。eye1=左耳外段 eye2=左脸颊 eye3=左眼 eye4=两眼间距 eye5=右眼 eye6=右脸颊 eye7=右耳外段。
# eye2~eye6(5段)只用内部分点,接口1/6 共用;eye1/eye7 需耳朵分割端线,仅接口1 有。 # eye2~eye6(5段)只用内部分点,接口1/6 共用;eye1/eye7 需耳朵分割端线,仅接口1 有。
@@ -430,11 +445,14 @@ def _run_face_measure_data(image, variant="v1"):
data["seven_eyes"][f"eye{i + 2}"] = ( data["seven_eyes"][f"eye{i + 2}"] = (
None if (a is None or b is None) else round((b - a) / pc, 2)) None if (a is None or b is None) else round((b - a) / pc, 2))
if variant != "v6": if variant != "v6":
# 接口1 额外算 eye1/eye7(左/右耳外段),需耳朵分割端线 # 接口1 额外算 eye1/eye7(左/右耳外段),需耳朵分割端线
# 竖向范围:发际线弃用时用眉心做上界(hair_top 不可靠),否则用头顶。
from face_analysis.annotation import _ear_edges_from_mask from face_analysis.annotation import _ear_edges_from_mask
top_y = (vd["brow_center"][1] if discarded
else vd["hair_top"][1])
head_l, head_r = _ear_edges_from_mask( head_l, head_r = _ear_edges_from_mask(
ear_mask, hair_mask, ear_mask, hair_mask,
result.vertical["hair_top"][1], result.vertical["chin_tip"][1], top_y, vd["chin_tip"][1],
lcx, rcx, (lcx + rcx) / 2) lcx, rcx, (lcx + rcx) / 2)
data["seven_eyes"]["eye1"] = ( data["seven_eyes"]["eye1"] = (
None if (head_l is None) else round((lcx - head_l) / pc, 2)) None if (head_l is None) else round((lcx - head_l) / pc, 2))
@@ -696,10 +714,11 @@ async def face_measure_v2(
- 发际线类型 `hairline_type`(英文 key - 发际线类型 `hairline_type`(英文 key
- 顺序 `order`(本期固定 `1..N`,不排序) - 顺序 `order`(本期固定 `1..N`,不排序)
> **female 走「换发型」模式**:生发图 `grown_image_base64` 由换发型(change_hair > **female 走「换发型」模式**1..5 的生发图 `grown_image_base64` 由换发型(change_hair
> + Flux-2 整帧重绘(= 接口12 final 管线,整帧美颜+整帧重绘)生成,其余参数用固化默认值。 > + Flux-2 整帧重绘(= 接口12 final 管线,整帧美颜+整帧重绘)生成,其余参数用固化默认值。
> **male 走原生发(ComfyUI add_hair)管线**。入参与返回结构不变。 > **6/7bigflower/clasicalflower)与 male 一样走原生发(ComfyUI add_hair)管线**。
> female 依赖 change_hair 与 ComfyUI(:8188) 均在跑 > **male 全部走原生发(ComfyUI add_hair)管线**。入参与返回结构不变
> female 1..5 依赖 change_hair 与 ComfyUI(:8188) 均在跑。
{_image_fields_desc} {_image_fields_desc}
@@ -707,15 +726,15 @@ async def face_measure_v2(
--- ---
- **gender**(必填):`male` / `female`。决定返回的贴图集合(female 5 张 / male 4 张)。 - **gender**(必填):`male` / `female`。决定返回的贴图集合(female 7 张 / male 6 张)。
非法或缺失返回 `1004`。 非法或缺失返回 `1004`。
- **hair_style**(必填):发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数量。 - **hair_style**(必填):发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数量。
`female`1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave `female`1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave, 6=bigflower, 7=clasicalflower
`male`1=ellipse, 2=inverse_arc, 3=m, 4=straight。越界/非法返回 `1007`。 `male`1=ellipse, 2=inverse_arc, 3=m, 4=straight, 5=heart, 6=Softpetal。越界/非法返回 `1007`。
- **beauty_enabled**:本期保留但不生效。 - **beauty_enabled**:本期保留但不生效。
`hairline_type` 取值:`ellipse` / `flower` / `heart` / `straight` / `wave`female), `hairline_type` 取值:`ellipse` / `flower` / `heart` / `straight` / `wave` / `bigflower` / `clasicalflower`female),
`ellipse` / `m` / `straight` / `inverse_arc`male)。 `ellipse` / `m` / `straight` / `inverse_arc` / `heart` / `Softpetal`male)。
""", """,
responses={ responses={
200: { 200: {
@@ -754,7 +773,7 @@ async def hair_grow(
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, 前缀)"),
gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"), gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"),
hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填),如 1,2,3。female:1-5 male:1-4"), hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填),如 1,2,3。female:1-7 male:1-6"),
beauty_enabled: bool = Form(default=False, description="是否开启美颜(本期不生效)"), beauty_enabled: bool = Form(default=False, description="是否开启美颜(本期不生效)"),
use_mask: bool = Form(default=True, description="是否启用 inpaint 遮罩(测试对比用)。false 时用干净原图生成(空遮罩,不烧模板线)"), use_mask: bool = Form(default=True, description="是否启用 inpaint 遮罩(测试对比用)。false 时用干净原图生成(空遮罩,不烧模板线)"),
prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词,会替换工作流节点60的文本"), prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词,会替换工作流节点60的文本"),
@@ -764,7 +783,7 @@ async def hair_grow(
return err(1004, "gender 必填且只能为 male / female") return err(1004, "gender 必填且只能为 male / female")
# 2. hair_style 必填校验(解析逗号分隔,越界 → 1007) # 2. hair_style 必填校验(解析逗号分隔,越界 → 1007)
max_styles = {"female": 5, "male": 4}[gender] max_styles = {"female": 7, "male": 6}[gender]
hair_styles = _parse_hair_styles(hair_style, max_styles) hair_styles = _parse_hair_styles(hair_style, max_styles)
if hair_styles is None: if hair_styles is None:
return err(1007, f"hair_style 必填且为 1..{max_styles} 的整数(逗号分隔),收到 {hair_style!r}") return err(1007, f"hair_style 必填且为 1..{max_styles} 的整数(逗号分隔),收到 {hair_style!r}")
@@ -786,7 +805,8 @@ async def hair_grow(
if gender == "female": if gender == "female":
from hairline.service import generate_grow_results_swap from hairline.service import generate_grow_results_swap
items = await run_in_threadpool( items = await run_in_threadpool(
generate_grow_results_swap, image, hair_styles, _V2_FINAL_DEFAULTS) generate_grow_results_swap, image, hair_styles, _V2_FINAL_DEFAULTS,
prompt=prompt)
else: else:
from hairline.service import generate_grow_results from hairline.service import generate_grow_results
items = await run_in_threadpool( items = await run_in_threadpool(
@@ -809,6 +829,149 @@ async def hair_grow(
return err(1007, f"处理失败:{ex}") return err(1007, f"处理失败:{ex}")
# ---------------------------------------------------------------------------
# 调试接口:接口2 女性生发 分步计时
# ---------------------------------------------------------------------------
@app.post(
"/api/v1/debug/grow-timing",
summary="调试-接口2女性生发分步计时",
tags=["调试"],
include_in_schema=False,
)
async def debug_grow_timing(
image_file: Optional[UploadFile] = File(default=None),
image_url: Optional[str] = Form(default=None),
image_base64: Optional[str] = Form(default=None),
hair_style: str = Form(default="2", description="发型序号(花瓣=2),逗号分隔多选"),
webui_steps: Optional[int] = Form(default=None, description="swapHair webui img2img 采样步数,None=服务端默认(15),可填10/15/20/25对比"),
redraw_max_side: Optional[int] = Form(default=None, description="ComfyUI重绘分辨率(长边像素)。None=默认8960=原图不缩;其他如640/768/1024"),
redraw_prompt: Optional[str] = Form(default=None, description="ComfyUI重绘提示词,None=默认'填充遮罩区域的头发'"),
):
"""单图跑接口2女性生发,返回每个步骤的耗时 + 结果图,用于定位性能瓶颈。
步骤拆分:
1. extract_context:人脸关键点检测 + 头发分割 + 发际线几何
2. [每个发型] generate_hairline_redraw
2a. compute_mask:发际线遮罩计算
2b. _call_swap:调 change_hair 换发型(内含 webui SD1.5 推理,远程或本机)
2c. _composite:接缝融合(多频段/羽化)
3. [每个发型] _call_local_redraw:调本机 ComfyUI 用 Flux.2 重绘
"""
import time as _time
from fastapi.concurrency import run_in_threadpool
raw, e = await resolve_image_bytes(image_file, image_url, image_base64)
if e is not None:
return e
image = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR)
if image is None:
return err(1008, "图片格式不支持(仅 JPG / PNG)")
try:
max_styles = 7
hair_styles = _parse_hair_styles(hair_style, max_styles)
if hair_styles is None:
return err(1007, f"hair_style 必须为 1..{max_styles}")
t_total0 = _time.perf_counter()
timings = {"total_ms": 0, "extract_context_ms": 0, "per_hairstyle": []}
# 步骤1: extract_context
t0 = _time.perf_counter()
from hairline.service import extract_context as _ec, _call_local_redraw, _REDRAW_MAX_SIDE # noqa
from face_analysis.hairline_grow import generate_hairline_redraw, NoFaceError # noqa
from face_analysis.head_mask import SEGFORMER_HAIR # noqa
ctx = await run_in_threadpool(_ec, image)
timings["extract_context_ms"] = int((_time.perf_counter() - t0) * 1000)
if ctx is None:
return err(1001, "无法识别人像")
hair_mask_reuse = (ctx["parse_map"] == SEGFORMER_HAIR)
h, w = image.shape[:2]
eff_side = _REDRAW_MAX_SIDE if redraw_max_side is None else redraw_max_side
redraw_img, hair_mask_redraw = image, hair_mask_reuse
downscale_info = None
if eff_side > 0 and max(h, w) > eff_side:
from hairline.service import _downscale_max_side
redraw_img, _rs = _downscale_max_side(image, eff_side)
_nh, _nw = redraw_img.shape[:2]
if hair_mask_redraw is not None:
hair_mask_redraw = cv2.resize(hair_mask_reuse.astype(np.uint8), (_nw, _nh),
interpolation=cv2.INTER_NEAREST).astype(bool)
downscale_info = {"from": f"{w}x{h}", "to": f"{_nw}x{_nh}", "max_side": eff_side}
textures_map = None
from hairline.service import get_texture_map, _FEMALE_KEY_TO_CHANG, load_texture_rgba, build_overlay_layer, load_ext_mesh
textures = get_texture_map()["female"]
items = [(s, textures[s - 1]) for s in hair_styles]
for order, (key, white_path) in items:
hs_t0 = _time.perf_counter()
entry = {"hairline_type": key, "order": order}
chang_id = _FEMALE_KEY_TO_CHANG.get(key)
entry["chang_id"] = chang_id
entry["ok"] = False
entry["error"] = None
entry["grown_b64"] = None
if chang_id is None:
entry["error"] = f"无对应 chang_id"
timings["per_hairstyle"].append(entry)
continue
try:
# 2a/2b/2c: generate_hairline_redraw (内部含 mask+swap+blend)
t0 = _time.perf_counter()
data = await run_in_threadpool(
generate_hairline_redraw, redraw_img, chang_id,
hair_mask=hair_mask_redraw, webui_steps=webui_steps, **_V2_FINAL_DEFAULTS)
t_redraw_pipeline = _time.perf_counter() - t0
_tm = data.get("timings_ms") or {}
entry["mask_ms"] = _tm.get("mask", 0)
entry["swap_ms"] = _tm.get("swap", 0)
entry["blend_ms"] = _tm.get("blend", 0)
entry["redraw_pipeline_ms"] = int(t_redraw_pipeline * 1000)
steps = data.get("steps") or {}
final_b64 = steps.get("final_base64") or ""
mask_b64 = steps.get("redraw_band_mask_base64") or ""
if not final_b64 or not mask_b64:
entry["error"] = f"final/遮罩缺失(final={len(final_b64)} mask={len(mask_b64)})"
timings["per_hairstyle"].append(entry)
continue
if final_b64.startswith("data:"):
final_b64 = final_b64.split(",", 1)[1]
if mask_b64.startswith("data:"):
mask_b64 = mask_b64.split(",", 1)[1]
# 3: ComfyUI 重绘
t0 = _time.perf_counter()
# max_side: 0 或 None 都让 _call_local_redraw 用默认逻辑(外层已控制分辨率)
_ms = redraw_max_side if redraw_max_side is not None and redraw_max_side > 0 else None
grown_png = await run_in_threadpool(
_call_local_redraw,
base64.b64decode(final_b64), base64.b64decode(mask_b64),
max_side=_ms, prompt=redraw_prompt)
entry["comfyui_redraw_ms"] = int((_time.perf_counter() - t0) * 1000)
if grown_png:
entry["grown_b64"] = "data:image/jpeg;base64," + _png_to_jpg_b64(grown_png)
entry["ok"] = True
else:
entry["error"] = "ComfyUI 重绘返回空"
except NoFaceError:
entry["error"] = "未检出人脸"
except Exception as ex: # noqa: BLE001
entry["error"] = str(ex)[:150]
entry["hairstyle_total_ms"] = int((_time.perf_counter() - hs_t0) * 1000)
timings["per_hairstyle"].append(entry)
timings["total_ms"] = int((_time.perf_counter() - t_total0) * 1000)
timings["downscale"] = downscale_info
timings["image_size"] = f"{w}x{h}"
return ok(timings)
except Exception as ex: # noqa: BLE001
logger.exception("debug/grow-timing 异常")
return err(1007, f"处理失败:{ex}")
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 接口 7:C 端生发 v2 —— 已弃用(add_hair2.json 用 Klein-9b 大模型,会把常驻的 # 接口 7:C 端生发 v2 —— 已弃用(add_hair2.json 用 Klein-9b 大模型,会把常驻的
# Klein-4b/Flux 挤出显存,导致接口2/3/5 耗时抖动;且业务已不再调用)。 # Klein-4b/Flux 挤出显存,导致接口2/3/5 耗时抖动;且业务已不再调用)。
@@ -994,9 +1157,10 @@ async def face_features(
--- ---
**入参**(同接口2:先选性别,再多选发型): **入参**(同接口2:先选性别,再多选发型):
- 必填 `gender``male`/`female`),决定发型集合(female 5 / male 4)。 - 必填 `gender``male`/`female`),决定发型集合(female 7 / male 6)。
- 必填 `hair_style`(发型序号,逗号分隔如 `1,2,3`),决定返回哪些发际线类型。缺失/越界/非法返回 `1007`。 - 必填 `hair_style`(发型序号,逗号分隔如 `1,2,3`),决定返回哪些发际线类型。缺失/越界/非法返回 `1007`。
`female`1=ellipse,2=flower,3=heart,4=straight,5=wave`male`1=ellipse,2=inverse_arc,3=m,4=straight。 `female`1=ellipse,2=flower,3=heart,4=straight,5=wave,6=bigflower,7=clasicalflower
`male`1=ellipse,2=inverse_arc,3=m,4=straight,5=heart,6=Softpetal。
- 可选 `use_mask` / `prompt`:同接口2 的生发控制参数。 - 可选 `use_mask` / `prompt`:同接口2 的生发控制参数。
注:生发黑模板固定取 `hairline_texture_black/`middle 档),即三档叠图分别用各自贴图、但生发目标固定 middle。 注:生发黑模板固定取 `hairline_texture_black/`middle 档),即三档叠图分别用各自贴图、但生发目标固定 middle。
- 可选 `generate_grow_image`(默认 `true`):是否生成生发效果图(ComfyUI 生发,全流程最耗时)。 - 可选 `generate_grow_image`(默认 `true`):是否生成生发效果图(ComfyUI 生发,全流程最耗时)。
@@ -1076,7 +1240,7 @@ async def hairline_generate(
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, 前缀)"),
gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"), gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"),
hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填,如 1,2,3)。female:1-5 male:1-4"), hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填,如 1,2,3)。female:1-7 male:1-6"),
use_mask: bool = Form(default=True, description="生发是否启用 inpaint 遮罩(同接口2,测试对比用)"), use_mask: bool = Form(default=True, description="生发是否启用 inpaint 遮罩(同接口2,测试对比用)"),
prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词(同接口2),会替换工作流节点60的文本"), prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词(同接口2),会替换工作流节点60的文本"),
generate_grow_image: bool = Form(default=True, description="是否生成生发效果图(ComfyUI 生发,最耗时)。默认 true 出图;false 时跳过生发,各发型 grown_image 恒为 null,仅返回三档发际线叠图与中心点"), generate_grow_image: bool = Form(default=True, description="是否生成生发效果图(ComfyUI 生发,最耗时)。默认 true 出图;false 时跳过生发,各发型 grown_image 恒为 null,仅返回三档发际线叠图与中心点"),
@@ -1085,7 +1249,7 @@ async def hairline_generate(
return err(1004, "gender 必填且只能为 male / female") return err(1004, "gender 必填且只能为 male / female")
# hair_style 必填(同接口2):解析逗号分隔,缺失/越界/非法 → 1007 # hair_style 必填(同接口2):解析逗号分隔,缺失/越界/非法 → 1007
max_styles = {"female": 5, "male": 4}[gender] max_styles = {"female": 7, "male": 6}[gender]
hair_styles = _parse_hair_styles(hair_style, max_styles) hair_styles = _parse_hair_styles(hair_style, max_styles)
if hair_styles is None: if hair_styles is None:
return err(1007, f"hair_style 必填且为 1..{max_styles} 的整数(逗号分隔),收到 {hair_style!r}") return err(1007, f"hair_style 必填且为 1..{max_styles} 的整数(逗号分隔),收到 {hair_style!r}")
+1 -1
View File
@@ -68,7 +68,7 @@
`face_ext.obj` 的 UV 把发际线贴图渲染到额头(预览)。生发:黑贴图渲染遮罩 → 调本机 **ComfyUI 8182** `face_ext.obj` 的 UV 把发际线贴图渲染到额头(预览)。生发:黑贴图渲染遮罩 → 调本机 **ComfyUI 8182**
`add_hair.json`(Flux-2) 出图。**关键坑**obj 是重排序,需 `INDEX_MAP_468` 把 MP 序→OBJ 序。 `add_hair.json`(Flux-2) 出图。**关键坑**obj 是重排序,需 `INDEX_MAP_468` 把 MP 序→OBJ 序。
返回 `results[].image_base64` + `grown_image_base64` 返回 `results[].image_base64` + `grown_image_base64`
- `hair_style` 映射:female 1=ellipse 2=flower 3=heart 4=straight 5=wavemale 1=ellipse 2=inverse_arc 3=m 4=straight。 - `hair_style` 映射:female 1=ellipse 2=flower 3=heart 4=straight 5=wave 6=bigflower 7=clasicalflowermale 1=ellipse 2=inverse_arc 3=m 4=straight 5=heart 6=Softpetal。female 1..5 走「换发型(change_hair)」+Flux-2 重绘管线;female 6/7 与 male 全部走原生发(ComfyUI add_hair)管线
### 接口7 C端生发 v2 `/api/v1/hair/grow-v2`worker)—— 接口2同款,add_hair2 工作流 ### 接口7 C端生发 v2 `/api/v1/hair/grow-v2`worker)—— 接口2同款,add_hair2 工作流
- **做什么**:与接口 2 完全一致(正面照 + `gender` + `hair_style` 逗号分隔多选 → N 组预览+生发图)。 - **做什么**:与接口 2 完全一致(正面照 + `gender` + `hair_style` 逗号分隔多选 → N 组预览+生发图)。
+5 -5
View File
@@ -265,7 +265,7 @@
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
|------|------|------|------| |------|------|------|------|
| gender | string | **是** | 性别:`male` / `female`。决定使用的发际线贴图集合 | | gender | string | **是** | 性别:`male` / `female`。决定使用的发际线贴图集合 |
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数。female1=ellipse, 2=flower, 3=heart, 4=straight, 5=wavemale1=ellipse, 2=inverse_arc, 3=m, 4=straight。越界/非法返回 `1007` | | hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数。female1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave, 6=bigflower, 7=clasicalflowermale1=ellipse, 2=inverse_arc, 3=m, 4=straight, 5=heart, 6=Softpetal。越界/非法返回 `1007` |
| beauty_enabled | bool | 否 | 生发图是否带美颜效果,默认 false(当前阶段不生效) | | beauty_enabled | bool | 否 | 生发图是否带美颜效果,默认 false(当前阶段不生效) |
| use_mask | bool | 否 | 是否启用 inpaint 遮罩,默认 `true``false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比 | | use_mask | bool | 否 | 是否启用 inpaint 遮罩,默认 `true``false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比 |
| prompt | string | 否 | ComfyUI 提示词,默认「补充遮罩区域的头发,加一点美颜」,会替换工作流节点 60 的文本 | | prompt | string | 否 | ComfyUI 提示词,默认「补充遮罩区域的头发,加一点美颜」,会替换工作流节点 60 的文本 |
@@ -278,7 +278,7 @@
|------|------|------| |------|------|------|
| image_url | string | 发际线曲线**透明 PNG** URL(仅白色发际线曲线,透明底,**不含人物**,需前端叠加原图显示) | | image_url | string | 发际线曲线**透明 PNG** URL(仅白色发际线曲线,透明底,**不含人物**,需前端叠加原图显示) |
| grown_image_url | string | **生发后图片** URLComfyUI/Flux「植发 3 个月」效果图,完整人像照片) | | grown_image_url | string | **生发后图片** URLComfyUI/Flux「植发 3 个月」效果图,完整人像照片) |
| hairline_type | string | 发际线类型 key`ellipse`/`flower`/`heart`/`straight`/`wave`female),`ellipse`/`m`/`straight`/`inverse_arc`male | | hairline_type | string | 发际线类型 key`ellipse`/`flower`/`heart`/`straight`/`wave`/`bigflower`/`clasicalflower`female),`ellipse`/`m`/`straight`/`inverse_arc`/`heart`/`Softpetal`male |
| order | int | 排序序号(当前阶段固定 `1..N`,按贴图顺序,暂不计算合适度) | | order | int | 排序序号(当前阶段固定 `1..N`,按贴图顺序,暂不计算合适度) |
> ⚠️ 生发图由本机 ComfyUIFlux-2,端口 8182)生成,**一次请求生成指定发型的 1 张、同步返回**。 > ⚠️ 生发图由本机 ComfyUIFlux-2,端口 8182)生成,**一次请求生成指定发型的 1 张、同步返回**。
@@ -405,8 +405,8 @@
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
|------|------|------|------| |------|------|------|------|
| gender | string | **是** | 性别:`male` / `female`。决定发型集合(female 5 / male 4)。缺失/非法返回 `1004` | | gender | string | **是** | 性别:`male` / `female`。决定发型集合(female 7 / male 6)。缺失/非法返回 `1004` |
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),决定返回哪些发际线类型。female1=ellipse, 2=flower, 3=heart, 4=straight, 5=wavemale1=ellipse, 2=inverse_arc, 3=m, 4=straight。缺失/越界/非法返回 `1007` | | hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),决定返回哪些发际线类型。female1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave, 6=bigflower, 7=clasicalflowermale1=ellipse, 2=inverse_arc, 3=m, 4=straight, 5=heart, 6=Softpetal。缺失/越界/非法返回 `1007` |
| use_mask | bool | 否 | 生发是否启用 inpaint 遮罩,默认 `true``false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比 | | use_mask | bool | 否 | 生发是否启用 inpaint 遮罩,默认 `true``false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比 |
| prompt | string | 否 | ComfyUI 提示词,默认「补充遮罩区域的头发,加一点美颜」,会替换工作流节点 60 的文本 | | prompt | string | 否 | ComfyUI 提示词,默认「补充遮罩区域的头发,加一点美颜」,会替换工作流节点 60 的文本 |
| generate_grow_image | bool | 否 | 是否生成生发效果图(ComfyUI 生发,全流程最耗时),默认 `true`。传 `false` 时跳过生发,各发型 `grown_image_*` 恒为 `null`,仅返回三档发际线叠图与中心点,可大幅降低耗时 | | generate_grow_image | bool | 否 | 是否生成生发效果图(ComfyUI 生发,全流程最耗时),默认 `true`。传 `false` 时跳过生发,各发型 `grown_image_*` 恒为 `null`,仅返回三档发际线叠图与中心点,可大幅降低耗时 |
@@ -427,7 +427,7 @@
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
|------|------|------| |------|------|------|
| hairline_type | string | 发际线类型 key`ellipse`/`flower`/`heart`/`straight`/`wave`female),`ellipse`/`m`/`straight`/`inverse_arc`male | | hairline_type | string | 发际线类型 key`ellipse`/`flower`/`heart`/`straight`/`wave`/`bigflower`/`clasicalflower`female),`ellipse`/`m`/`straight`/`inverse_arc`/`heart`/`Softpetal`male |
| image_middle_url | string | middle 档发际线曲线**透明 PNG** URL(仅曲线,透明底,**不含人物**,需叠加原图显示) | | image_middle_url | string | middle 档发际线曲线**透明 PNG** URL(仅曲线,透明底,**不含人物**,需叠加原图显示) |
| image_high_url | string | high 档发际线曲线**透明 PNG** URL(同上,high 档曲线) | | image_high_url | string | high 档发际线曲线**透明 PNG** URL(同上,high 档曲线) |
| image_low_url | string | low 档发际线曲线**透明 PNG** URL(同上,low 档曲线) | | image_low_url | string | low 档发际线曲线**透明 PNG** URL(同上,low 档曲线) |
+30 -5
View File
@@ -202,7 +202,7 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
# --- 自适应尺寸:字号/线宽/虚线/箭头按短边缩放 --- # --- 自适应尺寸:字号/线宽/虚线/箭头按短边缩放 ---
s = min(w, h) s = min(w, h)
font_size = max(8, round(s * 0.017)) # 字体更小 font_size = max(9, round(s * 0.020)) # 字号上调一档
line_w = max(1, round(s * 0.0022)) line_w = max(1, round(s * 0.0022))
dash_len = max(4, round(s * 0.008)) dash_len = max(4, round(s * 0.008))
gap_len = max(2, round(dash_len * 0.7)) # 虚线更稠密(间隙<划线) gap_len = max(2, round(dash_len * 0.7)) # 虚线更稠密(间隙<划线)
@@ -212,7 +212,11 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
buf = np.zeros((h, w, 4), dtype=np.uint8) buf = np.zeros((h, w, 4), dtype=np.uint8)
if variant == "v6": # 发际线弃用(hairline_discarded):保留头顶横线,去掉发际线横线,
# 也不标顶/上庭(缺发际线作边界,算不出)。横线 = 头顶/眉心/鼻翼下缘/下巴尖。
if getattr(measure_result, "hairline_discarded", False):
order = ["hair_top", "brow_center", "nose_bottom", "chin_tip"]
elif variant == "v6":
order = ["hairline", "brow_center", "nose_bottom", "chin_tip"] order = ["hairline", "brow_center", "nose_bottom", "chin_tip"]
else: else:
order = ["hair_top", "hairline", "brow_center", "nose_bottom", "chin_tip"] order = ["hair_top", "hairline", "brow_center", "nose_bottom", "chin_tip"]
@@ -239,7 +243,7 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
face_cx = (fx0 + fx1) / 2 face_cx = (fx0 + fx1) / 2
over = max(6, round(s * 0.030)) # 线超出包围盒的长度(参考图风格) over = max(6, round(s * 0.030)) # 线超出包围盒的长度(参考图风格)
face_half = (fx1 - fx0) / 2 + over # 横线超出最外侧竖线一点 face_half = (fx1 - fx0) / 2 + over # 横线超出最外侧竖线一点
# v6 竖线纵向范围 = 发际线→下巴尖(不超出);v1 = 头顶→下巴尖并两端超出一点 # 竖线纵向范围v6 = 发际线→下巴尖(不超出);v1(含发际线弃用)= 头顶→下巴尖并两端超出一点
v_top = fy0 if variant == "v6" else fy0 - over v_top = fy0 if variant == "v6" else fy0 - over
v_bot = fy1 if variant == "v6" else fy1 + over v_bot = fy1 if variant == "v6" else fy1 + over
@@ -255,6 +259,18 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
draw = ImageDraw.Draw(canvas) draw = ImageDraw.Draw(canvas)
font = _load_font(font_size) font = _load_font(font_size)
# --- 2b. 每条横线在「中间线段」(两内眼角之间)中点画原点突出 ---
# 注意:原点不在整条线的中点 face_cx,而在被竖线切出的中间段(左内眼角↔右内眼角)
# 的正中,即脸的竖直中轴附近、两内眼角连线中点。
li_x = pts["left_inner"][0]
ri_x = pts["right_inner"][0]
dot_cx = (li_x + ri_x) / 2
dot_r = max(2, round(s * 0.0045)) # 原点半径,与 arrow_size 同档自适应
for cy in ys:
x0, y0 = dot_cx - dot_r, cy - dot_r
x1, y1 = dot_cx + dot_r, cy + dot_r
draw.ellipse((x0, y0, x1, y1), fill=LINE_COLOR)
# --- 3a. 横线右侧:线名(头顶/发际线/眉心/鼻翼下缘/下巴尖),文字纵向居中对齐到线 --- # --- 3a. 横线右侧:线名(头顶/发际线/眉心/鼻翼下缘/下巴尖),文字纵向居中对齐到线 ---
name_x = fx1 + over + pad # 移到横线右端外侧一点(往右) name_x = fx1 + over + pad # 移到横线右端外侧一点(往右)
for i, name in enumerate(order): for i, name in enumerate(order):
@@ -265,19 +281,28 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
draw.text((x, ys[i]), text, fill=LINE_COLOR, font=font, anchor="lm") draw.text((x, ys[i]), text, fill=LINE_COLOR, font=font, anchor="lm")
# --- 3b. 左侧四庭:名 + 数值两行(无 cm)+ 竖向虚线双箭头 --- # --- 3b. 左侧四庭:名 + 数值两行(无 cm)+ 竖向虚线双箭头 ---
if variant == "v6": # court_start:庭段在 order 里的起始索引。发际线弃用时 order 首位是头顶(无下界发际线,
# 顶/上庭不标),中庭从眉心开始 → 跳过 order[0]。
if getattr(measure_result, "hairline_discarded", False):
court_cm = [measure_result.middle_cm, measure_result.lower_cm]
court_name = ["中庭", "下庭"]
n_court = 2
court_start = 1
elif variant == "v6":
court_cm = [measure_result.upper_cm, measure_result.middle_cm, measure_result.lower_cm] court_cm = [measure_result.upper_cm, measure_result.middle_cm, measure_result.lower_cm]
court_name = ["上庭", "中庭", "下庭"] court_name = ["上庭", "中庭", "下庭"]
n_court = 3 n_court = 3
court_start = 0
else: else:
court_cm = [measure_result.top_cm, measure_result.upper_cm, court_cm = [measure_result.top_cm, measure_result.upper_cm,
measure_result.middle_cm, measure_result.lower_cm] measure_result.middle_cm, measure_result.lower_cm]
court_name = ["顶庭", "上庭", "中庭", "下庭"] court_name = ["顶庭", "上庭", "中庭", "下庭"]
n_court = 4 n_court = 4
court_start = 0
arrow_x = max(arrow_size + 1, fx0 - pad) # 竖箭头所在 x(脸左侧,贴近最左竖线) arrow_x = max(arrow_size + 1, fx0 - pad) # 竖箭头所在 x(脸左侧,贴近最左竖线)
court_total = sum(court_cm) or 1.0 # 各庭占比分母 = 四庭(v6 三庭)之和 court_total = sum(court_cm) or 1.0 # 各庭占比分母 = 四庭(v6 三庭)之和
for i in range(n_court): for i in range(n_court):
y_a, y_b = ys[i], ys[i + 1] y_a, y_b = ys[court_start + i], ys[court_start + i + 1]
# 竖向虚线双箭头,覆盖该庭高度(略收一点避免压到横线) # 竖向虚线双箭头,覆盖该庭高度(略收一点避免压到横线)
inset = min(arrow_size, (y_b - y_a) * 0.12) inset = min(arrow_size, (y_b - y_a) * 0.12)
draw_dashed_line_with_arrows( draw_dashed_line_with_arrows(
+93 -44
View File
@@ -12,7 +12,7 @@ from face_analysis.calibration import (
estimate_scale_factor, normalized_to_pixel, pixel_distance, _lm_list, estimate_scale_factor, normalized_to_pixel, pixel_distance, _lm_list,
) )
from face_analysis.face_mesh_landmarks import ( from face_analysis.face_mesh_landmarks import (
GLABELLA_9, GLABELLA_151, NOSE_BOTTOM, CHIN_TIP, GLABELLA_9, NOSE_BOTTOM, CHIN_TIP,
LEFT_EYE_OUTER, LEFT_EYE_INNER, RIGHT_EYE_INNER, RIGHT_EYE_OUTER, LEFT_EYE_OUTER, LEFT_EYE_INNER, RIGHT_EYE_INNER, RIGHT_EYE_OUTER,
LEFT_CHEEK, RIGHT_CHEEK, LEFT_POSITION, RIGHT_POSITION, LEFT_CHEEK, RIGHT_CHEEK, LEFT_POSITION, RIGHT_POSITION,
) )
@@ -24,10 +24,8 @@ _TOP_RATIO = 0.22 / 0.28 # 顶庭 ÷ 中庭(≈ 0.786)
def _brow_center(lm, w, h): def _brow_center(lm, w, h):
"""眉心 = 索引 9 / 151 中点""" """眉心 = 索引 9(眉间上点)"""
g9 = normalized_to_pixel(lm[GLABELLA_9], w, h) return normalized_to_pixel(lm[GLABELLA_9], w, h)
g151 = normalized_to_pixel(lm[GLABELLA_151], w, h)
return (g9[0] + g151[0]) / 2, (g9[1] + g151[1]) / 2
def estimate_vertical_landmarks(landmarks, image_width, image_height): def estimate_vertical_landmarks(landmarks, image_width, image_height):
@@ -144,9 +142,22 @@ def measure_seven_eyes(landmarks, image_width, image_height):
} }
def pt_or_none(vertical, name):
"""vertical dict 的点 → {"x","y"},值为 None 时返回 None。"""
v = vertical.get(name)
if v is None:
return None
return {"x": int(round(v[0])), "y": int(round(v[1]))}
class MeasureResult: class MeasureResult:
"""测量结果,提供 to_response() 输出与接口文档同构的 data 字段。""" """测量结果,提供 to_response() 输出与接口文档同构的 data 字段。"""
# 发际线弃用阈值:发际线离头顶(顶庭)< 此值时判定分割不可靠,弃用发际线。
# hairline 与 hair_top 几乎重合(如稀疏头发中轴漏检只剩一小撮),说明发际线
# 定位无意义 → 顶/上庭置 null、标注图不画头顶/发际线。
HAIRLINE_DISCARD_TOP_CM = 0.7
def __init__(self, vertical, eyes, px_per_cm, hairline_source, head_pose, def __init__(self, vertical, eyes, px_per_cm, hairline_source, head_pose,
landmarks=None, image_width=None, image_height=None): landmarks=None, image_width=None, image_height=None):
self.vertical = vertical self.vertical = vertical
@@ -164,7 +175,14 @@ class MeasureResult:
self.upper_cm = vertical["upper_court_px"] / px_per_cm self.upper_cm = vertical["upper_court_px"] / px_per_cm
self.middle_cm = vertical["middle_court_px"] / px_per_cm self.middle_cm = vertical["middle_court_px"] / px_per_cm
self.lower_cm = vertical["lower_court_px"] / px_per_cm self.lower_cm = vertical["lower_court_px"] / px_per_cm
self.face_total_cm = self.top_cm + self.upper_cm + self.middle_cm + self.lower_cm # 发际线弃用判定:顶庭(头顶→发际线)过小视为发际线贴近头顶、不可靠。
# 弃用时 hairline_source 改为 "discarded"face_total 只算中庭+下庭。
self.hairline_discarded = self.top_cm < self.HAIRLINE_DISCARD_TOP_CM
if self.hairline_discarded:
self.hairline_source = "discarded"
self.face_total_cm = self.middle_cm + self.lower_cm
else:
self.face_total_cm = self.top_cm + self.upper_cm + self.middle_cm + self.lower_cm
# 七眼厘米 # 七眼厘米
self.eye_width_cm = eyes["eye_width_px"] / px_per_cm self.eye_width_cm = eyes["eye_width_px"] / px_per_cm
@@ -172,46 +190,77 @@ class MeasureResult:
self.inter_eye_cm = eyes["inter_eye_distance_px"] / px_per_cm self.inter_eye_cm = eyes["inter_eye_distance_px"] / px_per_cm
def to_response(self): def to_response(self):
total_px = (self.vertical["top_court_px"] + self.vertical["upper_court_px"] # 发际线弃用:顶/上庭相关字段置 null(保留键),ratio 分母只算中下庭;
+ self.vertical["middle_court_px"] + self.vertical["lower_court_px"]) # landmarks.hair_top/hairline 置 null。否则按四庭正常输出。
fw_px = self.eyes["face_width_px"] if self.hairline_discarded:
base_px = (self.vertical["middle_court_px"] + self.vertical["lower_court_px"])
def pt(name): data = {
x, y = self.vertical[name] "face_total_height_cm": round(self.face_total_cm, 2),
return {"x": int(round(x)), "y": int(round(y))} "four_courts": {
"top_court_cm": None,
data = { "upper_court_cm": None,
"face_total_height_cm": round(self.face_total_cm, 2), "middle_court_cm": round(self.middle_cm, 2),
"four_courts": { "lower_court_cm": round(self.lower_cm, 2),
"top_court_cm": round(self.top_cm, 2), "ratios": {
"upper_court_cm": round(self.upper_cm, 2), "top_court": None,
"middle_court_cm": round(self.middle_cm, 2), "upper_court": None,
"lower_court_cm": round(self.lower_cm, 2), "middle_court": round(self.vertical["middle_court_px"] / base_px, 3),
"ratios": { "lower_court": round(self.vertical["lower_court_px"] / base_px, 3),
"top_court": round(self.vertical["top_court_px"] / total_px, 3), },
"upper_court": round(self.vertical["upper_court_px"] / total_px, 3),
"middle_court": round(self.vertical["middle_court_px"] / total_px, 3),
"lower_court": round(self.vertical["lower_court_px"] / total_px, 3),
}, },
}, "seven_eyes": {
"seven_eyes": { "eye_width_cm": round(self.eye_width_cm, 2),
"eye_width_cm": round(self.eye_width_cm, 2), "face_width_cm": round(self.face_width_cm, 2),
"face_width_cm": round(self.face_width_cm, 2), "inter_eye_distance_cm": round(self.inter_eye_cm, 2),
"inter_eye_distance_cm": round(self.inter_eye_cm, 2), "ratios": {
"ratios": { "eye_width": round(self.eyes["eye_width_px"] / self.eyes["face_width_px"], 3),
"eye_width": round(self.eyes["eye_width_px"] / fw_px, 3), "inter_eye_distance": round(self.eyes["inter_eye_distance_px"] / self.eyes["face_width_px"], 3),
"inter_eye_distance": round(self.eyes["inter_eye_distance_px"] / fw_px, 3), },
}, },
}, "landmarks": {
"landmarks": { "hair_top": None,
"hair_top": pt("hair_top"), "hairline": None,
"hairline": pt("hairline"), "brow_center": pt_or_none(self.vertical, "brow_center"),
"brow_center": pt("brow_center"), "nose_bottom": pt_or_none(self.vertical, "nose_bottom"),
"nose_bottom": pt("nose_bottom"), "chin_tip": pt_or_none(self.vertical, "chin_tip"),
"chin_tip": pt("chin_tip"), },
}, "hairline_source": self.hairline_source,
"hairline_source": self.hairline_source, }
} else:
total_px = (self.vertical["top_court_px"] + self.vertical["upper_court_px"]
+ self.vertical["middle_court_px"] + self.vertical["lower_court_px"])
data = {
"face_total_height_cm": round(self.face_total_cm, 2),
"four_courts": {
"top_court_cm": round(self.top_cm, 2),
"upper_court_cm": round(self.upper_cm, 2),
"middle_court_cm": round(self.middle_cm, 2),
"lower_court_cm": round(self.lower_cm, 2),
"ratios": {
"top_court": round(self.vertical["top_court_px"] / total_px, 3),
"upper_court": round(self.vertical["upper_court_px"] / total_px, 3),
"middle_court": round(self.vertical["middle_court_px"] / total_px, 3),
"lower_court": round(self.vertical["lower_court_px"] / total_px, 3),
},
},
"seven_eyes": {
"eye_width_cm": round(self.eye_width_cm, 2),
"face_width_cm": round(self.face_width_cm, 2),
"inter_eye_distance_cm": round(self.inter_eye_cm, 2),
"ratios": {
"eye_width": round(self.eyes["eye_width_px"] / self.eyes["face_width_px"], 3),
"inter_eye_distance": round(self.eyes["inter_eye_distance_px"] / self.eyes["face_width_px"], 3),
},
},
"landmarks": {
"hair_top": pt_or_none(self.vertical, "hair_top"),
"hairline": pt_or_none(self.vertical, "hairline"),
"brow_center": pt_or_none(self.vertical, "brow_center"),
"nose_bottom": pt_or_none(self.vertical, "nose_bottom"),
"chin_tip": pt_or_none(self.vertical, "chin_tip"),
},
"hairline_source": self.hairline_source,
}
# left/right_positionmediapipe 21/251 号定位点(原图像素,与 landmarks 同坐标系)。 # left/right_positionmediapipe 21/251 号定位点(原图像素,与 landmarks 同坐标系)。
# landmarks 缺省(如测试直构 MeasureResult)时不输出,保持向后兼容。 # landmarks 缺省(如测试直构 MeasureResult)时不输出,保持向后兼容。
if self.landmarks is not None and self.w and self.h: if self.landmarks is not None and self.w and self.h:
+63 -11
View File
@@ -29,7 +29,8 @@ import logging
logger = logging.getLogger("hair.worker") logger = logging.getLogger("hair.worker")
# 接口2 女性发型 key → change_hair hair_idchang_*)映射:换发型+Flux-2 整帧重绘用。 # 接口2 女性发型 key → change_hair hair_idchang_*)映射:换发型+Flux-2 整帧重绘用。
# 与接口12 final 的 5 型一一对应。 # 与接口12 final 的 5 型一一对应。female 6/7bigflower/clasicalflower)无对应 LoRA
# 走与男性一致的原生生发(ComfyUI add_hair)管线,故不在本表。
_FEMALE_KEY_TO_CHANG = { _FEMALE_KEY_TO_CHANG = {
"ellipse": "chang_tuoyuan", # 椭圆 "ellipse": "chang_tuoyuan", # 椭圆
"flower": "chang_huaban", # 花瓣 "flower": "chang_huaban", # 花瓣
@@ -38,6 +39,16 @@ _FEMALE_KEY_TO_CHANG = {
"wave": "chang_bolang", # 波浪 "wave": "chang_bolang", # 波浪
} }
# 发际线贴图显式顺序表:决定 hair_style 序号(1-indexed)。
# 不再依赖文件名字母序——字母序会因新增/重命名文件而错位,破坏现有前端/客户端取值。
# key 须与 _gender_key 派生结果一致(已去空格):如 "inverse_arc"(源 man_ inverse_arc.png)、
# "Softpetal"(源 man_Soft petal.png,大写 S 保留)。表外未知 key 兜底排到末尾。
_HAIRSTYLE_ORDER = {
"female": ["ellipse", "flower", "heart", "straight", "wave",
"bigflower", "clasicalflower"], # 1..7
"male": ["ellipse", "inverse_arc", "m", "straight", "heart", "Softpetal"], # 1..6
}
_REPO = os.path.dirname(os.path.dirname(__file__)) _REPO = os.path.dirname(os.path.dirname(__file__))
_TEXTURE_DIR = os.path.join(_REPO, "hairline_texture") _TEXTURE_DIR = os.path.join(_REPO, "hairline_texture")
_BLACK_TEXTURE_DIR = os.path.join(_REPO, "hairline_texture_black") _BLACK_TEXTURE_DIR = os.path.join(_REPO, "hairline_texture_black")
@@ -123,10 +134,13 @@ def _gender_key(stem: str):
def get_texture_map(level: str = "middle") -> dict: def get_texture_map(level: str = "middle") -> dict:
"""扫描指定档位贴图目录建 {gender: [(key, path)]},按 key 排序、按档位缓存。 """扫描指定档位贴图目录建 {gender: [(key, path)]},按显式顺序表排序、按档位缓存。
levelmiddle(默认) / high / low,分别对应 hairline_texture[/_high|/_low]。 levelmiddle(默认) / high / low,分别对应 hairline_texture[/_high|/_low]。
文件名规范化去空格(如 `man_ inverse_arc.png` → key `inverse_arc`)。 文件名规范化去空格(如 `man_ inverse_arc.png` → key `inverse_arc`)。
排序依据 _HAIRSTYLE_ORDER:表内 key 按表序、表外未知 key 兜底排到末尾(再按字母序),
保证新增/重命名文件不会打乱现有 hair_style 序号。
""" """
if level not in _TEXTURE_DIRS: if level not in _TEXTURE_DIRS:
raise ValueError(f"hairline_level 必须是 middle/high/low,收到 {level!r}") raise ValueError(f"hairline_level 必须是 middle/high/low,收到 {level!r}")
@@ -140,7 +154,9 @@ def get_texture_map(level: str = "middle") -> dict:
if gender: if gender:
mapping[gender].append((key, path)) mapping[gender].append((key, path))
for g in mapping: for g in mapping:
mapping[g].sort(key=lambda kp: kp[0]) order = _HAIRSTYLE_ORDER.get(g, [])
idx = {k: i for i, k in enumerate(order)}
mapping[g].sort(key=lambda kp: (idx.get(kp[0], len(idx)), kp[0]))
_texture_maps[level] = mapping _texture_maps[level] = mapping
return mapping return mapping
@@ -203,7 +219,7 @@ def generate_grow_results(image_bgr: np.ndarray, gender: str, use_mask: bool = T
workflow_path: str | None = None): workflow_path: str | None = None):
"""指定发际线类型:发际线透明叠图(白线 RGBA) + 生发图(ComfyUI)。 """指定发际线类型:发际线透明叠图(白线 RGBA) + 生发图(ComfyUI)。
hair_styles1-indexed 列表):指定生成哪几张发际线(按贴图排序)。female: 1..5male: 1..4 hair_styles1-indexed 列表):指定生成哪几张发际线(按贴图排序)。female: 1..7male: 1..6
为 None 时生成全部(兼容旧调用)。 为 None 时生成全部(兼容旧调用)。
use_mask(默认 True):是否启用 inpaint 遮罩,用于测试对比(同接口3)。 use_mask(默认 True):是否启用 inpaint 遮罩,用于测试对比(同接口3)。
False 时用**干净原图 + 空遮罩**送 ComfyUI(不烧黑色模板线)。 False 时用**干净原图 + 空遮罩**送 ComfyUI(不烧黑色模板线)。
@@ -273,15 +289,22 @@ def generate_grow_results(image_bgr: np.ndarray, gender: str, use_mask: bool = T
def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | None, def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | None,
redraw_defaults: dict): redraw_defaults: dict,
"""接口2 女性专用:发际线透明叠图(同 generate_grow_results+ 换发型重绘图。 redraw_max_side: int | None = None,
unet_name: str | None = None,
prompt: str | None = None):
"""接口2 女性专用:发际线透明叠图(同 generate_grow_results+ 生发图。
grown 图来源(新流程):对每个选中发型把 female key 映射到 change_hair 的 chang_* hair_id 生发图来源按发型分两路:
调 face_analysis.hairline_grow.generate_hairline_redraw= 接口12 final 管线,参数用 - 换发型(chang_* 表内,1..5):female key → change_hair 的 chang_* hair_id,调
redraw_defaults)拿到 ④ final(接缝融合基底)+ ⑤-② 纯红遮罩 PNG,再**后端直接调 face_analysis.hairline_grow.generate_hairline_redraw= 接口12 final 管线,参数用
ComfyUI**0716add-hair-api.json 工作流)完成发际线带重绘,重绘结果作为生发图。 redraw_defaults)拿到 ④ final(接缝融合基底)+ ⑤-② 纯红遮罩 PNG,再**后端直接调
ComfyUI**0716add-hair-api.json 工作流)完成发际线带重绘。
- 原生生发(表外,6/7 bigflower/clasicalflower 等):无对应 change_hair LoRA,改走与男性
一致的原生生发(ComfyUI add_hair),由 _grow_native_one 完成(黑模板 + inpaint 遮罩)。
overlay 仍是发际线曲线透明层(与 generate_grow_results 完全一致)。 overlay 仍是发际线曲线透明层(与 generate_grow_results 完全一致)。
prompt 仅用于原生生发分支(换发型分支的提示词由 redraw 流程内部固定)。
Returns: list[dict] {"hairline_type","order","overlay","grown_png"(jpg bytes 或 None)} Returns: list[dict] {"hairline_type","order","overlay","grown_png"(jpg bytes 或 None)}
无人脸返回 None。单个发型换发型/重绘失败时 grown_png=None,不抛异常。 无人脸返回 None。单个发型换发型/重绘失败时 grown_png=None,不抛异常。
""" """
@@ -325,7 +348,10 @@ def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | N
grown_png = None grown_png = None
chang_id = _FEMALE_KEY_TO_CHANG.get(key) chang_id = _FEMALE_KEY_TO_CHANG.get(key)
if chang_id is None: if chang_id is None:
logger.warning("接口2 换发型:female key=%s 无对应 chang_id,跳过生发图", key) # 无对应 change_hair LoRA(如 bigflower/clasicalflower)→ 走与男性一致的原生生发
logger.info("接口2 女 key=%s 无 chang_id,走原生生发(ComfyUI add_hair)", key)
grown_png = _grow_native_one(image_bgr, ctx, white_path,
prompt=prompt, unet_name=unet_name)
else: else:
try: try:
import time as _t import time as _t
@@ -394,6 +420,32 @@ def _grow_from_texture(image_bgr: np.ndarray, ctx: dict, white_path: str | None,
return None return None
def _grow_native_one(image_bgr: np.ndarray, ctx: dict, white_path: str,
prompt: str | None = None, unet_name: str | None = None):
"""对单个发际线做原生生发(ComfyUI add_hair),与男性 generate_grow_results 一致。
接口2 女性新发型(bigflower/clasicalflower 等)无对应 change_hair LoRA,改走此路径:
黑模板 → build_inpaint_mask → 限边(_prep_comfy_input)→ comfyui.run(front=True)。
失败返回 None,不抛异常。结果按限边前原图尺寸放大回原尺寸(仅展示对齐)。
"""
try:
h, w = image_bgr.shape[:2]
black = load_texture_rgba(_black_texture_path(white_path))
marked, mask = build_inpaint_mask(
image_bgr, ctx["landmarks"], ctx["parse_map"], ctx["points"], black)
m_s, msk_s, gsc = _prep_comfy_input(marked, mask)
buf = io.BytesIO()
compose_comfy_rgba(m_s, msk_s).save(buf, format="PNG", compress_level=1)
# front=True:接口2 时延敏感,插到 ComfyUI 队列最前
grown_png = comfyui.run(buf.getvalue(), prompt=prompt, front=True, unet_name=unet_name)
if gsc < 1.0 and grown_png:
grown_png = _upscale_png_to(grown_png, w, h)
return grown_png
except Exception as e: # noqa: BLE001 单张失败不拖垮整请求
logger.warning("接口2 女原生生发图失败:%s", e)
return None
def generate_hairline_pngs(image_bgr: np.ndarray, gender: str, def generate_hairline_pngs(image_bgr: np.ndarray, gender: str,
hair_styles: list[int], use_mask: bool = True, hair_styles: list[int], use_mask: bool = True,
prompt: str | None = None, prompt: str | None = None,
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

+4
View File
@@ -237,12 +237,16 @@ const HAIR_STYLES = {
{ value:'3', label:'heart 心形' }, { value:'3', label:'heart 心形' },
{ value:'4', label:'straight 直线形' }, { value:'4', label:'straight 直线形' },
{ value:'5', label:'wave 波浪形' }, { value:'5', label:'wave 波浪形' },
{ value:'6', label:'bigflower 大花瓣型' },
{ value:'7', label:'clasicalflower 古典花瓣型' },
], ],
male: [ male: [
{ value:'1', label:'ellipse 椭圆形' }, { value:'1', label:'ellipse 椭圆形' },
{ value:'2', label:'inverse_arc 倒弧形' }, { value:'2', label:'inverse_arc 倒弧形' },
{ value:'3', label:'m M形' }, { value:'3', label:'m M形' },
{ value:'4', label:'straight 直线形' }, { value:'4', label:'straight 直线形' },
{ value:'5', label:'heart 桃心形' },
{ value:'6', label:'Softpetal 柔和花瓣形' },
] ]
}; };
+5 -1
View File
@@ -101,7 +101,7 @@
<div class="file-input"><input type="file" id="imageFile" accept="image/jpeg,image/png,.jpg,.jpeg,.png"></div> <div class="file-input"><input type="file" id="imageFile" accept="image/jpeg,image/png,.jpg,.jpeg,.png"></div>
<div class="form-group"> <div class="form-group">
<label>性别</label> <label>性别</label>
<select id="gender" onchange="onGenderChange()"><option value="female" selected>👩 Female5种)</option><option value="male">👨 Male4种)</option></select> <select id="gender" onchange="onGenderChange()"><option value="female" selected>👩 Female7种)</option><option value="male">👨 Male6种)</option></select>
</div> </div>
<div class="form-group" style="align-items:flex-start"> <div class="form-group" style="align-items:flex-start">
<label style="padding-top:3px">发型 *</label> <label style="padding-top:3px">发型 *</label>
@@ -174,12 +174,16 @@ const HAIR_STYLES = {
{ value:'3', label:'3. heart 心形' }, { value:'3', label:'3. heart 心形' },
{ value:'4', label:'4. straight 直线' }, { value:'4', label:'4. straight 直线' },
{ value:'5', label:'5. wave 波浪' }, { value:'5', label:'5. wave 波浪' },
{ value:'6', label:'6. bigflower 大花瓣型' },
{ value:'7', label:'7. clasicalflower 古典花瓣型' },
], ],
male: [ male: [
{ value:'1', label:'1. ellipse 椭圆' }, { value:'1', label:'1. ellipse 椭圆' },
{ value:'2', label:'2. inverse_arc 倒弧' }, { value:'2', label:'2. inverse_arc 倒弧' },
{ value:'3', label:'3. m M形' }, { value:'3', label:'3. m M形' },
{ value:'4', label:'4. straight 直线' }, { value:'4', label:'4. straight 直线' },
{ value:'5', label:'5. heart 桃心形' },
{ value:'6', label:'6. Softpetal 柔和花瓣形' },
] ]
}; };