File size: 9,815 Bytes
7349148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import warnings
from typing import Optional

import torch
from jaxtyping import Float
from lxml import etree


def load_asc_cdl(cdl_path: str, device: torch.device = torch.device("cpu")) -> dict:
    """
    Loads ASC CDL parameters from an XML file.

    Parameters:
        cdl_path (str): Path to the ASC CDL XML file

    Returns:
        Dict:
            slope, offset, power, and saturation values as torch tensors
    """
    try:
        tree = etree.parse(cdl_path)
        root = tree.getroot()
    except Exception as e:
        raise ValueError(f"Error loading ASC CDL from {cdl_path}: {e}")

    # Extract SOP values
    sop_node = root.find(".//SOPNode")
    slope = torch.tensor(
        [float(x) for x in sop_node.find("Slope").text.split()], device=device
    )
    offset = torch.tensor(
        [float(x) for x in sop_node.find("Offset").text.split()], device=device
    )
    power = torch.tensor(
        [float(x) for x in sop_node.find("Power").text.split()], device=device
    )

    # Extract Saturation value
    sat_node = root.find(".//SatNode")
    saturation = torch.tensor(float(sat_node.find("Saturation").text), device=device)

    return {"slope": slope, "offset": offset, "power": power, "saturation": saturation}


def save_asc_cdl(cdl_dict: dict, cdl_path: Optional[str]):
    """
    Saves ASC CDL parameters to an XML file.

    Parameters:
        cdl_dict (dict): Dictionary containing slope, offset, power, and
            saturation values
    """
    root = etree.Element("ASC_CDL")
    sop_node = etree.SubElement(root, "SOPNode")
    etree.SubElement(sop_node, "Slope").text = " ".join(
        str(x) for x in cdl_dict["slope"].detach().cpu().numpy()
    )
    etree.SubElement(sop_node, "Offset").text = " ".join(
        str(x) for x in cdl_dict["offset"].detach().cpu().numpy()
    )
    etree.SubElement(sop_node, "Power").text = " ".join(
        str(x) for x in cdl_dict["power"].detach().cpu().numpy()
    )
    sat_node = etree.SubElement(root, "SatNode")
    etree.SubElement(sat_node, "Saturation").text = str(
        cdl_dict["saturation"].detach().cpu().numpy()
    )

    tree = etree.ElementTree(root)
    if cdl_path is not None:
        try:
            tree.write(
                cdl_path, pretty_print=True, xml_declaration=True, encoding="utf-8"
            )
        except Exception as e:
            raise ValueError(f"Error saving ASC CDL to {cdl_path}: {e}")
    else:
        return etree.tostring(
            root, pretty_print=True, xml_declaration=True, encoding="utf-8"
        ).decode("utf-8")


def apply_sop(
    img: Float[torch.Tensor, "*B C H W"],
    slope: Float[torch.Tensor, "*B C"],
    offset: Float[torch.Tensor, "*B C"],
    power: Float[torch.Tensor, "*B C"],
    clamp: bool = True,
) -> Float[torch.Tensor, "*B C H W"]:
    """
    Applies Slope, Offset, and Power adjustments.

    Parameters:
        img (torch.Tensor): Input image tensor (*B, C, H, W)
        slope (torch.Tensor): Slope per channel (*B, C)
        offset (torch.Tensor): Offset per channel (*B, C)
        power (torch.Tensor): Power per channel (*B, C)

    Returns:
        torch.Tensor: Image after SOP adjustments.
    """
    so = img * slope.unsqueeze(-1).unsqueeze(-1) + offset.unsqueeze(-1).unsqueeze(-1)
    if clamp:
        so = torch.clamp(so, min=0.0, max=1.0)
    return torch.where(
        so > 1e-7, torch.pow(so.clamp(min=1e-7), power.unsqueeze(-1).unsqueeze(-1)), so
    )


def apply_saturation(
    img: Float[torch.Tensor, "*B C H W"],
    saturation: Float[torch.Tensor, "*B"],
) -> Float[torch.Tensor, "*B C H W"]:
    """
    Applies saturation adjustment.

    Parameters:
        img (torch.Tensor): Image tensor (*B, C, H, W)
        saturation (torch.Tensor): Saturation factor (*B)

    Returns:
        torch.Tensor: Image after saturation adjustment.
    """
    # Calculate luminance using Rec. 709 coefficients
    lum = (
        0.2126 * img[..., 0, :, :]
        + 0.7152 * img[..., 1, :, :]
        + 0.0722 * img[..., 2, :, :]
    )
    lum = lum.unsqueeze(-3)  # Add channel dimension
    return lum + (img - lum) * saturation.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)


