saliacoel commited on
Commit
396d621
·
verified ·
1 Parent(s): 2282c88

Upload Salia_Recolor.py

Browse files
Files changed (1) hide show
  1. Salia_Recolor.py +354 -0
Salia_Recolor.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ComfyUI color-only port of the supplied AllIn1SpriteShader.
2
+
3
+ Install this file in ComfyUI/custom_nodes/ and restart ComfyUI.
4
+ Requires only PyTorch, already included with ComfyUI. No models or textures.
5
+
6
+ Primary node: Salia Shader Recolor (Saturation / Vividness / Punch).
7
+ Each small effect node also has an input named exactly ``strength``.
8
+ 0 = bypass, 0.5 = half blend, 1 = the full effect at its selected settings.
9
+ RGB stays RGB; RGBA stays RGBA, with alpha copied exactly. Batch supported.
10
+
11
+ Math operates on the input RGB values directly (no implicit gamma conversion).
12
+ Shader saturate() calls are retained; other values clip only at final output.
13
+ Thus chaining small nodes can clip intermediate colors, while the primary
14
+ node runs its three effects together before final clipping.
15
+
16
+ Source: user-supplied AllIn1SpriteShader, custom ApplySaturation,
17
+ ApplyVividness and PunchColor, plus the inline built-in color operations.
18
+ ComfyUI interface: https://docs.comfy.org/custom-nodes/walkthrough
19
+ """
20
+
21
+ import math
22
+ import re
23
+
24
+ import torch
25
+
26
+
27
+ def _float(default, minimum, maximum, tooltip="", step=0.01):
28
+ return ("FLOAT", {"default": default, "min": minimum, "max": maximum,
29
+ "step": step, "tooltip": tooltip})
30
+
31
+
32
+ def _strength(default=1.0):
33
+ return _float(default, 0.0, 1.0,
34
+ "0 = no effect; 0.5 = half blend; 1 = full selected effect.")
35
+
36
+
37
+ def _color(default):
38
+ return ("STRING", {"default": default,
39
+ "tooltip": "RGB color as #RRGGBB, e.g. #FFCC99. Alpha is preserved."})
40
+
41
+
42
+ def _parse_color(value):
43
+ text = str(value).strip()
44
+ if text.startswith("#"):
45
+ text = text[1:]
46
+ if not re.fullmatch(r"[0-9a-fA-F]{6}", text):
47
+ raise ValueError("Color must be six hex digits, e.g. #FFCC99.")
48
+ return tuple(int(text[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
49
+
50
+
51
+ def _luma(rgb, weights=(0.299, 0.587, 0.114)):
52
+ return (rgb * rgb.new_tensor(weights)).sum(dim=-1, keepdim=True)
53
+
54
+
55
+ def _saturation(rgb, saturation):
56
+ if saturation == 1.0:
57
+ return rgb
58
+ luminance = _luma(rgb)
59
+ return luminance + (rgb - luminance) * saturation
60
+
61
+
62
+ def _vividness(rgb, vividness):
63
+ if vividness == 0.0:
64
+ # Even at zero, the enabled shader effect ends with saturate().
65
+ return rgb.clamp(0.0, 1.0)
66
+ denominator = 1.0 + 0.72 * vividness
67
+ # The source allows negative values that make pow undefined or singular.
68
+ # Keep its valid math, and define a finite extension at those edge cases.
69
+ if abs(denominator) < 1e-4:
70
+ denominator = math.copysign(1e-4, denominator)
71
+ curved = rgb.clamp_min(0.0).pow(1.0 / denominator)
72
+ curved = torch.nan_to_num(curved, nan=0.0, posinf=1e6, neginf=0.0).clamp_max(1e6)
73
+ delta = curved - _luma(curved)
74
+ saturation = torch.linalg.vector_norm(delta, dim=-1, keepdim=True)
75
+ boost = vividness * (1.0 - saturation)
76
+ return (curved + delta * boost).clamp(0.0, 1.0)
77
+
78
+
79
+ def _punch(rgb, punch):
80
+ if punch == 0.0:
81
+ return rgb
82
+ contrast = (rgb - 0.5) * (1.0 + punch * 0.4) + 0.5
83
+ mean = contrast.mean(dim=-1, keepdim=True)
84
+ vivid = mean + (contrast - mean) * (1.0 + punch * 0.3)
85
+ # Do not clamp this interpolation: the shader extrapolates at punch > 4/3.
86
+ return rgb + (vivid - rgb) * (punch * 0.75)
87
+
88
+
89
+ def _contrast(rgb, contrast):
90
+ if contrast == 1.0:
91
+ return rgb
92
+ return (rgb - 0.5) * contrast + 0.5
93
+
94
+
95
+ def _brightness(rgb, brightness):
96
+ return rgb + brightness
97
+
98
+
99
+ def _tint(rgb, color):
100
+ return rgb * rgb.new_tensor(_parse_color(color))
101
+
102
+
103
+ def _negative(rgb):
104
+ return 1.0 - rgb
105
+
106
+
107
+ def _greyscale(rgb, luminosity, tint_color):
108
+ luminance = (_luma(rgb, (0.3, 0.59, 0.11)) + luminosity).clamp(0.0, 1.0)
109
+ return luminance * rgb.new_tensor(_parse_color(tint_color))
110
+
111
+
112
+ def _posterize(rgb, levels, gamma):
113
+ if levels < 1 or gamma <= 0:
114
+ raise ValueError("Posterize levels must be >= 1 and gamma must be > 0.")
115
+ # Negative bases are undefined for fractional shader gamma values.
116
+ quantized = torch.floor(rgb.clamp_min(0.0).pow(gamma) * levels) / levels
117
+ return quantized.pow(1.0 / gamma)
118
+
119
+
120
+ def _hsv(rgb, hue_shift, saturation, brightness):
121
+ # This is the shader's luma-based matrix, not a standard HSV conversion.
122
+ # Its rounded blue-row coefficients introduce a tiny error even at neutral.
123
+ # Make the exact neutral settings a true bypass for editing convenience.
124
+ if hue_shift % 360.0 == 0.0 and saturation == 1.0 and brightness == 1.0:
125
+ return rgb
126
+ angle = math.radians(hue_shift)
127
+ cosine = brightness * saturation * math.cos(angle)
128
+ sine = brightness * saturation * math.sin(angle)
129
+ matrix = rgb.new_tensor([
130
+ [0.299 * brightness + 0.701 * cosine + 0.168 * sine,
131
+ 0.587 * brightness - 0.587 * cosine + 0.330 * sine,
132
+ 0.114 * brightness - 0.114 * cosine - 0.497 * sine],
133
+ [0.299 * brightness - 0.299 * cosine - 0.328 * sine,
134
+ 0.587 * brightness + 0.413 * cosine + 0.035 * sine,
135
+ 0.114 * brightness - 0.114 * cosine + 0.292 * sine],
136
+ [0.299 * brightness - 0.300 * cosine + 1.250 * sine,
137
+ 0.587 * brightness - 0.588 * cosine - 1.050 * sine,
138
+ 0.114 * brightness + 0.886 * cosine - 0.203 * sine],
139
+ ])
140
+ return rgb @ matrix.T
141
+
142
+
143
+ def _solid_color(rgb, color, glow):
144
+ return rgb.new_tensor(_parse_color(color)) * glow + torch.zeros_like(rgb)
145
+
146
+
147
+ def _replace_color(rgb, source_color, new_color, tolerance, luminosity):
148
+ current = rgb.clamp(0.0, 1.0)
149
+ distance = (current - rgb.new_tensor(_parse_color(source_color))).abs().sum(-1, keepdim=True)
150
+ # Preserve the shader's unusual convention: higher tolerance is narrower.
151
+ selected = distance < (1.0 - tolerance)
152
+ luminance = (_luma(current, (0.3, 0.59, 0.11)) + luminosity).clamp(0.0, 1.0)
153
+ replacement = luminance * rgb.new_tensor(_parse_color(new_color))
154
+ return torch.where(selected, replacement, rgb)
155
+
156
+
157
+ def _check_image(image):
158
+ if not isinstance(image, torch.Tensor):
159
+ raise TypeError("Expected a ComfyUI IMAGE tensor.")
160
+ if image.ndim != 4 or image.shape[-1] not in (3, 4):
161
+ raise ValueError("Expected IMAGE shape [batch, height, width, 3 or 4] for RGB/RGBA.")
162
+ if not image.is_floating_point():
163
+ raise TypeError("Expected a floating-point IMAGE tensor, normally in the 0..1 range.")
164
+
165
+
166
+ def _run(image, stages):
167
+ """Run ordered (strength, function, keyword-arguments) stages in float32.
168
+
169
+ Row chunks bound working memory for large image/video batches. Keep the
170
+ input's dtype/device and copy alpha without performing arithmetic on it.
171
+ """
172
+ _check_image(image)
173
+ active = []
174
+ for strength, function, arguments in stages:
175
+ strength = float(strength)
176
+ if not math.isfinite(strength) or not 0.0 <= strength <= 1.0:
177
+ raise ValueError("strength must be a finite number between 0 and 1.")
178
+ if strength > 0.0:
179
+ for key, value in arguments.items():
180
+ if isinstance(value, (int, float)) and not math.isfinite(value):
181
+ raise ValueError(key + " must be finite.")
182
+ active.append((strength, function, arguments))
183
+ if not active:
184
+ return (image,)
185
+
186
+ result = image.clone()
187
+ # Up to 262144 pixels per chunk, independent of batch length.
188
+ rows = max(1, 262144 // max(1, image.shape[2]))
189
+ with torch.no_grad():
190
+ for batch in range(image.shape[0]):
191
+ for start in range(0, image.shape[1], rows):
192
+ stop = start + rows
193
+ original = image[batch:batch + 1, start:stop, :, :3]
194
+ rgb = original.to(dtype=torch.float32)
195
+ for strength, function, arguments in active:
196
+ effect = function(rgb, **arguments)
197
+ rgb = effect if strength == 1.0 else rgb + (effect - rgb) * strength
198
+ rgb = torch.nan_to_num(rgb, nan=0.0, posinf=1.0, neginf=0.0).clamp(0.0, 1.0)
199
+ result[batch:batch + 1, start:stop, :, :3] = rgb.to(dtype=image.dtype)
200
+ return (result,)
201
+
202
+
203
+ class _ColorNode:
204
+ RETURN_TYPES = ("IMAGE",)
205
+ RETURN_NAMES = ("image",)
206
+ FUNCTION = "apply"
207
+ CATEGORY = "Salia/Image/Shader Recolor"
208
+ DESCRIPTION = "Color-only shader effect. RGB/RGBA and batches supported; alpha preserved exactly."
209
+ PARAMETERS = {}
210
+ EFFECT = None
211
+
212
+ @classmethod
213
+ def INPUT_TYPES(cls):
214
+ return {"required": {"image": ("IMAGE",), **cls.PARAMETERS, "strength": _strength()}}
215
+
216
+ def apply(self, image, strength=1.0, **settings):
217
+ arguments = {key: spec[1]["default"] for key, spec in self.PARAMETERS.items()}
218
+ arguments.update(settings)
219
+ return _run(image, [(strength, self.EFFECT, arguments)])
220
+
221
+
222
+ class SaliaShaderRecolor(_ColorNode):
223
+ DESCRIPTION = (
224
+ "The shader's custom effects in their original order: saturation, vividness, punch. "
225
+ "Each *_strength is 0=bypass, 1=full selected effect. All strengths start at 0. "
226
+ "RGB/RGBA and batches supported; alpha preserved exactly."
227
+ )
228
+
229
+ @classmethod
230
+ def INPUT_TYPES(cls):
231
+ return {"required": {
232
+ "image": ("IMAGE",),
233
+ "saturation": _float(1.3, -10.0, 20.0, "Shader saturation: 1 = neutral; 0 = greyscale."),
234
+ "saturation_strength": _strength(0.0),
235
+ "vividness": _float(1.0, -10.0, 20.0, "Shader gamma plus vibrance: 0 = neutral. Negative extremes are safeguarded."),
236
+ "vividness_strength": _strength(0.0),
237
+ "punch": _float(1.0, 0.0, 2.0, "Shader Vivid Punch: 0 = neutral; higher = more contrast and color punch."),
238
+ "punch_strength": _strength(0.0),
239
+ }}
240
+
241
+ def apply(self, image, saturation=1.3, saturation_strength=0.0,
242
+ vividness=1.0, vividness_strength=0.0, punch=1.0, punch_strength=0.0):
243
+ return _run(image, [
244
+ (saturation_strength, _saturation, {"saturation": saturation}),
245
+ (vividness_strength, _vividness, {"vividness": vividness}),
246
+ (punch_strength, _punch, {"punch": punch}),
247
+ ])
248
+
249
+
250
+ class SaliaShaderSaturation(_ColorNode):
251
+ PARAMETERS = {"saturation": _float(1.3, -10.0, 20.0, "1 = unchanged; 0 = greyscale.")}
252
+ EFFECT = staticmethod(_saturation)
253
+
254
+
255
+ class SaliaShaderVividness(_ColorNode):
256
+ PARAMETERS = {"vividness": _float(1.0, -10.0, 20.0, "0 = neutral. Gamma plus vibrance, exactly as in the shader for valid inputs.")}
257
+ EFFECT = staticmethod(_vividness)
258
+
259
+
260
+ class SaliaShaderPunch(_ColorNode):
261
+ PARAMETERS = {"punch": _float(1.0, 0.0, 2.0, "0 = unchanged. Adds the shader's contrast and saturation punch.")}
262
+ EFFECT = staticmethod(_punch)
263
+
264
+
265
+ class SaliaShaderContrast(_ColorNode):
266
+ PARAMETERS = {"contrast": _float(1.0, 0.0, 6.0, "1 = unchanged; 0 = flat mid-grey.")}
267
+ EFFECT = staticmethod(_contrast)
268
+
269
+
270
+ class SaliaShaderBrightness(_ColorNode):
271
+ PARAMETERS = {"brightness": _float(0.0, -1.0, 1.0, "Additive brightness. 0 = unchanged.")}
272
+ EFFECT = staticmethod(_brightness)
273
+
274
+
275
+ class SaliaShaderTint(_ColorNode):
276
+ PARAMETERS = {"color": _color("#FFFFFF")}
277
+ EFFECT = staticmethod(_tint)
278
+ DESCRIPTION = "Multiplicative main tint or warm tint from the shader. White is neutral; alpha stays unchanged."
279
+
280
+
281
+ class SaliaShaderNegative(_ColorNode):
282
+ EFFECT = staticmethod(_negative)
283
+
284
+
285
+ class SaliaShaderGreyscale(_ColorNode):
286
+ PARAMETERS = {"luminosity": _float(0.0, -1.0, 1.0), "tint_color": _color("#FFFFFF")}
287
+ EFFECT = staticmethod(_greyscale)
288
+
289
+
290
+ class SaliaShaderPosterize(_ColorNode):
291
+ PARAMETERS = {
292
+ "levels": ("INT", {"default": 8, "min": 1, "max": 100,
293
+ "tooltip": "Quantization steps per channel, not total palette size."}),
294
+ "gamma": _float(0.75, 0.1, 10.0),
295
+ }
296
+ EFFECT = staticmethod(_posterize)
297
+
298
+
299
+ class SaliaShaderHSV(_ColorNode):
300
+ PARAMETERS = {
301
+ "hue_shift": _float(0.0, 0.0, 360.0, "Hue angle in degrees; shader matrix, not standard HSV.", 1.0),
302
+ "saturation": _float(1.0, 0.0, 2.0),
303
+ "brightness": _float(1.0, 0.0, 2.0),
304
+ }
305
+ EFFECT = staticmethod(_hsv)
306
+
307
+
308
+ class SaliaShaderSolidColor(_ColorNode):
309
+ PARAMETERS = {"color": _color("#FFFFFF"), "glow": _float(1.0, 1.0, 100.0)}
310
+ EFFECT = staticmethod(_solid_color)
311
+ DESCRIPTION = "Shader hit-color blend. strength mixes toward color * glow; output clips to 0..1, without bloom."
312
+
313
+
314
+ class SaliaShaderReplaceColor(_ColorNode):
315
+ PARAMETERS = {
316
+ "source_color": _color("#FF0000"),
317
+ "new_color": _color("#FFFF00"),
318
+ "tolerance": _float(0.25, 0.0, 1.0, "Shader rule: HIGHER selects FEWER colors. Distance must be < 1 - tolerance."),
319
+ "luminosity": _float(0.0, 0.0, 1.0, "Replacement color is multiplied by source luminance + this amount."),
320
+ }
321
+ EFFECT = staticmethod(_replace_color)
322
+
323
+
324
+ NODE_CLASS_MAPPINGS = {
325
+ "SaliaRecolor": SaliaRecolor,
326
+ "SaliaSaturation": SaliaSaturation,
327
+ "SaliaVividness": SaliaVividness,
328
+ "SaliaPunch": SaliaPunch,
329
+ "SaliaContrast": SaliaContrast,
330
+ "SaliaBrightness": SaliaBrightness,
331
+ "SaliaTint": SaliaTint,
332
+ "SaliaNegative": SaliaNegative,
333
+ "SaliaGreyscale": SaliaGreyscale,
334
+ "SaliaPosterize": SaliaPosterize,
335
+ "SaliaHSV": SaliaHSV,
336
+ "SaliaSolidColor": SaliaSolidColor,
337
+ "SaliaReplaceColor": SaliaReplaceColor,
338
+ }
339
+
340
+ NODE_DISPLAY_NAME_MAPPINGS = {
341
+ "SaliaRecolor": "Salia Recolor (Saturation / Vividness / Punch)",
342
+ "SaliaSaturation": "Salia Saturation",
343
+ "SaliaVividness": "Salia Vividness",
344
+ "SaliaPunch": "Salia Vivid Punch",
345
+ "SaliaContrast": "Salia Contrast",
346
+ "SaliaBrightness": "Salia Brightness",
347
+ "SaliaTint": "Salia Tint / Warm Tint",
348
+ "SaliaNegative": "Salia Negative",
349
+ "SaliaGreyscale": "Salia Greyscale / Tint",
350
+ "SaliaPosterize": "Salia Posterize",
351
+ "SaliaHSV": "Salia Hue / Saturation / Brightness",
352
+ "SaliaSolidColor": "Salia Solid Color / Hit Color",
353
+ "SaliaReplaceColor": "Salia Replace Color",
354
+ }