feat: DCP to DCP LUT and HALD conversion tool

This commit is contained in:
zhoubinjia committed 2026-11-16 13:50:01 +08:00
1 parent b1bfdb99e5
commit ddc9ea19ac
8 files changed
+903

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.20)
project(photon_dcp_lut LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(SDK "${CMAKE_CURRENT_SOURCE_DIR}/../../app/src/main/cpp/dcp/dng_sdk/source")
file(GLOB SDK_SOURCES CONFIGURE_DEPENDS "${SDK}/*.cpp")
list(FILTER SDK_SOURCES EXCLUDE REGEX "/dng_(validate|jxl)\\.cpp$")
find_package(ZLIB REQUIRED)
find_package(Threads REQUIRED)
add_library(photon_dcp SHARED sdk_bridge.cpp ${SDK_SOURCES})
target_include_directories(photon_dcp PRIVATE "${SDK}" "${SDK}/../../XMPStub/include")
target_compile_definitions(photon_dcp PRIVATE
qDNGUseStdInt=1 qDNGReportErrors=1 qDNGXMPFiles=0 qDNGXMPDocOps=0
qDNGUseLibJPEG=0 qDNGValidate=0 qDNGValidateTarget=0 qDNGThreadSafe=0
PHOTON_ENABLE_DNG_JXL=0)
if(APPLE)
target_compile_definitions(photon_dcp PRIVATE qMacOS=1)
target_link_libraries(photon_dcp PRIVATE "-framework CoreServices")
elseif(UNIX)
target_compile_definitions(photon_dcp PRIVATE qLinux=1)
else()
message(FATAL_ERROR "This host tool currently requires macOS or Linux")
endif()
target_link_libraries(photon_dcp PRIVATE ZLIB::ZLIB Threads::Threads)
+137
View File
@@ -0,0 +1,137 @@
# DCP → DCP HALD / LUT 工具
桌面命令行工具,固定 D50,用源 DCP 的逆变换接目标 DCP 的正向变换。
输入是 **sRGB 编码的 HALD PNG**;输出为 16 位 sRGB HALD PNG、浮点 `.cube`、JSON 诊断报告。
## 使用
需要 macOS / Linux、C++17 编译器、CMake、zlib 开发库和 `uv`。macOS 可使用 Xcode Command Line Tools。
在仓库根目录执行,Python 依赖由 `uv` 管理;第一次转换会自动编译桌面 SDK 动态库到本目录的 `build/`。
这些命令应按仓库要求在沙箱外运行,不需要 Android Gradle 构建或安装 App。
生成恒等 HALD(已有 HALD 可跳过):
```bash
uv run tools/dcp_lut/dcp_lut.py --language zh identity \
--level 8 --output /tmp/identity-hald.png
```
转换示例:
```bash
uv run tools/dcp_lut/dcp_lut.py --language zh convert \
--source "app/src/main/assets/dcp/Google Pixel 10 Pro XL Wide Camera Adobe Standard.dcp" \
--target "app/src/main/assets/dcp/RICOH GR IV Camera Positive Film.dcp" \
--hald /tmp/identity-hald.png \
--output-prefix /tmp/pixel-to-ricoh-positive
```
生成:
- `/tmp/pixel-to-ricoh-positive.hald.png`:16 位 RGB PNG,写入 sRGB 色彩标记。
- `/tmp/pixel-to-ricoh-positive.cube`:RGB 浮点数据,红色索引变化最快,精度不经过 PNG 量化。
- `/tmp/pixel-to-ricoh-positive.json`:输入文件 SHA-256、D50 矩阵、曲线来源、各阶段逆解残差、色域裁切计数。
查看某个 DCP 的 D50 参数:
```bash
uv run tools/dcp_lut/dcp_lut.py --language zh inspect \
"app/src/main/assets/dcp/Leica M8 Camera Standard.dcp"
```
`--language en` / `--language zh` 放在子命令前。用户帮助和状态消息集中在 `messages.json`;底层 SDK / 文件系统错误保留原始诊断。
默认保护已有输出,可用 `--overwrite` 明确替换;输出始终不能与任一输入路径相同。
## 色彩处理约定
参考 App 的 `RawDemosaicProcessor.kt`、`AdobeCurveToneAlgorithm.kt`、`DcpHueSatMapGl.kt`,
并直接调用仓库内的 Adobe DNG SDK 1.7.1,而不是从零实现 DCP 标签解析或近似插值。
正向链:
```text
白平衡归一化 camera RGB
→ D50 camera-to-PCS → 线性 ProPhoto RGB D50
→ HueSatMap
→ ProfileBaselineExposureOffset 的 exposure ramp
→ LookTable
→ Adobe RGB tone curve(内置 spline,缺省 ACR3;包含负曝光 tone)
→ PCS D50 → 线性 sRGB D65
→ sRGB 编码
```
工具实际组合的链:
```text
HALD sRGB
→ 解 sRGB
→ 线性 sRGB D65 → PCS D50 → 线性 ProPhoto RGB D50
→ 逆 Adobe RGB tone
→ 逆 LookTable
→ 逆 exposure ramp
→ 逆 HueSatMap
→ 逆源 D50 色彩矩阵
→ 目标 D50 色彩矩阵
→ 目标 HueSatMap → exposure ramp → LookTable → Adobe RGB tone
→ 线性 sRGB D65 → sRGB 编码
→ 新 HALD + CUBE
```
严格逆序必须先逆 LookTable,再逆 HueSatMap。曲线不能逐通道独立应用:Adobe 对最大/最小通道应用曲线,
并按原来的相对位置重建中间通道;逆曲线使用同一 RGB 规则。
- D50 的 `SetWhiteXY`、ColorMatrix / ForwardMatrix 选择与双/三光源插值由 SDK 完成。
- 色域转换使用 SDK 的 ProPhoto 和 sRGB PCS 矩阵,包含 D50 ↔ D65 色适应。DCP 工作空间始终是**线性 ProPhoto**,不应用 ProPhoto gamma 1.8。
- 两种 HSV 表直接调用 SDK `RefBaselineHueSatMap`,包括周期色相插值、二维半/三维表差异和 `Profile*Encoding` 的 V 轴 sRGB 编解码。
- 内置曲线调用 SDK spline solver,再构建 SDK 默认 4096 区间的一维表;缺省使用 SDK ACR3。这里遵循 SDK 曲线精度,不采用 App 当前 `DcpToneCurve.toLut()` 的 256 点线性近似。
- 保留 DCP 的 `ProfileBaselineExposureOffset`:正 EV 用 exposure ramp,负 EV 用 SDK exposure tone。
- HALD 没有 RAW 场景元数据。DNG 图像自身的 BaselineExposure、曝光补偿、Shadows、黑电平都设为 0;不虚构 `DefaultBlackRender=Auto` 所需的图像黑场,不运行 PGTM、局部色调映射或其他图像相关流程。
- 两个 DCP 通过**白平衡归一化 camera RGB**连接:矩阵为 `ProPhotoFromPCS × CameraToPCS × diag(CameraWhite)`。
不同机型的传感器响应不是同一物理色彩空间,这一连接定义的是用户指定的 DCP 风格组合,不能恢复另一台相机的真实 RAW 响应。
逆矩阵产生的虚拟 camera RGB 交给 SDK `RefBaselineABCtoRGB`:保留其负值,
按 camera white 截断上界(归一化坐标为 1),矩阵后截断 ProPhoto 到 `[0,1]`,包括 HDR profile。
报告记录越界及裁切数量;源矩阵回算失败同样会触发严格模式拒绝导出。
- HDR DCP 的表使用 SDK overrange 规则,tone 在 overrange 编解码域操作。`--hdr-domain-max` 显式限定源 HDR 表逆解搜索范围,默认 16;输出仍是 SDR sRGB HALD/CUBE。
## HALD 排列和输入要求
HALD level 为 `L` 时,图片尺寸为 `L³ × L³`,LUT 为 `(L²)³` 个节点。
例如 level 8 = 512×512 PNG = 64³ LUT。接受 level 2–16,较大级数会增加内存和耗时。
- 默认 `--layout hald` 使用标准 HALD:光栅序列索引 `r + N*g + N*N*b`,其中 `N=L²`。
- `--layout tiles` 对应 App 当前 `BakedLutExporter` / `LutConverter` 的蓝色切片分块排列,
`x=(b % L)*N+r`,`y=(b // L)*N+g`。如要把输出 PNG 直接导入当前 App,用此选项生成及转换输入;`.cube` 不受 HALD 排列影响。
- 任意修改过的 HALD 也可输入;输出 LUT 表示“该 HALD 已有映射再接 DCP 转换”。只需要 DCP 之间的转换时,请使用恒等 HALD。
- 接受 8/16 位 RGB 或全不透明 RGBA PNG;不缩放、不旋转、不做隐式色彩管理。无标记 PNG 按 sRGB 解释。
- 拒绝非 sRGB gamma / 色度、ICC/cICP 色彩描述以及透明像素。含 ICC 的图片请先显式转成 sRGB 并保存为标准 sRGB PNG。
## 逆解与误差
HSV 表一般没有解析逆。工具以 SDK 的正向表作为唯一求值函数,采用有界、多起点 Gauss–Newton 求逆。
KD tree 仅提供初始值;不会用最近邻 LUT 替换数值逆解。SDR 搜索域为 `[0,1]³`。
逐阶段回算残差之后,再将逆解 camera RGB 完整通过源 DCP,验证最终 sRGB 是否重建输入。
默认 `--tolerance 0.00002` 是每像素最大通道误差上限;表/曲线残差单位是线性 ProPhoto,最终往返残差单位是编码 sRGB。
计算精度和图像文件量化精度分别记录:CUBE 来自浮点结果,PNG 额外存在最多约 `0.5/65535` 的通道量化误差。
源表可能折叠、饱和或裁切;某些 HALD 颜色没有有效前像,局部求解也可能不收敛。
残差达标只证明找到了可重建输入的前像,**不能证明该前像唯一或就是原 RAW 值**。
源 tone curve 非严格递增时直接拒绝逆向处理;不篡改曲线使其单调。
默认超出容差时仅写 JSON 报告,返回状态码 2,不导出新的 HALD/CUBE。
确认可以接受报告中的误差后,可用 `--allow-approximate` 显式导出求解所得的近似结果;报告状态会标为 `approximate`。
这不会修改 DCP、改变裁切规则或加入色彩补偿。
成功返回 0,参数/输入/构建错误返回 1,严格逆解检查失败返回 2。
## 代码位置
- `sdk_bridge.cpp` / `CMakeLists.txt`:桌面 SDK 桥接和编译,复用 App 同一份 SDK 与 XMP stub。
- `sdk.py`:动态库绑定、DCP 生命周期、参数读取。
- `pipeline.py`:颜色空间转换、RGB tone 正逆运算、HSV 表数值逆解、误差统计。
- `dcp_lut.py`:命令行、HALD 排列、16 位 PNG/CUBE 和报告导出。
- `errors.py` / `messages.json`:用户错误、帮助与状态消息的双语资源。
SDK 参考实现:仓库 `app/src/main/cpp/dcp/dng_sdk/source/` 中的
`dng_render.cpp`、`dng_reference.cpp`、`dng_color_spec.cpp`、`dng_color_space.cpp`、`dng_tone_curve.cpp`。
官方入口:[Adobe DNG SDK](https://www.adobe.com/support/downloads/dng/dng_sdk.html)。
+241
View File
@@ -0,0 +1,241 @@
# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy>=2.0,<3", "scipy>=1.14,<2", "pypng==0.20220715.0"]
# ///
"""Run with uv run tools/dcp_lut/dcp_lut.py --help."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import time
import zlib
import numpy as np
import png
from errors import ToolError
from pipeline import Converter
from sdk import HERE, Profile, load_sdk
def atomic_write(path, write):
path.parent.mkdir(parents=True, exist_ok=True)
fd, name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
try:
with os.fdopen(fd, "wb") as stream:
write(stream)
os.replace(name, path)
finally:
if os.path.exists(name):
os.unlink(name)
def check_destinations(outputs, inputs, overwrite):
protected = {p.resolve() for p in inputs}
for path in outputs:
if path.resolve() in protected:
raise ToolError("overwrite_input", path=path)
if path.exists() and not overwrite:
raise ToolError("output_exists", path=path)
def identity(level):
size = level * level
indices = np.arange(size ** 3)
return np.column_stack([indices % size, indices // size % size, indices // (size * size)]) / (size - 1)
def to_raster(rgb, level, layout):
size = level * level
if layout == "tiles":
# b = tileY * level + tileX; cube axes are b, g, r.
rgb = rgb.reshape(level, level, size, size, 3).transpose(0, 2, 1, 3, 4)
return rgb.reshape(level ** 3, level ** 3, 3)
def from_raster(rgb, level, layout):
if layout == "tiles":
size = level * level
rgb = rgb.reshape(level, size, level, size, 3).transpose(0, 2, 1, 3, 4)
return rgb.reshape(-1, 3)
def write_png(stream, rgb, level, layout):
raster = np.rint(np.clip(to_raster(rgb, level, layout), 0, 1) * 65535).astype(np.uint16)
# Explicit sRGB chunk; no approximate gamma-only color declaration.
# PNG header + IHDR occupies 33 bytes. Write sRGB directly after IHDR by
# streaming through a header buffer, avoiding a second full-image copy.
class SrgbStream:
def __init__(self):
self.header = bytearray()
self.ready = False
def write(self, data):
if self.ready:
return stream.write(data)
self.header.extend(data)
if len(self.header) >= 33:
stream.write(self.header[:33])
payload = b"sRGB\x00"
stream.write(struct.pack(">I", 1) + payload + struct.pack(">I", zlib.crc32(payload)))
stream.write(self.header[33:])
self.header.clear()
self.ready = True
return len(data)
png.Writer(level ** 3, level ** 3, bitdepth=16, greyscale=False).write(
SrgbStream(), raster.reshape(level ** 3, -1))
def read_hald(path, layout):
# Validate color semantics before decoding samples; never silently apply or
# discard an unknown ICC/HDR transfer function on a numeric LUT image.
with path.open("rb") as stream:
reader = png.Reader(file=stream)
reader.preamble()
width, height = reader.width, reader.height
level = round(width ** (1 / 3))
if width != height or level not in range(2, 17) or level ** 3 != width:
raise ToolError("invalid_hald_size")
with path.open("rb") as stream:
for kind, data in png.Reader(file=stream).chunks():
if kind in (b"iCCP", b"cICP"):
raise ToolError("unsupported_color_profile")
if kind == b"gAMA" and abs(struct.unpack(">I", data)[0] / 100000 - 0.45455) > 1e-5:
raise ToolError("invalid_gamma")
if kind == b"cHRM":
srgb = np.array([31270, 32900, 64000, 33000, 30000, 60000, 15000, 6000])
if np.any(np.abs(np.array(struct.unpack(">8I", data)) - srgb) > 5):
raise ToolError("invalid_primaries")
with path.open("rb") as stream:
width, height, rows, metadata = png.Reader(file=stream).asDirect()
depth = metadata["bitdepth"]
if depth not in (8, 16) or metadata["greyscale"]:
raise ToolError("invalid_samples")
array = np.vstack([np.asarray(row, dtype=np.uint16) for row in rows])
array = array.reshape(height, width, metadata["planes"])
if metadata["alpha"] and not np.all(array[:, :, 3] == (1 << depth) - 1):
raise ToolError("transparent_samples")
rgb = array[:, :, :3].astype(np.float64) / ((1 << depth) - 1)
return from_raster(rgb, level, layout), level, depth
def write_cube(stream, rgb, size, title):
title = title.replace('"', "'").replace("\n", " ").replace("\r", " ")
stream.write((f'TITLE "{title}"\n# D50 DCP composition; input/output encoded sRGB\n'
f'LUT_3D_SIZE {size}\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n').encode())
np.savetxt(stream, rgb, fmt="%.9f") # .cube: red changes fastest.
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def parser(messages):
cli = argparse.ArgumentParser(description=messages["description"])
cli.add_argument("--language", choices=["en", "zh"], default="en")
commands = cli.add_subparsers(dest="command", required=True)
make = commands.add_parser("identity", help=messages["identity"])
make.add_argument("--level", type=int, choices=range(2, 17), default=8, help=messages["level"])
make.add_argument("--output", type=Path, required=True)
convert = commands.add_parser("convert", help=messages["convert"])
convert.add_argument("--source", type=Path, required=True, help=messages["source"])
convert.add_argument("--target", type=Path, required=True, help=messages["target"])
convert.add_argument("--hald", type=Path, required=True, help=messages["input"])
convert.add_argument("--output-prefix", type=Path, required=True, help=messages["prefix"])
convert.add_argument("--allow-approximate", action="store_true", help=messages["approximate"])
convert.add_argument("--tolerance", type=float, default=2e-5, help=messages["tolerance"])
convert.add_argument("--hdr-domain-max", type=float, default=16, help=messages["hdr_domain"])
inspect = commands.add_parser("inspect", help=messages["inspect"])
inspect.add_argument("profile", type=Path)
for command in [make, convert]:
command.add_argument("--layout", choices=["hald", "tiles"], default="hald", help=messages["layout"])
command.add_argument("--overwrite", action="store_true", help=messages["overwrite"])
return cli
def convert(args, messages):
prefix = args.output_prefix
outputs = [Path(str(prefix) + ext) for ext in [".hald.png", ".cube", ".json"]]
check_destinations(outputs, [args.source, args.target, args.hald], args.overwrite)
if not (np.isfinite(args.tolerance) and 0 < args.tolerance < 1):
raise ToolError("invalid_tolerance")
if not (np.isfinite(args.hdr_domain_max) and 1 <= args.hdr_domain_max <= 256):
raise ToolError("invalid_domain")
rgb, level, depth = read_hald(args.hald, args.layout)
output = np.empty_like(rgb)
library = load_sdk()
started = time.monotonic()
with Profile(library, args.source) as source, Profile(library, args.target) as target:
processor = Converter(source, target, args.tolerance, args.hdr_domain_max)
last_progress = 0
for start in range(0, len(rgb), 4096):
end = min(start + 4096, len(rgb))
output[start:end] = processor.convert(rgb[start:end])
if time.monotonic() - last_progress >= 5 or end == len(rgb):
print(messages["progress"].format(done=end, total=len(rgb)), file=sys.stderr)
last_progress = time.monotonic()
diagnostics = processor.report()
failed = any(item["over_tolerance"] for item in diagnostics["inverse_residuals"].values())
report = {"schema_version": 1, "white": "D50", "sdk": library.dcp_version().decode(),
"source": source.describe(), "target": target.describe(),
"input_hald": str(args.hald.resolve()), "input_bit_depth": depth,
"input_hashes_sha256": {str(p.resolve()): digest(p) for p in [args.source, args.target, args.hald]},
"layout": args.layout, "hald_level": level, "lut_size": level * level,
"output_bit_depth": 16, "png_quantization_error_bound": 0.5 / 65535,
"exported": False,
"camera_bridge": "neutral-normalized white-balanced camera RGB",
"shadows": 0, "image_baseline_exposure": 0,
"hdr_inverse_domain_max": args.hdr_domain_max,
"inverse_uniqueness": "not guaranteed: table clipping/folds can have multiple preimages",
"status": "approximate" if failed and args.allow_approximate else "rejected" if failed else "validated",
"elapsed_seconds": time.monotonic() - started, **diagnostics}
atomic_write(outputs[2], lambda f: f.write(json.dumps(report, indent=2, ensure_ascii=False).encode()))
if failed and not args.allow_approximate:
print(messages["failed_inverse"].format(path=outputs[2]), file=sys.stderr)
return 2
if failed:
print(messages["approx_warning"].format(path=outputs[2]), file=sys.stderr)
atomic_write(outputs[0], lambda f: write_png(f, output, level, args.layout))
atomic_write(outputs[1], lambda f: write_cube(f, output, level * level, f"{source.name} to {target.name}"))
report["exported"] = True
atomic_write(outputs[2], lambda f: f.write(json.dumps(report, indent=2, ensure_ascii=False).encode()))
for path in outputs:
print(messages["saved"].format(path=path))
return 0
def main():
language_parser = argparse.ArgumentParser(add_help=False)
language_parser.add_argument("--language", choices=["en", "zh"], default="en")
language, _ = language_parser.parse_known_args()
messages = json.loads((HERE / "messages.json").read_text())[language.language]
args = parser(messages).parse_args()
try:
if args.command == "identity":
check_destinations([args.output], [], args.overwrite)
rgb = identity(args.level)
atomic_write(args.output, lambda f: write_png(f, rgb, args.level, args.layout))
print(messages["saved"].format(path=args.output))
return 0
if args.command == "inspect":
with Profile(load_sdk(), args.profile) as profile:
print(json.dumps(profile.describe(), indent=2, ensure_ascii=False))
return 0
return convert(args, messages)
except (ValueError, OSError, RuntimeError, png.Error, subprocess.CalledProcessError, np.linalg.LinAlgError) as exc:
detail = exc.translated(messages) if isinstance(exc, ToolError) else str(exc)
print(messages["error"].format(message=detail), file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+10
View File
@@ -0,0 +1,10 @@
"""Localizable user-facing failures; preserve SDK/system details as parameters."""
class ToolError(ValueError):
def __init__(self, key, **parameters):
self.key, self.parameters = key, parameters
super().__init__(key)
def translated(self, messages):
return messages[self.key].format(**self.parameters)
+72
View File
@@ -0,0 +1,72 @@
{
"en": {
"description": "Compose inverse source DCP and forward target DCP at D50; export HALD PNG and CUBE.",
"identity": "Create an identity sRGB HALD PNG",
"convert": "Convert a HALD through two DCP profiles",
"inspect": "Inspect the SDK-resolved D50 profile",
"level": "HALD level: image side = level^3, LUT size = level^2 (2..16)",
"layout": "hald: standard R-fastest raster; tiles: PhotonCamera blue-slice tiles",
"input": "Input 8/16-bit sRGB HALD PNG (untagged PNG is interpreted as sRGB)",
"source": "Source DCP to invert",
"target": "Target DCP to apply",
"prefix": "Output prefix for .hald.png, .cube and .json",
"approximate": "Explicitly allow export when inverse residual exceeds tolerance; keep diagnostics",
"tolerance": "Maximum absolute per-channel inverse residual (default: 0.00002)",
"hdr_domain": "Upper bound of the source HDR map inverse search (default: 16)",
"overwrite": "Replace existing outputs (input files are always protected)",
"progress": "Converted {done}/{total} HALD nodes",
"failed_inverse": "Inverse residual exceeds tolerance. Diagnostics: {path}. No HALD/CUBE exported. Use --allow-approximate only if these errors are acceptable.",
"approx_warning": "Approximate inverse: see residuals in {path}",
"saved": "Saved: {path}",
"error": "Error: {message}",
"overwrite_input": "Output would overwrite input: {path}",
"output_exists": "Output exists: {path} (use --overwrite)",
"invalid_hald_size": "HALD must be square, side = level^3, level in 2..16",
"unsupported_color_profile": "ICC/cICP PNG is not accepted; convert the HALD explicitly to sRGB",
"invalid_gamma": "HALD PNG gamma is not sRGB",
"invalid_primaries": "HALD PNG primaries are not sRGB",
"invalid_samples": "HALD must contain 8-bit or 16-bit RGB samples",
"transparent_samples": "Transparent HALD samples are not supported",
"invalid_tolerance": "--tolerance must be finite and between 0 and 1",
"invalid_domain": "--hdr-domain-max must be finite and in [1, 256]",
"nonmonotonic_curve": "Source tone curve is not strictly increasing; no unique inverse",
"sdk_failure": "{path}: {detail}",
"nonfinite_profile": "{path}: nonfinite profile data",
"nonfinite_stage": "{name}: nonfinite stage {stage} result"
},
"zh": {
"description": "在 D50 下逆向源 DCP、正向目标 DCP,导出 HALD PNG 和 CUBE。",
"identity": "生成 sRGB 恒等 HALD PNG",
"convert": "用两个 DCP 转换 HALD",
"inspect": "查看 SDK 在 D50 下解析的配置",
"level": "HALD 级数:图片边长 = 级数^3,LUT 边长 = 级数^2(2..16)",
"layout": "hald:标准 R 最快变化的行排列;tiles:PhotonCamera 的蓝色切片分块排列",
"input": "输入 8/16 位 sRGB HALD PNG(无色彩标记时按 sRGB 解释)",
"source": "需要逆向处理的源 DCP",
"target": "需要正向处理的目标 DCP",
"prefix": "输出前缀,生成 .hald.png、.cube 和 .json",
"approximate": "明确允许在逆解残差超出容差时导出,保留诊断结果",
"tolerance": "逆解各通道绝对残差上限(默认 0.00002)",
"hdr_domain": "源 HDR 表逆解的搜索域上限(默认 16)",
"overwrite": "替换已有输出(始终保护输入文件)",
"progress": "已转换 {done}/{total} 个 HALD 节点",
"failed_inverse": "逆解残差超出容差,诊断已保存:{path}。未导出 HALD/CUBE。仅在接受这些误差时使用 --allow-approximate。",
"approx_warning": "本次使用近似逆解,请查看残差报告:{path}",
"saved": "已保存:{path}",
"error": "错误:{message}",
"overwrite_input": "输出会覆盖输入文件:{path}",
"output_exists": "输出文件已存在:{path}(使用 --overwrite 可替换)",
"invalid_hald_size": "HALD 必须是正方形,边长等于级数的三次方,级数范围为 2..16",
"unsupported_color_profile": "不接受 ICC/cICP PNG,请先明确将 HALD 转换为标准 sRGB PNG",
"invalid_gamma": "HALD PNG 的 gamma 标记不是 sRGB",
"invalid_primaries": "HALD PNG 的原色色度不是 sRGB",
"invalid_samples": "HALD 必须包含 8 位或 16 位 RGB 数据",
"transparent_samples": "不支持含透明像素的 HALD",
"invalid_tolerance": "--tolerance 必须是 0 到 1 之间的有限数值",
"invalid_domain": "--hdr-domain-max 必须是 [1, 256] 范围内的有限数值",
"nonmonotonic_curve": "源曲线不是严格递增曲线,无法进行唯一逆解",
"sdk_failure": "{path}:{detail}",
"nonfinite_profile": "{path}:配置包含非有限数值",
"nonfinite_stage": "{name}:阶段 {stage} 的结果包含非有限数值"
}
}
+200
View File
@@ -0,0 +1,200 @@
"""D50 profile composition, with measured numerical inverses of SDK maps."""
from __future__ import annotations
import numpy as np
from scipy.spatial import cKDTree
from errors import ToolError
from sdk import Profile
def decode_srgb(x):
x = np.maximum(x, 0)
return np.where(x <= 0.04045, x / 12.92, ((x + 0.055) / 1.055) ** 2.4)
def encode_srgb(x):
x = np.maximum(x, 0)
return np.where(x <= 0.0031308, 12.92 * x, 1.055 * x ** (1 / 2.4) - 0.055)
def encode_overrange(x):
x = np.maximum(x, 0)
return x * (256 + x) / (256 * (1 + x))
def decode_overrange(x):
# Stable positive quadratic root, algebraically equal to SDK DecodeOverrange.
x = np.maximum(x, 0)
a = 256 * (1 - x)
root = np.sqrt(a * a + 1024 * x)
return np.where(a >= 0, 512 * x / np.maximum(root + a, 1e-30), (root - a) / 2)
def tone(profile: Profile, rgb, inverse=False):
"""Adobe RGB tone: map extrema; interpolate middle channel, preserving hue."""
values = profile.curve
if inverse and np.any(np.diff(values) <= 0):
raise ToolError("nonmonotonic_curve")
x = encode_overrange(rgb) if profile.hdr else np.clip(rgb, 0, 1)
lo, hi = x.min(axis=1), x.max(axis=1)
axis = np.linspace(0, 1, len(values))
if inverse:
low, high = np.interp(lo, values, axis), np.interp(hi, values, axis)
else:
low, high = np.interp(lo, axis, values), np.interp(hi, axis, values)
if profile.hdr:
slope = (values[-1] - np.interp(0.999, axis, values)) / 0.001
low = np.where(lo > 1, values[-1] + slope * (lo - 1), low)
high = np.where(hi > 1, values[-1] + slope * (hi - 1), high)
fraction = np.divide(x - lo[:, None], (hi - lo)[:, None],
out=np.zeros_like(x), where=(hi - lo)[:, None] > 0)
out = low[:, None] + fraction * (high - low)[:, None]
return decode_overrange(out) if profile.hdr else out
def exposure(profile: Profile, rgb, inverse=False):
# SDK exposure ramp with zero image-dependent shadows/black. Negative EV is
# already included in the SDK tone curve via dng_function_exposure_tone.
gain = 2 ** max(0, profile.exposure)
if inverse:
return rgb / gain
out = np.maximum(rgb, 0) * gain
return out if profile.hdr else np.minimum(out, 1)
def forward(profile: Profile, camera):
rgb = profile.apply(3, camera)
rgb = profile.apply(0, rgb)
rgb = exposure(profile, rgb)
rgb = profile.apply(1, rgb)
return tone(profile, rgb)
def error_summary(error, tolerance):
error = np.asarray(error)
return {"count": int(len(error)), "over_tolerance": int(np.sum(error > tolerance)),
"maximum": float(np.max(error, initial=0)),
"rms": float(np.sqrt(np.mean(error ** 2))) if len(error) else 0,
"p99": float(np.quantile(error, 0.99)) if len(error) else 0}
class MapInverse:
"""Bounded, multistart Gauss-Newton; every result is checked with the SDK.
A KD tree only supplies initial guesses. It never substitutes an inverse LUT
for the forward map. Multiple basins are tried for failed local solves.
Clipped/non-injective outputs cannot recover a unique original camera value.
"""
def __init__(self, profile: Profile, stage: int, tolerance: float, domain_max: float):
self.profile, self.stage = profile, stage
self.tolerance, self.upper = tolerance, domain_max
self.enabled = profile.maps[stage]
if self.enabled:
axis = np.linspace(0, 1, 33)
if domain_max > 1:
axis = np.unique(np.r_[axis, np.geomspace(1, domain_max, 17)])
self.seeds = np.stack(np.meshgrid(axis, axis, axis, indexing="ij"), -1).reshape(-1, 3)
self.tree = cKDTree(profile.apply(stage, self.seeds))
def solve(self, target):
if not self.enabled:
return target.copy()
best = self._iterate(target, np.clip(target, 0, self.upper))
best_error = np.max(np.abs(self.profile.apply(self.stage, best) - target), axis=1)
failed = np.flatnonzero(best_error > self.tolerance)
if len(failed):
_, indices = self.tree.query(target[failed], k=4)
for seed in range(4):
candidate = self._iterate(target[failed], self.seeds[indices[:, seed]])
error = np.max(np.abs(self.profile.apply(self.stage, candidate) - target[failed]), axis=1)
better = error < best_error[failed]
selected = failed[better]
best[selected], best_error[selected] = candidate[better], error[better]
return best
def _iterate(self, target, initial):
x = initial.copy()
damping = np.full(len(x), 1e-5)
# Map residual is linear ProPhoto, while the final validation is encoded
# sRGB. A fixed 5e-6 map error is visibly amplified by the toe + sRGB.
# Solve near the SDK float32 relative precision, especially in shadows.
convergence = np.minimum(self.tolerance / 32,
np.max(np.abs(target), axis=1) * 5e-8 + 1e-10)
for _ in range(60):
y = self.profile.apply(self.stage, x)
residual = y - target
active = np.flatnonzero(np.max(np.abs(residual), axis=1) > convergence)
if not len(active):
break
xa, ra = x[active], residual[active]
jac = np.empty((len(active), 3, 3))
for c in range(3):
step = 2e-4 * np.maximum(1, xa[:, c])
plus, minus = xa.copy(), xa.copy()
plus[:, c] = np.minimum(xa[:, c] + step, self.upper)
minus[:, c] = np.maximum(xa[:, c] - step, 0)
jac[:, :, c] = (self.profile.apply(self.stage, plus) -
self.profile.apply(self.stage, minus)) / (plus[:, c] - minus[:, c])[:, None]
jt = jac.transpose(0, 2, 1)
normal = jt @ jac + damping[active, None, None] * np.eye(3)
delta = np.linalg.solve(normal, (jt @ ra[:, :, None]))[:, :, 0]
candidate = np.clip(xa - delta, 0, self.upper)
new_residual = self.profile.apply(self.stage, candidate) - target[active]
better = np.sum(new_residual ** 2, axis=1) < np.sum(ra ** 2, axis=1)
x[active[better]] = candidate[better]
damping[active] = np.where(better, np.maximum(damping[active] * 0.3, 1e-9),
np.minimum(damping[active] * 10, 1e5))
if np.all(damping[active] >= 1e5):
break
return x
class Converter:
def __init__(self, source, target, tolerance=2e-5, hdr_domain_max=16):
self.source, self.target, self.tolerance = source, target, tolerance
if np.any(np.diff(source.curve) <= 0):
raise ToolError("nonmonotonic_curve")
self.from_srgb = np.linalg.inv(source.to_srgb)
self.inverse_matrix = np.linalg.inv(source.matrix)
upper = hdr_domain_max if source.hdr else 1
self.hue = MapInverse(source, 0, tolerance, upper)
self.look = MapInverse(source, 1, tolerance, upper)
self.errors = {key: [] for key in ["tone", "look_table", "hue_sat_map", "matrix", "source_roundtrip_srgb"]}
self.gamut_clipped = 0
self.target_matrix_clipped = 0
self.camera_outside_unit = 0
self.camera_white_clipped = 0
def convert(self, rgb):
source = self.source
pro = decode_srgb(rgb) @ self.from_srgb.T
before_tone = tone(source, pro, inverse=True)
self._record("tone", tone(source, before_tone), pro)
before_look = self.look.solve(before_tone)
self._record("look_table", source.apply(1, before_look), before_tone)
before_exposure = exposure(source, before_look, inverse=True)
before_hue = self.hue.solve(before_exposure)
self._record("hue_sat_map", source.apply(0, before_hue), before_exposure)
camera = before_hue @ self.inverse_matrix.T
self.camera_outside_unit += int(np.any((camera < 0) | (camera > 1), axis=1).sum())
self.camera_white_clipped += int(np.any(camera > 1 + 1e-7, axis=1).sum())
self._record("matrix", source.apply(3, camera), before_hue)
replay = encode_srgb(np.clip(forward(source, camera) @ source.to_srgb.T, 0, 1))
self._record("source_roundtrip_srgb", replay, rgb)
target_linear = np.minimum(camera, 1) @ self.target.matrix.T
self.target_matrix_clipped += int(np.any((target_linear < 0) | (target_linear > 1), axis=1).sum())
linear = forward(self.target, camera) @ self.target.to_srgb.T
self.gamut_clipped += int(np.any((linear < -1e-7) | (linear > 1 + 1e-7), axis=1).sum())
return encode_srgb(np.clip(linear, 0, 1))
def _record(self, key, actual, expected):
self.errors[key].append(np.max(np.abs(actual - expected), axis=1))
def report(self):
return {"inverse_residuals": {k: error_summary(np.concatenate(v), self.tolerance)
for k, v in self.errors.items()}, "tolerance": self.tolerance,
"target_srgb_gamut_clipped_nodes": self.gamut_clipped,
"target_prophoto_matrix_clipped_nodes": self.target_matrix_clipped,
"camera_white_clipped_nodes": self.camera_white_clipped,
"virtual_camera_outside_unit_nodes": self.camera_outside_unit}
+86
View File
@@ -0,0 +1,86 @@
"""Typed, lifetime-managed access to the repository's Adobe DNG SDK."""
from __future__ import annotations
import ctypes as ct
from pathlib import Path
import subprocess
import sys
import numpy as np
from errors import ToolError
HERE = Path(__file__).resolve().parent
def load_sdk() -> ct.CDLL:
build = HERE / "build"
# Always let CMake check dependencies; stale profile math must not survive SDK edits.
subprocess.run(["cmake", "-S", str(HERE), "-B", str(build),
"-DCMAKE_BUILD_TYPE=Release"], check=True, stdout=sys.stderr)
subprocess.run(["cmake", "--build", str(build), "-j", "8"],
check=True, stdout=sys.stderr)
suffix = "dylib" if sys.platform == "darwin" else "so"
lib = ct.CDLL(str(build / f"libphoton_dcp.{suffix}"))
fp = np.ctypeslib.ndpointer(dtype=np.float32, flags="C_CONTIGUOUS")
dp = np.ctypeslib.ndpointer(dtype=np.float64, flags="C_CONTIGUOUS")
for name, arguments, result in [
("dcp_open", [ct.c_char_p], ct.c_void_p),
("dcp_close", [ct.c_void_p], None),
("dcp_error", [], ct.c_char_p),
("dcp_version", [], ct.c_char_p),
("dcp_name", [ct.c_void_p], ct.c_char_p),
("dcp_info", [ct.c_void_p, dp], None),
("dcp_apply", [ct.c_void_p, ct.c_int, fp, fp, ct.c_int], ct.c_int),
]:
function = getattr(lib, name)
function.argtypes, function.restype = arguments, result
return lib
class Profile:
def __init__(self, lib: ct.CDLL, path: Path):
self.lib, self.path = lib, path.resolve()
self.handle = lib.dcp_open(str(self.path).encode())
if not self.handle:
raise ToolError("sdk_failure", path=self.path, detail=lib.dcp_error().decode())
info = np.empty(23 + 4097, dtype=np.float64)
lib.dcp_info(self.handle, info)
self.matrix = info[:9].reshape(3, 3).copy()
self.to_srgb = info[9:18].reshape(3, 3).copy()
self.exposure = float(info[18])
self.hdr, self.embedded_curve = bool(info[19]), bool(info[20])
self.maps = [bool(info[21]), bool(info[22])]
self.curve = info[23:].copy()
self.name = lib.dcp_name(self.handle).decode("utf-8")
if not np.isfinite(info).all():
self.close()
raise ToolError("nonfinite_profile", path=self.path)
def close(self):
if self.handle:
self.lib.dcp_close(self.handle)
self.handle = None
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
def apply(self, stage: int, rgb: np.ndarray) -> np.ndarray:
rgb = np.ascontiguousarray(rgb, dtype=np.float32)
output = np.empty_like(rgb)
if not self.lib.dcp_apply(self.handle, stage, rgb, output, len(rgb)):
raise ToolError("sdk_failure", path=self.path, detail=self.lib.dcp_error().decode())
if not np.isfinite(output).all():
raise ToolError("nonfinite_stage", name=self.name, stage=stage)
return output.astype(np.float64)
def describe(self) -> dict:
return {"path": str(self.path), "name": self.name,
"camera_wb_to_prophoto_d50": self.matrix.tolist(),
"prophoto_d50_to_linear_srgb": self.to_srgb.tolist(),
"baseline_exposure_offset_ev": self.exposure,
"tone_curve": "embedded_sdk_spline" if self.embedded_curve else "ACR3",
"supports_overrange": self.hdr, "hue_sat_map": self.maps[0],
"look_table": self.maps[1]}
+134
View File
@@ -0,0 +1,134 @@
// Host-only C ABI. All profile interpretation and forward table evaluation belong
// to the vendored Adobe SDK, not to a second TIFF/DCP implementation.
#include "dng_1d_table.h"
#include "dng_camera_profile.h"
#include "dng_color_space.h"
#include "dng_color_spec.h"
#include "dng_exceptions.h"
#include "dng_file_stream.h"
#include "dng_host.h"
#include "dng_negative.h"
#include "dng_reference.h"
#include "dng_render.h"
#include "dng_spline.h"
#include "dng_utils.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
thread_local std::string error;
struct Profile {
dng_host host;
dng_camera_profile profile;
AutoPtr<dng_hue_sat_map> hue;
AutoPtr<dng_1d_table> hueEncode, hueDecode, lookEncode, lookDecode;
dng_1d_table tone;
dng_matrix cameraToProPhoto;
double exposure;
explicit Profile(const char* path) {
dng_file_stream stream(path);
if (!profile.ParseExtended(stream) || !profile.IsValid(3))
throw std::runtime_error("Invalid three-channel DCP");
AutoPtr<dng_negative> negative(host.Make_dng_negative());
negative->SetColorChannels(3);
dng_color_spec spec(*negative.Get(), &profile);
spec.SetWhiteXY(D50_xy_coord());
cameraToProPhoto = dng_space_ProPhoto::Get().MatrixFromPCS() * spec.CameraToPCS();
// Join profiles in neutral-normalized, white-balanced camera RGB.
for (uint32 r = 0; r < 3; ++r)
for (uint32 c = 0; c < 3; ++c)
cameraToProPhoto[r][c] *= spec.CameraWhite()[c];
hue.Reset(profile.HueSatMapForWhite(D50_xy_coord()));
BuildHueSatMapEncodingTable(host.Allocator(), profile.HueSatMapEncoding(),
hueEncode, hueDecode, false);
BuildHueSatMapEncodingTable(host.Allocator(), profile.LookTableEncoding(),
lookEncode, lookDecode, false);
exposure = profile.BaselineExposureOffset().As_real64();
if (!std::isfinite(exposure)) throw std::runtime_error("Nonfinite exposure offset");
dng_spline_solver spline;
const dng_1d_function* curve = &dng_tone_curve_acr3_default::Get();
if (profile.ToneCurve().IsValid()) {
profile.ToneCurve().Solve(spline);
curve = &spline;
}
dng_function_exposure_tone exposureTone(exposure);
dng_1d_concatenate totalTone(exposureTone, *curve);
tone.Initialize(host.Allocator(), totalTone);
}
};
void captureError() {
try { throw; }
catch (const dng_exception& e) { error = "Adobe DNG SDK error " + std::to_string(e.ErrorCode()); }
catch (const std::exception& e) { error = e.what(); }
catch (...) { error = "Unknown Adobe DNG SDK error"; }
}
}
extern "C" {
const char* dcp_version() { return kDNGSDK_GetInfoVersion; }
const char* dcp_error() { return error.c_str(); }
void* dcp_open(const char* path) {
try { return new Profile(path); }
catch (...) { captureError(); return nullptr; }
}
void dcp_close(void* handle) { delete static_cast<Profile*>(handle); }
const char* dcp_name(void* handle) { return static_cast<Profile*>(handle)->profile.Name().Get(); }
// 9 WB camera->ProPhoto coefficients, 9 ProPhoto->sRGB coefficients,
// exposure EV, HDR flag, embedded-curve flag, HueSat/Look presence, 4097 curve samples.
void dcp_info(void* handle, double* out) {
auto& p = *static_cast<Profile*>(handle);
auto toSrgb = dng_space_sRGB::Get().MatrixFromPCS() * dng_space_ProPhoto::Get().MatrixToPCS();
for (int r = 0; r < 3; ++r) for (int c = 0; c < 3; ++c) {
out[r * 3 + c] = p.cameraToProPhoto[r][c];
out[9 + r * 3 + c] = toSrgb[r][c];
}
out[18] = p.exposure;
out[19] = p.profile.IsHDR();
out[20] = p.profile.ToneCurve().IsValid();
out[21] = p.hue.Get() && p.hue->IsValid();
out[22] = p.profile.HasLookTable();
for (int i = 0; i <= 4096; ++i) out[23 + i] = p.tone.Table()[i];
}
// Packed RGB input/output. Map/tone stages require nonnegative RGB; the matrix
// stage retains signed virtual camera coordinates, as RefBaselineABCtoRGB does.
// Stage 0 = HueSatMap, 1 = LookTable, 2 = RGB tone (SDR reference oracle),
// 3 = normalized camera -> ProPhoto including Adobe's camera-white clipping.
int dcp_apply(void* handle, int stage, const float* input, float* output, int count) {
try {
if (count < 0 || stage < 0 || stage > 3) throw std::runtime_error("Invalid stage/count");
auto& p = *static_cast<Profile*>(handle);
std::vector<float> planes(static_cast<size_t>(count) * 3);
for (int i = 0; i < count; ++i) for (int c = 0; c < 3; ++c) {
float x = input[i * 3 + c];
if (!std::isfinite(x) || (stage != 3 && x < 0)) throw std::runtime_error("Invalid stage input");
planes[c * count + i] = x;
}
float *r = planes.data(), *g = r + count, *b = g + count;
if (stage == 3) {
const dng_vector_3 white(1.0, 1.0, 1.0);
RefBaselineABCtoRGB(r, g, b, r, g, b, count, white, p.cameraToProPhoto);
} else if (stage == 2) {
RefBaselineRGBTone(r, g, b, r, g, b, count, p.tone);
} else {
const dng_hue_sat_map* map = stage == 0 ? p.hue.Get() : &p.profile.LookTable();
if (map && map->IsValid())
RefBaselineHueSatMap(r, g, b, r, g, b, count, *map,
stage == 0 ? p.hueEncode.Get() : p.lookEncode.Get(),
stage == 0 ? p.hueDecode.Get() : p.lookDecode.Get(), p.profile.IsHDR());
}
for (int i = 0; i < count; ++i) for (int c = 0; c < 3; ++c)
output[i * 3 + c] = planes[c * count + i];
return 1;
} catch (...) { captureError(); return 0; }
}
}