The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.
Add ACEScg to Convert Image Color Space and Save Image (Advanced) EXR (#17023)
DoronGenzelHassbc5f880dbdd4
diff --git a/comfy_extras/nodes_images.py b/comfy_extras/nodes_images.pyindex 64b09805d..cf234ae44 100644--- a/comfy_extras/nodes_images.py+++ b/comfy_extras/nodes_images.py@@ -17,6 +17,7 @@ import uuidimport zlibimport comfy.utils+import comfy.model_managementfrom av.video.reformatter import ColorPrimaries, ColorRange, ColorTrcfrom enum import Enumfrom fractions import Fraction@@ -1406,16 +1407,16 @@ class ImageSDRToHDR(IO.ComfyNode):class ImageColorSpace(IO.ComfyNode):@classmethoddef define_schema(cls):- spaces = ["sRGB", "HDR", "HDR PQ", "linear", "HDR LogC3", "HDR ACEScct"]+ spaces = ["sRGB", "HDR", "HDR ACEScct", "HDR LogC3", "HDR PQ", "linear", "linear ACEScg"]return IO.Schema(node_id="ImageColorSpace",display_name="Convert Image Color Space",category="image/color",- description="Convert sRGB, linear Rec.709, HDR (Rec.2020 HLG), HDR PQ (Rec.2020 PQ), HDR LogC3, and HDR ACEScct. LogC3 uses the EI 800 curve with Rec.709 primaries and codes clamped to [0, 1]. ACEScct uses AP1 primaries and D60 white, with Bradford adaptation to D65. Convert LogC3 or ACEScct to linear for EXR saving. Linear 1.0 uses the same 203-nit reference white as sRGB; HLG uses a 1000-nit reference display. Linear and ACEScct outputs preserve extended values. Linear-to-HDR conversions preserve highlights without tone mapping; HLG and PQ outputs clip negative channels. SDR output and PQ-to-HLG conversion tone-map excess luminance across the batch and compress out-of-gamut colors. Conversions compute in float32 and return the intermediate device and dtype. Straight alpha is not color-transformed.",+ description="Convert sRGB, linear Rec.709, HDR (Rec.2020 HLG), HDR PQ (Rec.2020 PQ), HDR LogC3, linear ACEScg, and HDR ACEScct. LogC3 uses the EI 800 curve with Rec.709 primaries and codes clamped to [0, 1]. ACEScg is scene-linear AP1 with D60 white. ACEScct is the ACEScg log encoding. Both use Bradford adaptation to D65. Convert LogC3 or ACEScct to linear ACEScg (AP1 scene-linear) or linear (Rec.709) before saving EXR. Linear 1.0 and ACEScg 1.0 use the same 203-nit reference white as sRGB; HLG uses a 1000-nit reference display. Linear, ACEScg, and ACEScct outputs preserve extended values. Linear-to-HDR conversions preserve highlights without tone mapping; HLG and PQ outputs clip negative channels. SDR output and PQ-to-HLG conversion tone-map excess luminance across the batch and compress out-of-gamut colors. Conversions compute in float32 and return the intermediate device and dtype. Straight alpha is not color-transformed.",inputs=[IO.Image.Input("image"),IO.Combo.Input("source", options=spaces, default="sRGB", tooltip="Color space of the input pixels."),- IO.Combo.Input("destination", options=spaces, default="sRGB", tooltip="Color space of the output pixels. Set the save node to this same color space. Convert LogC3 or ACEScct to linear before saving EXR, or to sRGB/HDR/HDR PQ before saving video."),+ IO.Combo.Input("destination", options=spaces, default="sRGB", tooltip="Color space of the output pixels. Set the save node to this same color space. Convert LogC3 or ACEScct to linear ACEScg for ACEScg EXR, or to linear for Rec.709 EXR. Convert to sRGB/HDR/HDR PQ before saving video."),],outputs=[IO.Image.Output()],)@@ -1433,6 +1434,8 @@ class ImageColorSpace(IO.ComfyNode):rgb = _convert_rgb_primaries(srgb_to_linear(rgb), _REC709_TO_REC2020) * _SDR_WHITE_NITSelif source == "linear":rgb = _convert_rgb_primaries(rgb, _REC709_TO_REC2020) * _SDR_WHITE_NITS+ elif source == "linear ACEScg":+ rgb = _convert_rgb_primaries(rgb, _ACESCG_TO_REC2020) * _SDR_WHITE_NITSelif source == "HDR LogC3":rgb = rgb.clamp(0.0, 1.0)low = (rgb - _LOGC3_F) / _LOGC3_E@@ -1457,6 +1460,8 @@ class ImageColorSpace(IO.ComfyNode):if destination == "linear":rgb = _convert_rgb_primaries(rgb / _SDR_WHITE_NITS, _REC2020_TO_REC709)+ elif destination == "linear ACEScg":+ rgb = _convert_rgb_primaries(rgb / _SDR_WHITE_NITS, _REC2020_TO_ACESCG)elif destination == "HDR LogC3":rgb = _convert_rgb_primaries(rgb / _SDR_WHITE_NITS, _REC2020_TO_REC709).clamp_min(0.0)low = _LOGC3_E * rgb + _LOGC3_F@@ -1536,12 +1541,14 @@ def inject_png_metadata(png_bytes: bytes, prompt: dict | None, extra_pnginfo: di# Standard chromaticities (CIE 1931 xy) for the colorspaces this node writes.-# Each tuple is (Rx, Ry, Gx, Gy, Bx, By, Wx, Wy). All share D65 white point.+# Each tuple is (Rx, Ry, Gx, Gy, Bx, By, Wx, Wy)._CHROMATICITIES = {- # ITU-R BT.709 / sRGB primaries+ # ITU-R BT.709 / sRGB primaries, D65"Rec.709": (0.6400, 0.3300, 0.3000, 0.6000, 0.1500, 0.0600, 0.3127, 0.3290),- # ITU-R BT.2020 (UHDTV / wide-gamut HDR) primaries+ # ITU-R BT.2020 (UHDTV / wide-gamut HDR) primaries, D65"Rec.2020": (0.7080, 0.2920, 0.1700, 0.7970, 0.1310, 0.0460, 0.3127, 0.3290),+ # ACEScg / AP1 primaries, ACES white (D60). SMPTE ST 2065-1.+ "ACEScg": (0.7130, 0.2930, 0.1650, 0.8300, 0.1280, 0.0440, 0.32168, 0.33767),}@@ -1572,15 +1579,18 @@ def inject_exr_metadata(their RGB→XYZ relationship is the `chromaticities` attribute. We pick theprimaries that match what the user told us their input was:- colorspace="sRGB" → Rec. 709 / sRGB primaries (D65)- colorspace="HDR" → Rec. 2020 / BT.2100 primaries (D65)+ colorspace="sRGB" → Rec. 709 / sRGB primaries (D65)+ colorspace="HDR" → Rec. 2020 / BT.2100 primaries (D65)+ colorspace="linear" → Rec. 709 primaries (D65)+ colorspace="linear ACEScg" → ACEScg / AP1 primaries (D60)Pixels are always converted to linear scene light upstream (sRGB EOTF- inverse for sRGB; HLG OETF inverse for HDR), so the file content is- scene-linear in the indicated gamut. OpenEXR has no standard transfer-- function attribute (the OpenEXR TSC has discussed adding one but it- doesn't exist), so we don't invent one — `chromaticities` plus the EXR- linear-by-convention rule fully specifies the color.+ inverse for sRGB; HLG OETF inverse for HDR; ACEScg is already linear),+ so the file content is scene-linear in the indicated gamut. OpenEXR has+ no standard transfer-function attribute (the OpenEXR TSC has discussed+ adding one but it doesn't exist), so we don't invent one —+ `chromaticities` plus the EXR linear-by-convention rule fully specifies+ the color.Prompt/workflow: written as plain `string` attributes using the same keys(`prompt`, `workflow`, ...) that Comfy uses for PNG tEXt chunks, so the@@ -1602,11 +1612,13 @@ def inject_exr_metadata(if colorspace is not None:# Map each colorspace option to the RGB primaries the linear pixels# are now in. "sRGB" and "linear" both produce Rec. 709 linear; "HDR"- # (HLG-encoded Rec. 2020 input) produces Rec. 2020 linear.+ # (HLG-encoded Rec. 2020 input) produces Rec. 2020 linear; "linear ACEScg"+ # is already ACEScg / AP1 linear.primaries_name = {- "sRGB": "Rec.709",- "linear": "Rec.709",- "HDR": "Rec.2020",+ "sRGB": "Rec.709",+ "HDR": "Rec.2020",+ "linear": "Rec.709",+ "linear ACEScg": "ACEScg",}.get(colorspace, "Rec.709")new_blob += _exr_attribute("chromaticities",@@ -1914,6 +1926,7 @@ def _to_scene_linear(img_tensor: torch.Tensor, colorspace: str) -> torch.Tensor:return srgb_to_linear(img_tensor)if colorspace == "HDR":return hlg_to_linear(img_tensor)+ # "linear" (Rec.709) and "linear ACEScg" (AP1) are already scene-linear.return img_tensor@@ -1963,11 +1976,13 @@ def _encode_image(For EXR the input is interpreted according to `colorspace` and convertedto scene-linear (EXR's convention) before writing:- "sRGB" → input is sRGB-encoded Rec. 709; apply inverse sRGB EOTF.- "HDR" → input is HLG-encoded Rec. 2020 (BT.2100); apply inverse HLG- OETF to get scene-linear, per BT.2100 Note 5a.- "linear" → input is already scene-linear (Rec. 709 primaries); write- through unchanged. Use this for renderer/compositor output.+ "sRGB" → input is sRGB-encoded Rec. 709; apply inverse sRGB EOTF.+ "HDR" → input is HLG-encoded Rec. 2020 (BT.2100); apply inverse HLG+ OETF to get scene-linear, per BT.2100 Note 5a.+ "linear" → input is already scene-linear (Rec. 709 primaries); write+ through unchanged. Use this for renderer/compositor output.+ "linear ACEScg" → input is already scene-linear ACEScg (AP1 / D60); write+ through unchanged. Use this for ACES VFX plates.For PNG, colorspace selection does not modify pixels — PNG is deliveredsRGB-encoded and there is no PNG path for wide-gamut HDR in this node.@@ -2111,14 +2126,15 @@ class SaveImageAdvanced(IO.ComfyNode):IO.Combo.Input("bit_depth", options=["32-bit float", "16-bit float"], default="16-bit float", advanced=True),IO.Combo.Input("input_color_space",- options=["sRGB", "HDR", "linear"],+ options=["sRGB", "HDR", "linear", "linear ACEScg"],default="sRGB",advanced=True,tooltip=("Colorspace of the input tensor. The EXR is always written as scene-linear in the matching gamut.\n""sRGB — input is sRGB-encoded Rec.709; the inverse sRGB EOTF is applied.\n""HDR — input is HLG-encoded Rec.2020 (BT.2100); the inverse HLG OETF is applied to get scene-linear light.\n"- "linear — input is already scene-linear (Rec.709 primaries); written through unchanged. Use this for renderer/compositor output."+ "linear — input is already scene-linear (Rec.709 primaries); written through unchanged. Use this for renderer/compositor output.\n"+ "linear ACEScg — input is already scene-linear ACEScg (AP1 / D60); written through unchanged with ACEScg chromaticities."),),]),diff --git a/tests-unit/comfy_extras_test/image_color_space_acescg_test.py b/tests-unit/comfy_extras_test/image_color_space_acescg_test.pynew file mode 100644index 000000000..a6180725d--- /dev/null+++ b/tests-unit/comfy_extras_test/image_color_space_acescg_test.py@@ -0,0 +1,133 @@+"""ACEScg support on Convert Image Color Space and Save Image (Advanced) EXR."""++import struct+import sys+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++import folder_paths+from comfy.cli_args import args++previous_nodes = sys.modules.get("nodes")+previous_server = sys.modules.get("server")+sys.modules["nodes"] = MagicMock(MAX_RESOLUTION=16384)+sys.modules["server"] = MagicMock()+from comfy_extras import nodes_images # noqa: E402+from comfy_extras.nodes_images import ( # noqa: E402+ ImageColorSpace,+ SaveImageAdvanced,+ _encode_image,+ inject_exr_metadata,+)+for name, previous in (("nodes", previous_nodes), ("server", previous_server)):+ if previous is None:+ sys.modules.pop(name)+ else:+ sys.modules[name] = previous+++def _convert(image, source, destination):+ return ImageColorSpace.execute(image, source, destination).result[0]+++def _read_chromaticities(exr_bytes: bytes) -> tuple[float, ...]:+ pos = 8+ while pos < len(exr_bytes) and exr_bytes[pos] != 0:+ name_end = exr_bytes.index(b"\x00", pos)+ name = exr_bytes[pos:name_end].decode("latin-1")+ type_end = exr_bytes.index(b"\x00", name_end + 1)+ size = struct.unpack("<i", exr_bytes[type_end + 1:type_end + 5])[0]+ value = exr_bytes[type_end + 5:type_end + 5 + size]+ if name == "chromaticities":+ return struct.unpack("<8f", value)+ pos = type_end + 5 + size+ raise AssertionError("EXR header has no chromaticities attribute")+++# Mid-grey, SDR white, and a superwhite that must stay above 1.0, with their+# ACEScct codes from (log2(x) + 9.72) / 17.52 (Academy S-2016-001).+ACESCG = torch.tensor([[[[0.18, 1.0, 4.0]]]], dtype=torch.float32)+ACESCCT = torch.tensor([[[[0.413588, 0.554795, 0.668950]]]], dtype=torch.float32)++# AP1 primaries and ACES white (D60) as (Rx, Ry, Gx, Gy, Bx, By, Wx, Wy), from SMPTE ST 2065-1 / Academy S-2014-004.+AP1_D60_CHROMATICITIES = (0.713, 0.293, 0.165, 0.830, 0.128, 0.044, 0.32168, 0.33767)+++def test_acescct_to_acescg_decodes_reference_codes():+ out = _convert(ACESCCT, "HDR ACEScct", "linear ACEScg")++ torch.testing.assert_close(out, ACESCG, rtol=1e-5, atol=1e-5)+++def test_acescg_to_acescct_encodes_reference_codes():+ out = _convert(ACESCG, "linear ACEScg", "HDR ACEScct")++ torch.testing.assert_close(out, ACESCCT, rtol=1e-5, atol=1e-5)+++def test_acescg_round_trip_preserves_superwhites():+ linear = torch.tensor([[[[0.02, 0.18, 8.0]]]], dtype=torch.float32)++ cct = _convert(linear, "linear ACEScg", "HDR ACEScct")+ back = _convert(cct, "HDR ACEScct", "linear ACEScg")++ torch.testing.assert_close(back, linear, rtol=1e-4, atol=1e-5)+ assert back.amax().item() > 1.0+++def test_acescg_to_linear_uses_ap1_to_rec709():+ primaries = torch.tensor([[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]]], dtype=torch.float32)+ # Columns of the published AP1 → Rec.709 matrix with Bradford D60 → D65 adaptation.+ expected = torch.tensor([[[[1.70505, -0.13026, -0.02400], [-0.62179, 1.14080, -0.12897], [-0.08326, -0.01055, 1.15297]]]], dtype=torch.float32)++ out = _convert(primaries, "linear ACEScg", "linear")++ torch.testing.assert_close(out, expected, rtol=0, atol=1e-4)+++def test_same_space_acescg_is_a_no_op_on_values():+ image = torch.tensor([[[[1.5, -0.1, 0.2]]]], dtype=torch.float32)+ out = _convert(image, "linear ACEScg", "linear ACEScg")+ torch.testing.assert_close(out.cpu().float(), image)+++def test_exr_metadata_stamps_ap1_d60_for_acescg():+ raw = _encode_image(torch.ones(2, 2, 3), "exr", "32-bit float", "linear")+ tagged = inject_exr_metadata(raw, None, None, "linear ACEScg")+ chroma = _read_chromaticities(tagged)++ assert chroma == pytest.approx(AP1_D60_CHROMATICITIES)+ linear_tagged = inject_exr_metadata(raw, None, None, "linear")+ assert _read_chromaticities(linear_tagged)[6:] == pytest.approx((0.3127, 0.3290)) # D65+++def dirs(tmp_path, monkeypatch):+ saved = (folder_paths.get_output_directory(), folder_paths.get_previews_directory())+ folder_paths.set_output_directory(str(tmp_path / "output"))+ folder_paths.set_previews_directory(str(tmp_path / "previews"))+ (tmp_path / "output").mkdir()+ monkeypatch.setattr(+ nodes_images.PromptServer,+ "instance",+ SimpleNamespace(asset_manager=SimpleNamespace(enabled=True)),+ raising=False,+ )+ monkeypatch.setattr(args, "disable_metadata", False)+ monkeypatch.setattr(SaveImageAdvanced, "hidden", SimpleNamespace(prompt=None, extra_pnginfo=None), raising=False)+ yield tmp_path+ folder_paths.set_output_directory(saved[0])+ folder_paths.set_previews_directory(saved[1])+++def test_save_image_advanced_writes_acescg_chromaticities(dirs):+ images = torch.full((1, 8, 8, 3), 1.5)+ fmt = {"format": "exr", "bit_depth": "32-bit float", "input_color_space": "linear ACEScg"}+ entry = SaveImageAdvanced.execute(images, "acescg", fmt).ui["images"][0]+ path = dirs / "output" / entry["filename"]+ chroma = _read_chromaticities(path.read_bytes())++ assert chroma == pytest.approx(AP1_D60_CHROMATICITIES)