latent-image 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ """latent_image — Agent-friendly 照片开发工具包。
2
+
3
+ 分层:decode(解码)/ color(色彩域)/ operators(全局算子)/
4
+ masks(蒙版)/ pipeline(流水线)/ schema(参数)/ score(测量打分)/ cli(命令行)。
5
+ """
6
+
7
+ from .errors import LatentError
8
+
9
+ __version__ = "0.3.0"
10
+ __all__ = ["LatentError", "__version__"]
@@ -0,0 +1,5 @@
1
+ """`python -m latent_image` 入口,等价于 `latent_image` 命令。"""
2
+ from .cli import main
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
latent_image/cli.py ADDED
@@ -0,0 +1,190 @@
1
+ """latent_image 命令行入口(Agent-friendly:纯 JSON 输入输出,无交互)。
2
+
3
+ 子命令:
4
+ baseline 为原图生成中性 develop.json 参数骨架
5
+ render 按参数渲染预览/成品图
6
+ score 测量硬指标并给内部参考分,可对照基线
7
+ validate 校验参数 JSON,输出归一化结果与告警(有告警时退出码 1)
8
+ record 把本轮参数与分数追加进 develop.json 的 history
9
+ alias 创建短别名(默认 li),目标名被占用时跳过
10
+
11
+ 错误处理:`LatentError` / 文件系统错误只打印一行消息并返回退出码 2,
12
+ 不打印 traceback;未预期的异常仍然照常抛出,便于定位 bug。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from . import decode, pipeline, schema
24
+ from . import score as score_mod
25
+ from .errors import LatentError
26
+
27
+
28
+ def _fail(message: str, code: int = 2) -> int:
29
+ print(f"错误:{message}", file=sys.stderr)
30
+ return code
31
+
32
+
33
+ def _print_warnings(warnings: list[str]) -> None:
34
+ for message in warnings:
35
+ print(f"警告:{message}", file=sys.stderr)
36
+
37
+
38
+
39
+
40
+ def _cmd_baseline(args: argparse.Namespace) -> int:
41
+ src = Path(args.input)
42
+ if not src.exists():
43
+ return _fail(f"找不到文件 {src}")
44
+ doc = schema.baseline_doc(str(src), decode.sha256_of(src))
45
+ schema.write_json(args.out, doc)
46
+ print(f"已写入参数骨架:{args.out}")
47
+ return 0
48
+
49
+
50
+ def _cmd_render(args: argparse.Namespace) -> int:
51
+ warnings: list[str] = []
52
+ params = (schema.load_params(args.params, warnings=warnings)
53
+ if args.params else schema.default_params())
54
+ result = pipeline.render(args.input, params, long_edge=args.long_edge)
55
+ saved = pipeline.save_array(result["array"], args.out, depth=args.depth,
56
+ quality=args.quality)
57
+ _print_warnings(warnings)
58
+ if saved["warning"]:
59
+ _print_warnings([saved["warning"]])
60
+ width, height = result["size"]
61
+ print(f"已输出:{saved['path']} 尺寸 {width}x{height} "
62
+ f"RAW={result['is_raw']} depth={saved['depth']}-bit")
63
+ return 0
64
+
65
+
66
+ def _cmd_score(args: argparse.Namespace) -> int:
67
+ metrics = score_mod.measure_path(args.image)
68
+ report: dict[str, Any] = {"file": args.image, "metrics": metrics,
69
+ "score": score_mod.score(metrics)}
70
+ if args.baseline:
71
+ report["compare_to_baseline"] = score_mod.compare(
72
+ schema.load_json(args.baseline), report)
73
+ if args.out:
74
+ schema.write_json(args.out, report)
75
+ print(json.dumps(report, ensure_ascii=False, indent=2))
76
+ return 0
77
+
78
+
79
+ def _cmd_validate(args: argparse.Namespace) -> int:
80
+ warnings: list[str] = []
81
+ params = schema.load_params(args.params, warnings=warnings)
82
+ print(json.dumps({"ok": not warnings, "warnings": warnings, "params": params},
83
+ ensure_ascii=False, indent=2))
84
+ return 0 if not warnings else 1
85
+
86
+
87
+ def _cmd_record(args: argparse.Namespace) -> int:
88
+ doc = schema.load_json(args.doc)
89
+ warnings: list[str] = []
90
+ params = schema.load_params(args.params or args.doc, warnings=warnings)
91
+ report = schema.load_json(args.score) if args.score else None
92
+ updated = schema.record_round(doc, params, report, args.note)
93
+ schema.write_json(args.doc, updated)
94
+ _print_warnings(warnings)
95
+ entry = updated["history"][-1]
96
+ print(f"已记录第 {updated['round']} 轮:score={entry['score']} "
97
+ f"变更 {len(entry['params_delta'])} 项")
98
+ return 0
99
+
100
+
101
+ def _cmd_alias(args: argparse.Namespace) -> int:
102
+ """在可执行文件同目录创建短别名;目标名被占用时跳过。
103
+
104
+ pip 没有"装完之后"的钩子,无法在安装时按机器情况注册入口,
105
+ 所以别名做成显式子命令:装完跑一次 `latent-image alias` 即可。
106
+ """
107
+ import shutil
108
+
109
+ name = args.name
110
+ taken = shutil.which(name)
111
+ shim_dir = Path(sys.executable).parent
112
+ suffix = ".cmd" if os.name == "nt" else ""
113
+ target = shim_dir / f"{name}{suffix}"
114
+ if taken and Path(taken).resolve() != target.resolve():
115
+ print(f"别名 {name} 已被 {taken} 占用,跳过", file=sys.stderr)
116
+ return 1
117
+ if target.exists():
118
+ print(f"{target} 已存在,跳过", file=sys.stderr)
119
+ return 1
120
+
121
+ python = sys.executable
122
+ if os.name == "nt":
123
+ target = shim_dir / f"{name}.cmd"
124
+ target.write_text(f'@echo off\n"{python}" -m latent_image %*\n',
125
+ encoding="utf-8")
126
+ else:
127
+ target = shim_dir / name
128
+ target.write_text(f'#!/bin/sh\nexec "{python}" -m latent_image "$@"\n',
129
+ encoding="utf-8")
130
+ target.chmod(0o755)
131
+ print(f"已创建别名:{target}")
132
+ return 0
133
+
134
+
135
+ def build_parser() -> argparse.ArgumentParser:
136
+ ap = argparse.ArgumentParser(prog="latent-image",
137
+ description="Agent-friendly 照片开发 CLI")
138
+ sub = ap.add_subparsers(dest="command", required=True)
139
+
140
+ p_base = sub.add_parser("baseline", help="生成中性参数骨架")
141
+ p_base.add_argument("input", help="原图路径")
142
+ p_base.add_argument("--out", required=True, help="develop.json 输出路径")
143
+ p_base.set_defaults(func=_cmd_baseline)
144
+
145
+ p_render = sub.add_parser("render", help="按参数渲染图片")
146
+ p_render.add_argument("input", help="原图路径(RAW/常规格式)")
147
+ p_render.add_argument("--params", help="develop.json 参数路径(缺省用中性参数)")
148
+ p_render.add_argument("--out", required=True, help="输出图片路径")
149
+ p_render.add_argument("--long-edge", type=int, default=2048,
150
+ help="长边像素上限,解码后降采样(0 = 全尺寸,默认 2048)")
151
+ p_render.add_argument("--quality", type=int, default=85, help="JPEG 质量")
152
+ p_render.add_argument("--depth", type=int, choices=(8, 16), default=8,
153
+ help="PNG/TIFF 成品位深;JPEG 固定 8-bit")
154
+ p_render.set_defaults(func=_cmd_render)
155
+
156
+ p_score = sub.add_parser("score", help="测量硬指标并打分,可对照基线")
157
+ p_score.add_argument("image", help="预览/成品图路径")
158
+ p_score.add_argument("--baseline", help="上一轮 score 报告 JSON,用于算差值")
159
+ p_score.add_argument("--out", help="把报告 JSON 写入文件")
160
+ p_score.set_defaults(func=_cmd_score)
161
+
162
+ p_val = sub.add_parser("validate", help="校验参数 JSON 并输出归一化结果")
163
+ p_val.add_argument("params", help="develop.json 路径")
164
+ p_val.set_defaults(func=_cmd_validate)
165
+
166
+ p_rec = sub.add_parser("record", help="把本轮参数与分数记进 develop.json")
167
+ p_rec.add_argument("doc", help="develop.json 路径")
168
+ p_rec.add_argument("--params", help="本轮参数文件(缺省用 doc 里的 params)")
169
+ p_rec.add_argument("--score", help="本轮 score 报告 JSON")
170
+ p_rec.add_argument("--note", default="", help="本轮备注")
171
+ p_rec.set_defaults(func=_cmd_record)
172
+
173
+ p_alias = sub.add_parser("alias", help="创建短别名(默认 li),被占用则跳过")
174
+ p_alias.add_argument("--name", default="li", help="别名命令名(默认 li)")
175
+ p_alias.set_defaults(func=_cmd_alias)
176
+ return ap
177
+
178
+
179
+ def main(argv: list[str] | None = None) -> int:
180
+ args = build_parser().parse_args(argv)
181
+ try:
182
+ return args.func(args)
183
+ except (LatentError, OSError) as exc:
184
+ return _fail(str(exc))
185
+ except json.JSONDecodeError as exc:
186
+ return _fail(f"JSON 解析失败:{exc}")
187
+
188
+
189
+ if __name__ == "__main__":
190
+ raise SystemExit(main())
latent_image/color.py ADDED
@@ -0,0 +1,56 @@
1
+ """色彩域工具:sRGB gamma <-> 线性光、亮度、白平衡。
2
+
3
+ v1 影调算子在**线性光 RGB** 上运算,避免 gamma 域乘算带来的色偏;
4
+ 曲线与细节算子在编码前/后按需切换,见 operators.py。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+
10
+ SRGB_A = 0.055
11
+ SRGB_THRESH = 0.04045
12
+
13
+
14
+ def srgb_to_linear(x: np.ndarray) -> np.ndarray:
15
+ x = np.clip(x, 0.0, 1.0)
16
+ return np.where(x <= SRGB_THRESH, x / 12.92,
17
+ ((x + SRGB_A) / (1.0 + SRGB_A)) ** 2.4)
18
+
19
+
20
+ def linear_to_srgb(x: np.ndarray) -> np.ndarray:
21
+ x = np.clip(x, 0.0, 1.0)
22
+ return np.where(x <= 0.0031308, x * 12.92,
23
+ 1.055 * x ** (1.0 / 2.4) - SRGB_A)
24
+
25
+
26
+ def luma(rgb: np.ndarray) -> np.ndarray:
27
+ """Rec.709 相对亮度,形状 H×W。"""
28
+ return 0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]
29
+
30
+
31
+ def smoothstep(edge0: float, edge1: float, x: np.ndarray) -> np.ndarray:
32
+ """平滑选区权重;edge0 == edge1 时退化为阶跃。"""
33
+ if edge0 == edge1:
34
+ return np.where(x >= edge1, 1.0, 0.0)
35
+ t = np.clip((x - edge0) / (edge1 - edge0), 0.0, 1.0)
36
+ return t * t * (3.0 - 2.0 * t)
37
+
38
+
39
+ def white_balance(rgb: np.ndarray, temperature: float, tint: float) -> np.ndarray:
40
+ """在 linear RGB 上施加色温/色调通道乘子。
41
+
42
+ temperature > 0 偏暖(红升蓝降),< 0 偏冷;
43
+ tint > 0 偏洋红(红/蓝升绿降),< 0 偏绿。
44
+ """
45
+ if temperature == 0.0 and tint == 0.0:
46
+ return rgb
47
+ t = temperature / 100.0
48
+ ti = tint / 150.0
49
+ r_g = 1.0 + t * 0.08 + ti * 0.02
50
+ g_g = 1.0 - ti * 0.03
51
+ b_g = 1.0 - t * 0.06 + ti * 0.01
52
+ out = rgb.copy()
53
+ out[..., 0] *= r_g
54
+ out[..., 1] *= g_g
55
+ out[..., 2] *= b_g
56
+ return out
latent_image/decode.py ADDED
@@ -0,0 +1,126 @@
1
+ """解码:RAW / 常规图片 -> sRGB float32 [0,1] + 元数据。
2
+
3
+ 解码结果统一为 H×W×3、顺序 RGB、sRGB gamma 空间;方向已转正。
4
+ 本模块不做任何影调/色彩调整。
5
+
6
+ RAW 走 rawpy 的 16-bit 输出并关闭自动提亮:同一份参数在同一份 RAW 上结果可复现,
7
+ 也不会让自动提亮吃掉 14 位动态范围。常规图按 8-bit 读入(Pillow 不提供 16-bit 彩色路径),
8
+ 16-bit RGB TIFF 走 tifffile 以保住完整精度。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+ from PIL import Image, ImageOps
18
+
19
+ from .errors import LatentError
20
+
21
+ try:
22
+ import rawpy # type: ignore
23
+ HAVE_RAWPY = True
24
+ except Exception:
25
+ HAVE_RAWPY = False
26
+
27
+ RAW_EXTS = {".cr2", ".cr3", ".arw", ".nef", ".nrw", ".raf", ".orf",
28
+ ".rw2", ".pef", ".srw", ".dng", ".kdc", ".erf", ".mrw"}
29
+
30
+
31
+ def sha256_of(path: Path) -> str:
32
+ h = hashlib.sha256()
33
+ with path.open("rb") as fh:
34
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
35
+ h.update(chunk)
36
+ return h.hexdigest()
37
+
38
+
39
+ def _raw_meta(path: Path) -> dict[str, Any]:
40
+ """RAW 的 EXIF/XMP/ICC。rawpy 不暴露 EXIF,Pillow 一般也读不了 RAW,尽力而为。"""
41
+ meta: dict[str, Any] = {"exif": b"", "xmp": b"", "icc": b""}
42
+ try:
43
+ with Image.open(path) as probe:
44
+ exif_obj = probe.getexif()
45
+ meta["exif"] = exif_obj.tobytes()
46
+ meta["xmp"] = probe.info.get("xmp") or exif_obj.get(700) or b""
47
+ meta["icc"] = probe.info.get("icc_profile") or b""
48
+ except Exception:
49
+ pass
50
+ return meta
51
+
52
+
53
+ def _decode_raw(path: Path) -> tuple[np.ndarray, dict[str, Any]]:
54
+ if not HAVE_RAWPY:
55
+ raise LatentError("RAW 解码需要 rawpy:pip install 'latent_image[raw]'")
56
+ with rawpy.imread(str(path)) as raw:
57
+ rgb = raw.postprocess(
58
+ use_camera_wb=True,
59
+ output_color=rawpy.ColorSpace.sRGB,
60
+ output_bps=16,
61
+ no_auto_bright=True,
62
+ )
63
+ return rgb.astype(np.float32) / 65535.0, _raw_meta(path)
64
+
65
+
66
+ def _image_meta(path: Path) -> dict[str, Any]:
67
+ with Image.open(path) as src:
68
+ exif_obj = src.getexif()
69
+ return {
70
+ "exif": exif_obj.tobytes() or src.info.get("exif") or b"",
71
+ "xmp": src.info.get("xmp") or exif_obj.get(700) or b"",
72
+ "icc": src.info.get("icc_profile") or b"",
73
+ }
74
+
75
+
76
+ def _read_tiff16(path: Path) -> np.ndarray | None:
77
+ """16-bit RGB TIFF 走 tifffile,保住完整精度(Pillow 只给 8-bit)。"""
78
+ try:
79
+ import tifffile
80
+ except ImportError:
81
+ return None
82
+ try:
83
+ data = tifffile.imread(str(path))
84
+ except Exception:
85
+ return None
86
+ if data.dtype != np.uint16 or data.ndim != 3 or data.shape[2] < 3:
87
+ return None
88
+ return data[..., :3].astype(np.float32) / 65535.0
89
+
90
+
91
+ def _decode_image(path: Path) -> tuple[np.ndarray, dict[str, Any]]:
92
+ meta = _image_meta(path)
93
+ if path.suffix.lower() in (".tif", ".tiff"):
94
+ rgb16 = _read_tiff16(path)
95
+ if rgb16 is not None:
96
+ return rgb16, meta
97
+ with Image.open(path) as src:
98
+ img = ImageOps.exif_transpose(src)
99
+ img.load()
100
+ if img.mode in ("RGBA", "LA", "P"):
101
+ rgba = img.convert("RGBA")
102
+ bg = Image.new("RGB", rgba.size, (255, 255, 255))
103
+ bg.paste(rgba, mask=rgba.split()[-1])
104
+ img = bg
105
+ else:
106
+ img = img.convert("RGB")
107
+ return np.asarray(img, dtype=np.float32) / 255.0, meta
108
+
109
+
110
+ def open_source(path: str | Path) -> dict[str, Any]:
111
+ """返回 {rgb, meta, sha256, size, is_raw}。"""
112
+ p = Path(path)
113
+ if not p.exists():
114
+ raise LatentError(f"找不到文件:{p}")
115
+ is_raw = p.suffix.lower() in RAW_EXTS
116
+ if is_raw:
117
+ rgb, meta = _decode_raw(p)
118
+ else:
119
+ rgb, meta = _decode_image(p)
120
+ return {
121
+ "rgb": rgb,
122
+ "meta": meta,
123
+ "sha256": sha256_of(p),
124
+ "size": (rgb.shape[1], rgb.shape[0]),
125
+ "is_raw": is_raw,
126
+ }
latent_image/errors.py ADDED
@@ -0,0 +1,9 @@
1
+ """用户可修复的错误。
2
+
3
+ CLI 捕获 LatentError 后只打印消息、返回非零退出码,不打印 traceback;
4
+ 未预期的异常仍然照常抛出,便于定位 bug。
5
+ """
6
+
7
+
8
+ class LatentError(RuntimeError):
9
+ """缺少可选依赖、参数不合法、输出格式不支持等调用方可修复的问题。"""
latent_image/masks.py ADDED
@@ -0,0 +1,171 @@
1
+ """蒙版层:选区权重图 + 局部调整叠加。
2
+
3
+ ## 蒙版模型
4
+
5
+ 每个蒙版是一张 H×W 的浮点权重图 `M ∈ [0,1]`,表示该区域受调整影响的强度;
6
+ 最终像素:`out = rgb·(1−M·opacity) + adjusted·(M·opacity)`。
7
+
8
+ ### 坐标
9
+
10
+ - 全部用归一化坐标 `[left, top, right, bottom]`(0..1),相对**裁剪转正后的画面**;
11
+ - 与像素尺寸解耦,换分辨率不失效(预览代理分辨率下同样成立)。
12
+
13
+ ### 类型
14
+
15
+ | type | 选区 | 说明 |
16
+ |---|---|---|
17
+ | `rect` | 轴对齐矩形 | 区域内全选,边缘按 feather 渐变 |
18
+ | `ellipse` | 区域内接椭圆 | 径向渐变,feather 控制边缘柔化 |
19
+ | `luma` | 亮度选区 | 按画面亮度区间软选;`region` 可再限定范围 |
20
+ | `brush` | 画笔点列 | 多点按半径距离衰减取并集(最大权重) |
21
+ | `color` | 色相范围 | `hue`/`width` 选色相,`sat_lo`/`sat_hi` 门控饱和度 |
22
+
23
+ ### 字段
24
+
25
+ - `feather`:0..1,边缘过渡宽度,相对选区尺寸;0 为硬边。
26
+ - `opacity`:0..1,蒙版整体强度。
27
+ - `invert`:反转选区。
28
+ - `adjustment`:仅作用于蒙版内的算子子集(见 `schema.MASK_ADJUSTMENTS`);
29
+ 留空则蒙版只起选区作用。
30
+
31
+ ### 叠加顺序
32
+
33
+ `masks` 数组顺序即应用顺序;后一个蒙版在前一个的结果上继续叠加。
34
+ 重叠区域的强度按各自 `opacity` 累积,不做选区互斥。
35
+ """
36
+ from __future__ import annotations
37
+
38
+ import numpy as np
39
+
40
+ from . import operators
41
+ from .color import luma, smoothstep
42
+ from .schema import MASK_ADJUSTMENTS
43
+
44
+ _ADJUSTMENT_OPS = {
45
+ "exposure": operators.exposure,
46
+ "contrast": operators.contrast,
47
+ "shadows": operators.shadows,
48
+ "highlights": operators.highlights,
49
+ "saturation": operators.saturation,
50
+ }
51
+
52
+
53
+ def _grid(h: int, w: int) -> tuple[np.ndarray, np.ndarray]:
54
+ nx = np.linspace(0.0, 1.0, w, dtype=np.float32)[None, :].repeat(h, axis=0)
55
+ ny = np.linspace(0.0, 1.0, h, dtype=np.float32)[:, None].repeat(w, axis=1)
56
+ return nx, ny
57
+
58
+
59
+ def _rect_mask(h: int, w: int, region: list[float], feather: float) -> np.ndarray:
60
+ l, t, r, b = region
61
+ nx, ny = _grid(h, w)
62
+ inside = (nx >= l) & (nx <= r) & (ny >= t) & (ny <= b)
63
+ if feather <= 0.0:
64
+ return inside.astype(np.float32)
65
+ bw = max(r - l, 1e-6)
66
+ bh = max(b - t, 1e-6)
67
+ band = feather * min(bw, bh)
68
+ dx = np.minimum(nx - l, r - nx)
69
+ dy = np.minimum(ny - t, b - ny)
70
+ margin = np.minimum(dx, dy)
71
+ soft = np.clip(margin / band, 0.0, 1.0)
72
+ return (inside * soft).astype(np.float32)
73
+
74
+
75
+ def _ellipse_mask(h: int, w: int, region: list[float], feather: float) -> np.ndarray:
76
+ l, t, r, b = region
77
+ cx, cy = (l + r) / 2.0, (t + b) / 2.0
78
+ rx, ry = max((r - l) / 2.0, 1e-6), max((b - t) / 2.0, 1e-6)
79
+ nx, ny = _grid(h, w)
80
+ d = ((nx - cx) / rx) ** 2 + ((ny - cy) / ry) ** 2
81
+ if feather <= 0.0:
82
+ return (d <= 1.0).astype(np.float32)
83
+ band = max(feather, 1e-3)
84
+ return np.clip((1.0 - d) / band, 0.0, 1.0).astype(np.float32)
85
+
86
+
87
+ def _luma_mask(rgb: np.ndarray, region: list[float],
88
+ lo: float, hi: float) -> np.ndarray:
89
+ h, w = rgb.shape[:2]
90
+ mask = smoothstep(lo, hi, luma(rgb))
91
+ l, t, r, b = region
92
+ nx, ny = _grid(h, w)
93
+ bounds = (nx >= l) & (nx <= r) & (ny >= t) & (ny <= b)
94
+ return (mask * bounds).astype(np.float32)
95
+
96
+
97
+ def _brush_mask(h: int, w: int, points: list, radius: float,
98
+ feather: float) -> np.ndarray:
99
+ """画笔点列:每个归一化点按半径距离衰减,多点取并集(最大权重)。"""
100
+ nx, ny = _grid(h, w)
101
+ acc = np.zeros((h, w), dtype=np.float32)
102
+ radius = max(radius, 1e-3)
103
+ for pt in points or []:
104
+ if not isinstance(pt, (list, tuple)) or len(pt) < 2:
105
+ continue
106
+ x, y = float(pt[0]), float(pt[1])
107
+ d = np.sqrt((nx - x) ** 2 + (ny - y) ** 2)
108
+ wpt = np.clip(1.0 - d / radius, 0.0, 1.0)
109
+ if feather > 0.0:
110
+ wpt = wpt ** (1.0 + feather * 2.0)
111
+ acc = np.maximum(acc, wpt)
112
+ return acc
113
+
114
+
115
+ def _color_mask(rgb: np.ndarray, region: list[float], hue: float, width: float,
116
+ sat_lo: float, sat_hi: float) -> np.ndarray:
117
+ """色相范围选区:按环形色相差加权,可再用饱和度区间门控。"""
118
+ h, w = rgb.shape[:2]
119
+ hh, ss, _ = operators.rgb_to_hsv(rgb)
120
+ d = np.abs(((hh - hue + 180.0) % 360.0) - 180.0)
121
+ half = max(width / 2.0, 1e-3)
122
+ weight = np.clip(1.0 - d / half, 0.0, 1.0)
123
+ weight *= ((ss >= sat_lo) & (ss <= sat_hi)).astype(np.float32)
124
+ l, t, r, b = region
125
+ nx, ny = _grid(h, w)
126
+ bounds = (nx >= l) & (nx <= r) & (ny >= t) & (ny <= b)
127
+ return (weight * bounds).astype(np.float32)
128
+
129
+
130
+ def build_mask(rgb: np.ndarray, spec: dict) -> np.ndarray:
131
+ h, w = rgb.shape[:2]
132
+ mtype = spec.get("type", "rect")
133
+ region = spec.get("region") or [0.0, 0.0, 1.0, 1.0]
134
+ feather = float(spec.get("feather", 0.2))
135
+
136
+ if mtype == "ellipse":
137
+ mask = _ellipse_mask(h, w, region, feather)
138
+ elif mtype == "luma":
139
+ mask = _luma_mask(rgb, region, float(spec.get("lo", 0.25)),
140
+ float(spec.get("hi", 0.75)))
141
+ elif mtype == "brush":
142
+ mask = _brush_mask(h, w, spec.get("points", []),
143
+ float(spec.get("radius", 0.1)), feather)
144
+ elif mtype == "color":
145
+ mask = _color_mask(rgb, region, float(spec.get("hue", 0.0)),
146
+ float(spec.get("width", 40.0)),
147
+ float(spec.get("sat_lo", 0.0)),
148
+ float(spec.get("sat_hi", 1.0)))
149
+ else:
150
+ mask = _rect_mask(h, w, region, feather)
151
+
152
+ if spec.get("invert", False):
153
+ mask = 1.0 - mask
154
+ opacity = float(spec.get("opacity", 1.0))
155
+ return np.clip(mask * opacity, 0.0, 1.0).astype(np.float32)
156
+
157
+
158
+ def _apply_adjustment(rgb: np.ndarray, adj: dict) -> np.ndarray:
159
+ out = rgb
160
+ for name in MASK_ADJUSTMENTS:
161
+ value = float(adj.get(name, 0.0))
162
+ if value:
163
+ out = _ADJUSTMENT_OPS[name](out, value)
164
+ return out
165
+
166
+
167
+ def apply_masked(rgb: np.ndarray, spec: dict) -> np.ndarray:
168
+ """对单个蒙版套用其局部调整,返回合成后的图。"""
169
+ mask = build_mask(rgb, spec)[..., None]
170
+ adjusted = _apply_adjustment(rgb, spec.get("adjustment", {}))
171
+ return rgb * (1.0 - mask) + adjusted * mask