def asc_cdl_forward(
    img: Float[torch.Tensor, "*B C H W"],
    slope: Float[torch.Tensor, "*B C"],
    offset: Float[torch.Tensor, "*B C"],
    power: Float[torch.Tensor, "*B C"],
    saturation: Float[torch.Tensor, "*B"],
    clamp: bool = True,
) -> Float[torch.Tensor, "*B C H W"]:
    """
    Applies ASC CDL transformation in Fwd or FwdNoClamp mode.

    Parameters:
        img (torch.Tensor): Input image tensor (*B, C, H, W)
        slope (torch.Tensor): Slope per channel (*B, C)
        offset (torch.Tensor): Offset per channel (*B, C)
        power (torch.Tensor): Power per channel (*B, C)
        saturation (torch.Tensor): Saturation factor (*B)
        clamp (bool): If True, clamps output to [0, 1] (Fwd mode).
            If False, no clamping (FwdNoClamp mode).

    Returns:
        torch.Tensor: Transformed image tensor.
    """
    # Add warning if saturation, slope, power are below 0
    if (saturation < 0).any():
        warnings.warn("Saturation is below 0, this will result in a color shift.")
    if (slope < 0).any():
        warnings.warn("Slope is below 0, this will result in a color shift.")
    if (power < 0).any():
        warnings.warn("Power is below 0, this will result in a color shift.")

    img_batch_dim = img.shape[:-3]
    # Check if slope, offset, power, saturation have the same batch dimension
    # If they do not have any batch dimensions, add a single batch dimensions
    if slope.ndim == 1:
        slope = slope.view(*[1] * len(img_batch_dim), *slope.shape)
    if offset.ndim == 1:
        offset = offset.view(*[1] * len(img_batch_dim), *offset.shape)
    if power.ndim == 1:
        power = power.view(*[1] * len(img_batch_dim), *power.shape)
    if saturation.ndim == 0:
        saturation = saturation.view(*[1] * len(img_batch_dim), *saturation.shape)

    # Now check that the lengths are matching
    assert slope.ndim == len(img_batch_dim) + 1
    assert offset.ndim == len(img_batch_dim) + 1
    assert power.ndim == len(img_batch_dim) + 1
    assert saturation.ndim == len(img_batch_dim)

    # Apply Slope, Offset, and Power adjustments
    img = apply_sop(img, slope, offset, power, clamp=clamp)
    # print("img after sop", img.min(), img.max())
    # Apply Saturation adjustment
    img = apply_saturation(img, saturation)
    # print("img after saturation", img.min(), img.max())
    # Clamp if in Fwd mode
    if clamp:
        img = torch.clamp(img, 0.0, 1.0)
    return img


def inverse_saturation(
    img: Float[torch.Tensor, "*B C H W"],
    saturation: Float[torch.Tensor, "*B"],
) -> Float[torch.Tensor, "*B C H W"]:
    """
    Reverts saturation adjustment.

    Parameters:
        img (torch.Tensor): Image tensor (*B, C, H, W)
        saturation (torch.Tensor): Saturation factor (*B)

    Returns:
        torch.Tensor: Image after reversing saturation adjustment.
    """
    # Calculate luminance using Rec. 709 coefficients
    lum = (
        0.2126 * img[..., 0, :, :]
        + 0.7152 * img[..., 1, :, :]
        + 0.0722 * img[..., 2, :, :]
    )
    lum = lum.unsqueeze(-3)  # Add channel dimension
    return lum + (img - lum) / saturation.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)


def asc_cdl_reverse(
    img: Float[torch.Tensor, "*B C H W"],
    slope: Float[torch.Tensor, "*B C"],
    offset: Float[torch.Tensor, "*B C"],
    power: Float[torch.Tensor, "*B C"],
    saturation: Float[torch.Tensor, "*B"],
    clamp: bool = True,
) -> Float[torch.Tensor, "*B C H W"]:
    """
    Applies reverse ASC CDL transformation.

    Parameters:
        img (torch.Tensor): Transformed image tensor (*B, C, H, W)
        slope (torch.Tensor): Slope per channel (*B, C)
        offset (torch.Tensor): Offset per channel (*B, C)
        power (torch.Tensor): Power per channel (*B, C)
        saturation (torch.Tensor): Saturation factor (*B)
        clamp (bool): If True, clamps output to [0, 1].

    Returns:
        torch.Tensor: Recovered input image tensor.
    """
    # Add warning if saturation, slope, power are below 0
    if (saturation < 0).any():
        warnings.warn("Saturation is below 0, this will result in a color shift.")
    if (slope < 0).any():
        warnings.warn("Slope is below 0, this will result in a color shift.")
    if (power < 0).any():
        warnings.warn("Power is below 0, this will result in a color shift.")

    img_batch_dim = img.shape[:-3]
    # Check if slope, offset, power, saturation have the same batch dimension
    # If they do not have any batch dimensions, add a single batch dimensions
    if slope.ndim == 1:
        slope = slope.view(*[1] * len(img_batch_dim), *slope.shape)
    if offset.ndim == 1:
        offset = offset.view(*[1] * len(img_batch_dim), *offset.shape)
    if power.ndim == 1:
        power = power.view(*[1] * len(img_batch_dim), *power.shape)
    if saturation.ndim == 0:
        saturation = saturation.view(*[1] * len(img_batch_dim), *saturation.shape)

    # Now check that the lengths are matching
    assert slope.ndim == len(img_batch_dim) + 1
    assert offset.ndim == len(img_batch_dim) + 1
    assert power.ndim == len(img_batch_dim) + 1
    assert saturation.ndim == len(img_batch_dim)

    # Inverse Saturation adjustment
    img = inverse_saturation(img, saturation)
    # Inverse SOP adjustments
    if clamp:
        img = torch.clamp(img, 0.0, 1.0)
    img = torch.where(
        img > 1e-7, torch.pow(img, 1 / power.unsqueeze(-1).unsqueeze(-1)), img
    )
    img = (img - offset.unsqueeze(-1).unsqueeze(-1)) / slope.unsqueeze(-1).unsqueeze(-1)
    # Clamp if specified
    if clamp:
        img = torch.clamp(img, 0.0, 1.0)
    return img