-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpostprocess.py
More file actions
2689 lines (2423 loc) · 121 KB
/
Copy pathpostprocess.py
File metadata and controls
2689 lines (2423 loc) · 121 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""RedNode post processing: one grading chain instead of a shelf of little nodes.
Every effect here is an independent implementation of a standard, long-published
image operation, written from the maths rather than adapted from any pack:
denoise bilateral filter (Tomasi & Manduchi, 1998): a Gaussian spatial weight
multiplied by a Gaussian weight on the intensity difference, so flat
areas average and edges do not
colour brightness as a gain, contrast around mid grey, saturation as a lerp
between the luma and the colour
clarity unsharp mask at a large radius (local contrast), composited through a
soft light blend and gated by a luminance range, the classic
"blend if" limiter
sharpen unsharp mask, or Richardson-Lucy deconvolution (Richardson 1972,
Lucy 1974) against a Gaussian point spread function
bloom luminance threshold with a soft knee, blur, then screen composite
halation the same threshold, blurred wider and tinted warm, added not screened:
film's red-sensitive layer scattering light back through the base
distortion radial remap of the sampling grid, barrel or pincushion
aberration per-channel geometric offset, radial and/or axis-aligned
grain value noise at a chosen scale, mixed mono or coloured
vignette radial luminance falloff
dof depth-weighted defocus: the circle of confusion grows with distance
from the focal plane, so a depth map drives a per-pixel blur
haze aerial perspective: distance fades towards a haze colour and loses
contrast, which is most of what makes a background read as far away
light wrap bright regions bleed onto the darker pixels beside them, the way a
real lens flares across an edge
diffusion the pro-mist filter: a soft veil over the whole frame that lifts the
blacks slightly instead of only glowing the highlights
rolloff a soft shoulder near white so highlights compress instead of clipping
ORDER OF THE CHAIN. The rule compositors use is that lensing goes LAST, in the
order light actually meets a physical camera, so the chain is:
1. repair and grade the picture denoise, colour, clarity, sharpen
2. the air in front of the lens haze
3. the lens, in light-path order distortion (glass geometry), depth of field
(focus), chromatic aberration (dispersion),
bloom (veiling glare), light wrap, diffusion
(front filter), vignette (cos^4 falloff)
4. the film behind it halation (base reflection), film stock
(the characteristic curve), highlight
roll-off (a shoulder by hand), grain (emulsion)
Two consequences are worth stating because they are easy to get backwards:
sharpening runs BEFORE depth of field, or it re-sharpens what the defocus just
blurred; and grain runs after the vignette, because grain is the emulsion itself
and the vignette is light falling off before it ever reaches the film.
Which effects to offer was informed by skatardude10's ComfyUI-Optical-Realism
(github.com/skatardude10/ComfyUI-Optical-Realism), a good survey of the optical
phenomena worth simulating. The feature list is the debt; the implementations
here are written independently from the underlying optics, as above.
Images are ComfyUI IMAGE tensors: [B, H, W, C] float in 0..1.
"""
import base64
from .overrides import env as _env
import inspect
import io as _io
import json
import math
import os
import random as _random
import time
import torch
import torch.nn.functional as F
POST_TYPE = "KREA2_POST"
# The default for every control is the value the pack ships with, chosen to match
# a grade the author had already tuned across several packs' nodes.
DEFAULTS = {
"denoise": {"on": False, "sigma": 0.997, "threshold": 0.051, "radius_multiplier": 1.149,
"strength": 1.0},
# THE COLOUR CARD: the tone and colour grade. Every dial after black_point is a
# no-op at its default, so an old saved chain grades as it did. `awb` is the
# Measure button's estimator, never an argument.
"color": {"on": False, "brightness": 1.0, "contrast": 1.0, "saturation": 1.0,
"temperature": 0.0, "tint": 0.0, "black_point": 0.0,
"exposure": 0.0, "shadows": 0.0, "highlights": 0.0, "local_hdr": 0.0,
"lift": 0.0, "gamma": 1.0, "gain": 1.0, "vibrance": 0.0,
"split_shadow": 0.0, "split_highlight": 0.0, "split_balance": 0.0,
"awb": "shades_of_grey"},
# MATCH A REFERENCE: the picture's colour statistics moved onto a reference
# picture's (per-channel mean and spread), with skin held back so faces keep
# their hue. source names where the reference comes from: a Workspace tab
# for the wireless node, the reference input for the standalone one.
"match": {"on": False, "source": "moodboard", "method": "adain", "strength": 1.0,
"skin_protect": 0.5, "ref_file": ""},
# A LUT: a .cube file from models/luts, trilinear, strength past 1 overdrives
"lut": {"on": False, "file": "", "strength": 1.0, "log": False},
# THE SKIN CARD: grading that lands on skin and nowhere else. The mask is built
# in Lab from colour rules crossed with RGB rules, minus a protect term for eyes,
# teeth, lips and fine detail, minus busy pattern (printed cloth, knitwear, hair)
# by local variance, and ANDed with the subject mask when the chain has one.
# Every EDIT dial ships at 0, so the card on and untouched is a passthrough.
"skin": {"on": False, "subject": "auto", "show": "off", "protect": 1.0,
"pattern_reject": 0.6, "mask_soften": 3.0,
"de_yellow": 0.0, "rosy": 0.0, "brighten": 0.0, "shadow_lift": 0.0,
"evenness": 0.0, "smooth": 0.0, "texture_preserve": 0.55,
"saturation": 0.0},
"clarity": {"on": False, "radius": 3, "offset": 2.0, "strength": 0.4,
"blend_mode": "soft light", "blend_if_dark": 50, "blend_if_light": 205,
"dark_intensity": 0.4, "light_intensity": 0.0},
# SHARPEN: three modes. lucy and unsharp use the four dials above; the detail
# band uses amount and radius plus the guards below, which is what stops a hard
# setting from haloing, speckling or crunching an AI frame.
"sharpen": {"on": False, "mode": "lucy", "iterations": 1, "kernel_size": 3,
"amount": 0.5, "radius": 1.0,
"edge_preserve": 0.02, "noise_gate": 0.055, "shadow_protect": 0.35,
"highlight_protect": 0.5, "fringe_hold": 0.5, "skin_protect": 0.0},
# THE DEPTH CARD: not an effect, the settings for the depth map the two depth
# effects share. Which estimator, which Depth Anything V2 checkpoint, and the
# working resolution. "auto" is whichever is installed, and its own default file.
"depth": {"on": False, "estimator": "auto", "model": "auto", "resolution": 512},
# THE MASK CARD: settings, not an effect. Any card can be limited to the
# subject or the background; this is where the mask comes from (the pack's
# own auto-mask, or the mask wired into the standalone node) and how soft
# its edge is, in pixels.
"mask": {"on": False, "source": "auto", "feather": 12},
"dof": {"on": False, "focus": 0.35, "range": 0.15, "blur": 6.0, "flip_depth": False},
# RELIGHT: a new key light over the depth map's relief. Azimuth is where it
# comes from (0 right, 90 top, 180 left, 270 below), elevation how high it
# sits (0 grazing, 90 straight on). Ambient is what the unlit side keeps.
"relight": {"on": False, "azimuth": 45.0, "elevation": 35.0, "intensity": 0.6,
"warmth": 0.0, "ambient": 0.6, "softness": 0.5, "shadow": 0.4,
"relief": 1.0, "flip_depth": False},
"haze": {"on": False, "strength": 0.35, "start": 0.45, "lift": 0.12,
"flip_depth": False},
"light_wrap": {"on": False, "strength": 0.4, "radius": 2.5, "threshold": 0.7},
"diffusion": {"on": False, "strength": 0.25, "radius": 4.0, "black_lift": 0.03},
"rolloff": {"on": False, "knee": 0.75, "strength": 0.6},
"bloom": {"on": False, "intensity": 1.16, "threshold": 0.62, "smoothing": 0.23,
"radius_multiplier": 1.0, "saturation": 0.77, "exposure": 1.0},
# THE FILM CARD: a named stock's response (toe, shoulder and contrast per channel,
# base fog, saturation, shadow and highlight colour). "none" is a passthrough.
# The Wratten filter is for the black and white stocks.
"film": {"on": False, "stock": "none", "wratten": "none", "strength": 1.0,
"fade": 0.0},
"halation": {"on": False, "strength": 0.35, "threshold": 0.75, "radius": 3.0,
"warmth": 0.7},
# LENS DISTORTION: `lens` is which named lens filled the dials (panel memory, never
# an argument); scale_by_size sizes the pixel amounts against a 1024 short edge.
"distortion": {"on": False, "amount": 0.0, "edge_softness": 0.0,
"lens": "custom", "scale_by_size": False},
"aberration": {"on": False, "amount": 0.47, "red_shift": 1.0, "green_shift": -1.0,
"blue_shift": -3.0, "direction": "horizontal", "scale_by_size": False},
"grain": {"on": False, "power": 0.09, "scale": 1.0, "saturation": 1.0, "seed": 0,
"softness": 0.0},
# VIGNETTE: two falloff laws. "smooth" is the shipped one, a flat centre and a
# soft ring near the edge; "cos4" is what real glass does, cosine to the fourth
# of the field angle, normalised so the corner lands at the same darkness either
# way and Amount means one thing. Roundness runs from the frame's own oval to a
# true circle; the ring colour lands in the falloff only, as a gain that changes
# colour without changing brightness.
"vignette": {"on": False, "amount": 0.10, "feather": 0.6, "law": "smooth",
"roundness": 0.0, "tint_hue": 30.0, "tint_amount": 0.0},
}
BLEND_MODES = ("soft light", "overlay", "normal", "linear light")
SETTINGS_CARDS = ("depth", "mask")
LIMITS = ("off", "subject", "background")
MATCH_METHODS = ("adain", "linear")
MATCH_SOURCES = ("file", "moodboard", "subject", "scene", "i2i", "wired")
MASK_SOURCES = ("auto", "wired")
# every effect can be limited to the subject or the background; the settings
# cards cannot, they are not effects
for _n, _blk in DEFAULTS.items():
if _n not in SETTINGS_CARDS:
_blk["limit"] = "off"
# the Depth card's choices: panel keys to the estimator node each one means, and
# the Depth Anything V2 checkpoints by their short names
DEPTH_ESTIMATORS = {
"depth_anything_v2": "DepthAnythingV2Preprocessor",
"depth_anything": "DepthAnythingPreprocessor",
"midas": "MiDaS-DepthMapPreprocessor",
"zoe": "Zoe-DepthMapPreprocessor",
}
DEPTH_MODELS = {"vitg": "depth_anything_v2_vitg.pth", "vitl": "depth_anything_v2_vitl.pth",
"vitb": "depth_anything_v2_vitb.pth", "vits": "depth_anything_v2_vits.pth"}
SHARPEN_MODES = ("lucy", "unsharp", "band")
VIGNETTE_LAWS = ("smooth", "cos4")
SKIN_SUBJECT = ("off", "auto", "always")
SKIN_SHOWS = ("off", "mask", "over")
# cards that want the subject mask for their own working, not only for a Limit
MASK_EFFECTS = ("relight", "skin")
# keys a chain instance carries for the panel's sake that are NOT arguments to the
# effect function: the switch, the random ranges, the Limit row, the instance's
# identity, the Match card's dropped picture, the lens picker's memory and the
# colour card's auto white balance estimator
NON_ARG_KEYS = ("on", "rand", "limit", "fx", "id", "ref_file", "lens", "awb")
AWB_METHODS = ("grey_world", "white_patch", "shades_of_grey", "grey_edge")
CA_DIRECTIONS = ("horizontal", "vertical", "radial")
FILM_PIVOT = 0.18 # scene mid grey, in linear light
# What each lens filter passes to a black and white stock, normalised to sum to 1 so
# a grey card reads the same through every filter.
WRATTEN = {
"none": (0.299, 0.587, 0.114),
"yellow8": (0.42, 0.52, 0.06),
"orange16": (0.55, 0.42, 0.03),
"red25": (0.80, 0.19, 0.01),
"green11": (0.18, 0.74, 0.08),
}
# Readings of each stock's character, not measurements: gamma is the straight
# line's slope, toe and shoulder how hard the two ends flatten, fog the base density
# in linear light, sat the colour, and the offsets the tint the shadows and the
# highlights carry.
FILM_STOCKS = {
"portra400": {
"label": "Portra 400", "bw": False,
"gamma": (0.92, 0.94, 0.90), "toe": (0.085, 0.080, 0.075),
"shoulder": (0.150, 0.140, 0.125), "fog": 0.008, "sat": 0.96,
"shadow_off": (-0.004, 0.000, 0.010), "high_off": (0.014, 0.006, -0.008)},
"ektar100": {
"label": "Ektar 100", "bw": False,
"gamma": (1.10, 1.08, 1.12), "toe": (0.050, 0.050, 0.045),
"shoulder": (0.095, 0.095, 0.085), "fog": 0.004, "sat": 1.18,
"shadow_off": (0.000, 0.000, 0.012), "high_off": (0.008, 0.000, -0.004)},
"gold200": {
"label": "Gold 200", "bw": False,
"gamma": (0.98, 0.96, 0.92), "toe": (0.070, 0.070, 0.065),
"shoulder": (0.130, 0.130, 0.120), "fog": 0.010, "sat": 1.12,
"shadow_off": (0.006, 0.002, -0.006), "high_off": (0.020, 0.010, -0.018)},
"fuji400h": {
"label": "Fuji Pro 400H", "bw": False,
"gamma": (0.88, 0.90, 0.92), "toe": (0.100, 0.095, 0.090),
"shoulder": (0.170, 0.160, 0.150), "fog": 0.010, "sat": 0.92,
"shadow_off": (-0.006, 0.004, 0.012), "high_off": (0.004, 0.008, 0.004)},
"superia400": {
"label": "Superia 400", "bw": False,
"gamma": (0.96, 1.00, 0.96), "toe": (0.080, 0.080, 0.075),
"shoulder": (0.140, 0.140, 0.130), "fog": 0.010, "sat": 1.06,
"shadow_off": (-0.008, 0.008, 0.004), "high_off": (0.004, 0.002, -0.004)},
"ektachrome100": {
"label": "Ektachrome 100 (slide)", "bw": False,
"gamma": (1.25, 1.22, 1.25), "toe": (0.030, 0.030, 0.028),
"shoulder": (0.200, 0.200, 0.190), "fog": 0.002, "sat": 1.12,
"shadow_off": (0.000, 0.000, 0.008), "high_off": (-0.002, 0.000, 0.006)},
"cinestill800t": {
"label": "Cinestill 800T", "bw": False,
"gamma": (0.95, 0.95, 0.98), "toe": (0.070, 0.070, 0.060),
"shoulder": (0.135, 0.135, 0.115), "fog": 0.012, "sat": 1.05,
"shadow_off": (-0.010, -0.002, 0.024), "high_off": (0.010, 0.000, 0.006)},
"instant600": {
"label": "Instant film", "bw": False,
"gamma": (0.80, 0.80, 0.78), "toe": (0.140, 0.140, 0.130),
"shoulder": (0.220, 0.220, 0.200), "fog": 0.012, "sat": 0.9,
"shadow_off": (-0.012, 0.006, 0.014), "high_off": (0.018, 0.010, -0.012)},
"trix400": {
"label": "Tri-X 400", "bw": True,
"gamma": (1.12, 1.12, 1.12), "toe": (0.060, 0.060, 0.060),
"shoulder": (0.125, 0.125, 0.125), "fog": 0.012, "sat": 1.0,
"shadow_off": (0.002, 0.000, -0.002), "high_off": (0.002, 0.001, -0.002)},
"hp5": {
"label": "HP5 Plus 400", "bw": True,
"gamma": (0.98, 0.98, 0.98), "toe": (0.085, 0.085, 0.085),
"shoulder": (0.165, 0.165, 0.165), "fog": 0.010, "sat": 1.0,
"shadow_off": (0.000, 0.000, 0.000), "high_off": (0.000, 0.000, 0.000)},
"acros100": {
"label": "Acros 100", "bw": True,
"gamma": (1.05, 1.05, 1.05), "toe": (0.050, 0.050, 0.050),
"shoulder": (0.100, 0.100, 0.100), "fog": 0.006, "sat": 1.0,
"shadow_off": (0.000, 0.000, 0.000), "high_off": (0.000, 0.000, 0.000)},
}
FILM_STOCK_NAMES = ("none",) + tuple(FILM_STOCKS)
WRATTEN_NAMES = tuple(WRATTEN)
# the lens picker's names; the values live in web/rednode_ws_tables.js (LENS_PRESETS)
LENS_NAMES = ("custom", "ultrawide_14", "wide_24", "reportage_35", "normal_50",
"portrait_85", "long_135", "vintage_55", "anamorphic_40",
"phone_main", "phone_ultrawide")
# the chain order: repair, tone, detail, light, lens
ORDER = ("denoise", "color", "match", "lut", "skin", "clarity", "sharpen", # repair and grade
"relight", # light
"haze", # the air
"distortion", "dof", "aberration", "bloom", # the lens...
"light_wrap", "diffusion", "vignette", # ...and its glare
"halation", "film", "rolloff", "grain") # the film
# effects that cannot run without a depth map wired into the node
DEPTH_EFFECTS = ("dof", "haze", "relight")
# ---------------------------------------------------------------------------
# helpers
def _nchw(img):
return img.permute(0, 3, 1, 2)
def _nhwc(t):
return t.permute(0, 2, 3, 1)
def _luma(t):
"""Rec.709 luminance of an NCHW tensor, kept as a 1-channel map."""
r, g, b = t[:, 0:1], t[:, 1:2], t[:, 2:3]
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def _gauss_kernel(sigma, device, dtype):
radius = max(1, int(round(sigma * 3)))
x = torch.arange(-radius, radius + 1, device=device, dtype=dtype)
k = torch.exp(-(x ** 2) / (2 * sigma * sigma))
return k / k.sum()
def gaussian_blur(t, sigma):
"""Separable Gaussian blur on NCHW, reflect-padded so edges do not darken."""
if sigma <= 0:
return t
k = _gauss_kernel(sigma, t.device, t.dtype)
r = (k.numel() - 1) // 2
c = t.shape[1]
kx = k.view(1, 1, 1, -1).expand(c, 1, 1, -1)
ky = k.view(1, 1, -1, 1).expand(c, 1, -1, 1)
# reflect padding needs the pad smaller than the side; fall back to replicate
mode = "reflect" if r < min(t.shape[2], t.shape[3]) else "replicate"
t = F.pad(t, (r, r, 0, 0), mode=mode)
t = F.conv2d(t, kx, groups=c)
t = F.pad(t, (0, 0, r, r), mode=mode)
return F.conv2d(t, ky, groups=c)
def _box(t, r):
"""Mean of an NCHW tensor over a (2r+1) square window, replicate padded.
Cumulative sums, so the cost does not grow with the radius: local statistics
over 4 percent of the short edge are 80 px across at 4K, far too wide for a
convolution. The global mean comes out before the sums and goes back after,
which keeps float32 accurate along a long row.
"""
r = int(r)
if r < 1:
return t
k = 2 * r + 1
mu = t.mean()
x = F.pad(t - mu, (r, r, r, r), mode="replicate")
cs = F.pad(x.cumsum(-1), (1, 0, 0, 0))
x = cs[..., k:] - cs[..., :-k]
cs = F.pad(x.cumsum(-2), (0, 0, 1, 0))
x = cs[..., k:, :] - cs[..., :-k, :]
return x / float(k * k) + mu
def _guided(guide, src, r, eps):
"""Guided filter (He, Sun and Tang, 2010): a low pass that follows the guide's
edges. Where the guide is flat the output is the local mean; across an edge
much stronger than eps (in the guide's units squared) the edge passes through."""
mean_g = _box(guide, r)
mean_s = _box(src, r)
var_g = (_box(guide * guide, r) - mean_g * mean_g).clamp_min(0.0)
cov = _box(guide * src, r) - mean_g * mean_s
a = cov / (var_g + float(eps))
b = mean_s - a * mean_g
return _box(a, r) * guide + _box(b, r)
def _smoothstep(x, lo=0.0, hi=1.0):
"""0 below lo, 1 above hi, the smooth Hermite ramp between."""
t = ((x - lo) / max(1e-6, float(hi) - float(lo))).clamp(0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
def _clamp01(t):
return t.clamp(0.0, 1.0)
# ---------------------------------------------------------------------------
# effects
# Denoise is the one effect whose cost runs away with its settings: the window is
# (2r+1) squared passes over the whole picture, and r follows sigma and the radius
# multiplier together. Measured on a 1024 by 1024 frame: 0.1 s at the shipped
# defaults, 0.55 s at sigma 2, 4.5 s at both sliders maxed. That is slow, not
# broken, so nothing here is capped: capping would quietly change a grade somebody
# had already tuned. It says so instead, once per set of settings, because four
# seconds with no explanation reads as a hang.
_DENOISE_SAID = None
def _denoise_notice(radius, pixels):
global _DENOISE_SAID
taps = (2 * radius + 1) ** 2
if taps < 400:
return
key = (taps, pixels)
if key == _DENOISE_SAID:
return
_DENOISE_SAID = key
secs = taps * pixels / 8.6e8 # from the measurement above
print(f"[RedNode Post] denoise is set wide (radius {radius}, {taps} passes over "
f"{pixels // 1000} K pixels), so expect around {secs:.0f} s. Lower sigma or "
"the radius multiplier if that is not worth it.", flush=True)
def denoise(img, sigma=0.997, threshold=0.051, radius_multiplier=1.149, strength=1.0):
"""Bilateral filter: average neighbours that are both CLOSE and SIMILAR.
sigma sets how far the averaging reaches, threshold how different a pixel may
be before it stops contributing (so edges survive), and radius_multiplier
trades speed for reach by widening the window around that sigma.
"""
k = max(0.0, min(1.0, float(strength)))
if sigma <= 0 or threshold <= 0 or k <= 0:
return img
t = _nchw(img)
radius = max(1, int(round(sigma * radius_multiplier * 2)))
_denoise_notice(radius, t.shape[-1] * t.shape[-2])
guide = _luma(t)
two_ss = 2.0 * sigma * sigma
two_tt = 2.0 * threshold * threshold
acc = torch.zeros_like(t)
wsum = torch.zeros_like(guide)
pad = F.pad(t, (radius,) * 4, mode="replicate")
gpad = F.pad(guide, (radius,) * 4, mode="replicate")
h, w = t.shape[2], t.shape[3]
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
spatial = math.exp(-(dx * dx + dy * dy) / two_ss)
if spatial < 1e-4:
continue
shifted = pad[:, :, radius + dy:radius + dy + h, radius + dx:radius + dx + w]
gshift = gpad[:, :, radius + dy:radius + dy + h, radius + dx:radius + dx + w]
wr = torch.exp(-((gshift - guide) ** 2) / two_tt) * spatial
acc += shifted * wr
wsum += wr
out = acc / wsum.clamp_min(1e-6)
if k < 1.0:
out = t + (out - t) * k # strength: how much of the smoothing lands
return _nhwc(out)
def color(img, brightness=1.0, contrast=1.0, saturation=1.0, temperature=0.0,
tint=0.0, black_point=0.0, exposure=0.0, shadows=0.0, highlights=0.0,
local_hdr=0.0, lift=0.0, gamma=1.0, gain=1.0, vibrance=0.0,
split_shadow=0.0, split_highlight=0.0, split_balance=0.0):
"""The tone and colour grade, in this order: exposure in stops (linear light),
brightness, contrast on mid grey, white balance with the frame's brightness put
back, shadows and highlights (multiplicative, so black stays black), local HDR
(the big tonal swing flattened in linear light, fine detail kept), lift / gamma /
gain, split tone on a luma-neutral warm-cool axis, vibrance (the least saturated
colours first, skin held), saturation, black point. Each step is skipped at its
default.
"""
t = _nchw(img)
ev = float(exposure)
if ev:
t = _linear_to_srgb(_srgb_to_linear(_clamp01(t)) * (2.0 ** ev))
t = t * float(brightness)
t = (t - 0.5) * float(contrast) + 0.5
if temperature or tint:
warm = float(temperature) * 0.5
gm = float(tint) * 0.5
wb = torch.tensor([1.0 + warm, 1.0 + gm, 1.0 - warm],
device=t.device, dtype=t.dtype).view(1, 3, 1, 1)
before = float(_luma(t).mean())
t = t * wb
after = float(_luma(t).mean())
if before > 1e-6 and after > 1e-6:
t = t * max(0.25, min(4.0, before / after))
sh, hl = float(shadows), float(highlights)
if sh or hl:
y = _clamp01(_luma(t))
if sh:
t = t * (1.0 + sh * 0.8 * (1.0 - y) ** 2)
if hl:
# a bump on the bright half, u^2 (1 - u), that is 0 at mid grey AND at white,
# so a white background stays white; the gains keep the curve rising
u = ((y - 0.5) * 2.0).clamp(0.0, 1.0)
k_hl = 1.0 if hl < 0 else 0.5
y2 = y + hl * k_hl * u * u * (1.0 - u)
t = t * (y2 / y.clamp_min(1e-4))
a = max(0.0, min(1.0, float(local_hdr)))
if a:
lin = _srgb_to_linear(_clamp01(t))
lum = _luma(lin).clamp_min(1e-4)
r = max(1, round(0.04 * min(t.shape[2], t.shape[3])))
base = _box(_box(lum, r), r).clamp_min(1e-4)
g = ((base.mean() / base) ** (a * 0.5)).clamp(0.25, 4.0)
t = _linear_to_srgb(_clamp01(lin * g))
lf, gm_, gn = float(lift), float(gamma), float(gain)
if lf or gm_ != 1.0 or gn != 1.0:
x = _clamp01(t)
t = (gn * (x + lf * (1.0 - x))).clamp_min(0.0) ** (1.0 / max(0.05, gm_))
ss, shi = float(split_shadow), float(split_highlight)
if ss or shi:
y = _clamp01(_luma(t))
pivot = 0.5 + float(split_balance) * 0.3
w_hi = _smoothstep(y, pivot - 0.25, pivot + 0.25)
w_lo = (1.0 - w_hi) * (y / 0.06).clamp(0.0, 1.0)
axis = torch.tensor([0.8596, -0.1404, -1.1404], device=t.device,
dtype=t.dtype).view(1, 3, 1, 1)
t = t + axis * 0.12 * (w_lo * ss + w_hi * shi)
vib = float(vibrance)
if vib:
x = _clamp01(t)
sat = x.amax(1, keepdim=True) - x.amin(1, keepdim=True)
k = vib * (1.0 - sat) ** 2 * (1.0 - 0.6 * _skin_weight(x))
lu = _luma(t)
t = lu + (t - lu) * (1.0 + k)
if saturation != 1.0:
t = _luma(t) + (t - _luma(t)) * float(saturation)
bp = float(black_point)
if bp:
# positive crushes the blacks, negative lifts them into a faded, milky look
t = (t - bp) / max(1e-3, 1.0 - bp) if bp > 0 else t * (1.0 + bp) - bp
return _clamp01(_nhwc(t))
# ---------------------------------------------------------------------------
# colour spaces for the match card's skin hold and the LUT's log toggle
def _srgb_to_linear(t):
return torch.where(t <= 0.04045, t / 12.92, ((t.clamp(min=0) + 0.055) / 1.055) ** 2.4)
def _linear_to_srgb(t):
return torch.where(t <= 0.0031308, t * 12.92, 1.055 * t.clamp(min=0) ** (1 / 2.4) - 0.055)
_LAB_D = 6.0 / 29.0
def _rgb_to_lab(t):
"""NCHW sRGB 0..1 to CIE Lab (D65), as three N1HW planes."""
lin = _srgb_to_linear(t.clamp(0, 1))
r, g, b = lin[:, 0:1], lin[:, 1:2], lin[:, 2:3]
x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047
y = 0.2126729 * r + 0.7151522 * g + 0.0721750 * b
z = (0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / 1.08883
d, d3 = _LAB_D, _LAB_D ** 3
f = lambda u: torch.where(u > d3, u.clamp_min(0) ** (1.0 / 3.0), # noqa: E731
u / (3 * d * d) + 4.0 / 29.0)
fx, fy, fz = f(x.clamp_min(0)), f(y.clamp_min(0)), f(z.clamp_min(0))
return 116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)
def _lab_to_rgb(L, a, b):
"""CIE Lab (D65) planes back to NCHW sRGB 0..1."""
fy = (L + 16.0) / 116.0
fx = fy + a / 500.0
fz = fy - b / 200.0
d = _LAB_D
g = lambda u: torch.where(u > d, u ** 3, 3 * d * d * (u - 4.0 / 29.0)) # noqa: E731
x, y, z = 0.95047 * g(fx), g(fy), 1.08883 * g(fz)
r = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z
gg = -0.9692660 * x + 1.8760108 * y + 0.0415560 * z
bb = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z
return _clamp01(_linear_to_srgb(torch.cat([r, gg, bb], 1)))
def _rgb_to_hsv(t):
"""NCHW in 0..1 to (h, s, v), each N1HW, h in turns."""
r, g, b = t[:, 0:1], t[:, 1:2], t[:, 2:3]
mx = t.max(1, keepdim=True)[0]
mn = t.min(1, keepdim=True)[0]
d = mx - mn
eps = 1e-8
s_ = torch.where(mx > eps, d / (mx + eps), torch.zeros_like(mx))
hr = ((g - b) / (d + eps)) % 6.0
hg = (b - r) / (d + eps) + 2.0
hb = (r - g) / (d + eps) + 4.0
h = torch.where(mx == r, hr, torch.where(mx == g, hg, hb))
h = torch.where(d > eps, h / 6.0, torch.zeros_like(h)) % 1.0
return h, s_, mx
def _hsv_to_rgb(h, s_, v):
h6 = (h % 1.0) * 6.0
i = torch.floor(h6)
f = h6 - i
p = v * (1 - s_)
q = v * (1 - s_ * f)
t_ = v * (1 - s_ * (1 - f))
i = i.long() % 6
r = torch.where(i == 0, v, torch.where(i == 1, q, torch.where(i == 2, p,
torch.where(i == 3, p, torch.where(i == 4, t_, v)))))
g = torch.where(i == 0, t_, torch.where(i == 1, v, torch.where(i == 2, v,
torch.where(i == 3, q, p))))
b = torch.where(i == 0, p, torch.where(i == 1, p, torch.where(i == 2, t_,
torch.where(i == 3, v, torch.where(i == 4, v, q)))))
return torch.cat([r, g, b], 1)
def _skin_weight(t):
"""N1HW, 1 where the colour reads as skin: a hue window round 25 degrees, a
saturation band that excludes grey and neon, and enough brightness to be skin."""
h, s_, v = _rgb_to_hsv(t)
deg = h * 360.0
dh = torch.minimum((deg - 25.0).abs(), 360.0 - (deg - 25.0).abs())
w_h = (1.0 - dh / 30.0).clamp(0, 1)
w_s = ((s_ - 0.08) / 0.12).clamp(0, 1) * ((0.8 - s_) / 0.15).clamp(0, 1)
w_v = ((v - 0.15) / 0.2).clamp(0, 1)
return w_h * w_s * w_v
def _skin_hold(before, after, protect):
"""Give skin its hue back and cap its saturation near the original's, by the
skin weight times protect. Everything that is not skin keeps the new grade."""
if protect <= 0:
return after
w = _skin_weight(before) * float(protect)
h0, s0, _v0 = _rgb_to_hsv(before)
h1, s1, v1 = _rgb_to_hsv(after)
dh = ((h0 - h1 + 0.5) % 1.0) - 0.5 # the short way round the wheel
h2 = (h1 + dh * w) % 1.0
cap = s0 * 1.15
s2 = torch.where(s1 > cap, s1 + (cap - s1) * w, s1)
return _hsv_to_rgb(h2, s2, v1)
_MATCH_SAID = {"no_ref": False}
def match(img, reference=None, method="adain", strength=1.0, skin_protect=0.5,
source="moodboard", ref_file=""):
"""Move the picture's per-channel mean and spread onto the reference's. adain
works in sRGB, linear in linear light. The reference's first frame is used."""
if reference is None or strength <= 0:
if reference is None and not _MATCH_SAID["no_ref"]:
print("[RedNode Post] match: no reference picture, the card passed the "
"frame through", flush=True)
_MATCH_SAID["no_ref"] = True
return img
x = _nchw(img).float()
r = _nchw(reference[:1]).float().to(x.device)
if r.shape[1] > 3:
r = r[:, :3]
if x.shape[1] > 3:
x = x[:, :3]
lin = method == "linear"
xw, rw = (_srgb_to_linear(x), _srgb_to_linear(r)) if lin else (x, r)
mu_x, sd_x = xw.mean((2, 3), keepdim=True), xw.std((2, 3), keepdim=True) + 1e-6
mu_r, sd_r = rw.mean((2, 3), keepdim=True), rw.std((2, 3), keepdim=True) + 1e-6
y = (xw - mu_x) * (sd_r / sd_x) + mu_r
y = _linear_to_srgb(y.clamp(0, 1)) if lin else y
y = y.clamp(0, 1)
y = _skin_hold(x, y, skin_protect)
out = x + (y - x) * float(strength)
return _nhwc(_clamp01(out)).to(img.dtype)
# ---------------------------------------------------------------- the LUT card
_LUT_CACHE = {}
def _ensure_lut_folder():
"""models/luts as a ComfyUI model folder, registered once, so the file list
and get_full_path work the way they do for every other model kind."""
import folder_paths
if "luts" in folder_paths.folder_names_and_paths:
return
path = os.path.join(folder_paths.models_dir, "luts")
try:
os.makedirs(path, exist_ok=True)
except OSError:
pass
folder_paths.folder_names_and_paths["luts"] = ([path], {".cube"})
def lut_files():
import folder_paths
_ensure_lut_folder()
try:
return sorted(folder_paths.get_filename_list("luts"))
except Exception:
return []
def _load_cube(path):
"""A .cube file as (table[S, S, S, 3] indexed [b][g][r], domain_min, domain_max).
The file lists red fastest, which is what the reshape assumes."""
key = (path, os.path.getmtime(path))
if key in _LUT_CACHE:
return _LUT_CACHE[key]
size, dmin, dmax, rows = 0, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0], []
with open(path, "r", encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#"):
continue
up = line.upper()
if up.startswith("TITLE"):
continue
if up.startswith("LUT_3D_SIZE"):
size = int(line.split()[-1])
continue
if up.startswith("LUT_1D_SIZE"):
raise ValueError("1D LUTs are not supported, only LUT_3D_SIZE files")
if up.startswith("DOMAIN_MIN"):
dmin = [float(v) for v in line.split()[1:4]]
continue
if up.startswith("DOMAIN_MAX"):
dmax = [float(v) for v in line.split()[1:4]]
continue
parts = line.split()
if len(parts) >= 3:
try:
rows.append([float(parts[0]), float(parts[1]), float(parts[2])])
except ValueError:
continue
if size <= 1:
size = int(round(len(rows) ** (1.0 / 3.0)))
if size <= 1 or len(rows) < size ** 3:
raise ValueError("cube has %d rows for size %d" % (len(rows), size))
table = torch.tensor(rows[:size ** 3], dtype=torch.float32).view(size, size, size, 3)
_LUT_CACHE.clear()
_LUT_CACHE[key] = (table, torch.tensor(dmin), torch.tensor(dmax))
return _LUT_CACHE[key]
def lut(img, file="", strength=1.0, log=False):
"""Apply a .cube LUT, trilinear, from models/luts. strength blends and goes
past 1 as an overdrive; log applies a 2.2 gamma in and out for LUTs cut for
log footage."""
if not file or file == "None" or strength <= 0:
return img
import folder_paths
_ensure_lut_folder()
path = folder_paths.get_full_path("luts", file)
if path is None:
print("[RedNode Post] LUT %r is not in models/luts; the card passed the frame "
"through" % file, flush=True)
return img
try:
table, dmin, dmax = _load_cube(path)
except Exception as exc:
print("[RedNode Post] LUT %r could not be read (%s); passed through" % (file, exc),
flush=True)
return img
x = _nchw(img).float()
if x.shape[1] > 3:
x = x[:, :3]
src = x.clamp(0, 1) ** (1.0 / 2.2) if log else x.clamp(0, 1)
n, _c, h, w = src.shape
dev = x.device
lo = dmin.to(dev).view(1, 3, 1, 1)
hi = dmax.to(dev).view(1, 3, 1, 1)
rgb = ((src - lo) / (hi - lo).clamp(min=1e-6)).clamp(0, 1) * 2.0 - 1.0
# the volume is [1, 3, B, G, R]; grid_sample's last axis is (x, y, z) = (r, g, b)
vol = table.to(dev).permute(3, 0, 1, 2).unsqueeze(0).expand(n, -1, -1, -1, -1)
grid = torch.stack([rgb[:, 0], rgb[:, 1], rgb[:, 2]], -1).view(n, 1, h, w, 3)
out = F.grid_sample(vol, grid, mode="bilinear", padding_mode="border",
align_corners=True)[:, :, 0]
if log:
out = out.clamp(0, 1) ** 2.2
res = x + (out - x) * float(strength)
return _nhwc(_clamp01(res)).to(img.dtype)
# ---------------------------------------------------------------- the skin card
def _ramp(v, lo, hi, klo, khi):
"""1 inside [lo, hi], falling to 0 over klo below and khi above."""
return (((v - lo + klo) / klo).clamp(0, 1) * ((hi + khi - v) / khi).clamp(0, 1))
def _skin_mask(t, L, a, b, protect=1.0, pattern_reject=0.6, soften=3.0, subject=None):
"""N1HW in 0..1: how much each pixel reads as bare skin."""
H, W = t.shape[2], t.shape[3]
short = min(H, W)
C = torch.sqrt(a * a + b * b)
w_lab = (_ramp(L, 32, 92, 8, 6) * _ramp(a, 3, 38, 3, 6) * _ramp(b, 2, 40, 4, 6)
* _ramp(C, 6, 50, 4, 8))
R_, G_, B_ = t[:, 0:1], t[:, 1:2], t[:, 2:3]
mx = t.max(1, keepdim=True)[0]
mn = t.min(1, keepdim=True)[0]
w_rgb = (((R_ - 0.12) / 0.10).clamp(0, 1) * ((R_ - G_ - 0.02) / 0.06).clamp(0, 1)
* ((R_ - B_ - 0.04) / 0.08).clamp(0, 1) * ((mx - mn - 0.04) / 0.06).clamp(0, 1))
w0 = 0.65 * w_lab + 0.35 * w_rgb
r_hf = max(1, int(round(0.004 * short)))
p_eye = ((34 - L) / 8).clamp(0, 1) * ((16 - C) / 8).clamp(0, 1)
p_teeth = ((L - 78) / 10).clamp(0, 1) * ((14 - C) / 8).clamp(0, 1)
p_lips = (((a - 22) / 8).clamp(0, 1) * ((C - 28) / 10).clamp(0, 1)
* ((L - 25) / 10).clamp(0, 1) * ((72 - L) / 12).clamp(0, 1))
p_micro = (((L - _box(L, r_hf)).abs() - 4) / 6).clamp(0, 1)
p = float(protect) * (1 - (1 - p_eye) * (1 - p_teeth) * (1 - p_lips) * (1 - p_micro))
w1 = w0 * (1 - p)
r_var = max(2, int(round(0.02 * short)))
sd_L = (_box(L * L, r_var) - _box(L, r_var) ** 2).clamp_min(0).sqrt()
sd_C = (_box(C * C, r_var) - _box(C, r_var) ** 2).clamp_min(0).sqrt()
pat = 0.5 * _smoothstep(sd_L, 6, 13) + 0.5 * _smoothstep(sd_C, 5, 11)
w2 = w1 * (1 - float(pattern_reject) * pat)
if subject is not None:
m = subject if subject.ndim == 4 else subject.unsqueeze(1)
m = m[:, :1].to(t.device, t.dtype)
if m.shape[0] != t.shape[0]:
m = m[:1].expand(t.shape[0], -1, -1, -1)
if m.shape[2:] != t.shape[2:]:
m = F.interpolate(m, size=t.shape[2:], mode="bilinear", align_corners=False)
w2 = w2 * gaussian_blur(m.clamp(0, 1), 2.0)
return gaussian_blur(w2, max(0.0, float(soften)) / 2.0).clamp(0, 1)
def skin(img, mask=None, subject="auto", show="off", protect=1.0, pattern_reject=0.6,
mask_soften=3.0, de_yellow=0.0, rosy=0.0, brighten=0.0, shadow_lift=0.0,
evenness=0.0, smooth=0.0, texture_preserve=0.55, saturation=0.0):
"""Retouching under a skin mask, every edit in Lab.
de_yellow and rosy trim the two colour axes, evenness pulls them toward a local
average so blotches even out, saturation scales skin's chroma, smoothing softens
lightness while texture_preserve puts the fine detail back, the brightness lift
fades out near white, and the shadow lift is weighted to the dark side of the
face. Nothing outside the mask is touched.
"""
if show == "off" and not any(float(v) for v in (de_yellow, rosy, brighten, shadow_lift,
evenness, smooth, saturation)):
return img
t = _nchw(img)[:, :3].float()
L, a, b = _rgb_to_lab(t)
w = _skin_mask(t, L, a, b, protect, pattern_reject, mask_soften,
mask if subject != "off" else None)
if show == "mask":
return _nhwc(w.expand(-1, 3, -1, -1)).to(img.dtype)
if show == "over":
tint = torch.tensor([0.10, 0.95, 0.35], device=t.device, dtype=t.dtype).view(1, 3, 1, 1)
return _nhwc(_clamp01(t * (1 - 0.5 * w) + tint * 0.5 * w)).to(img.dtype)
short = min(t.shape[2], t.shape[3])
r_even = max(1, int(round(0.04 * short)))
ev = float(evenness)
a1 = a + ev * (_box(a, r_even) - a) if ev else a
b1 = b + ev * (_box(b, r_even) - b) if ev else b
a2 = a1 + float(rosy)
b2 = b1 - float(de_yellow)
sat = float(saturation)
if sat:
a2 = a2 * (1.0 + sat)
b2 = b2 * (1.0 + sat)
L1 = L
if float(smooth):
r_sm = max(1, int(round(0.012 * short)))
low = 100.0 * _guided(L / 100.0, L / 100.0, r_sm, 4e-4)
L1 = low + (L - low) * (1.0 - float(smooth) * (1.0 - float(texture_preserve)))
L2 = L1 + float(shadow_lift) * (1.0 - L / 100.0) ** 2
L3 = L2 + float(brighten) * ((92.0 - L) / 12.0).clamp(0, 1)
Lo = (L + w * (L3 - L)).clamp(0, 100)
ao = (a + w * (a2 - a)).clamp(-128, 127)
bo = (b + w * (b2 - b)).clamp(-128, 127)
return _nhwc(_lab_to_rgb(Lo, ao, bo)).to(img.dtype)
# ---------------------------------------------------------------- the limit
_LIMIT_SAID = {"no_mask": False}
def limit_to(before, after, mask, limit, feather, name=""):
"""The effect's result only where the mask says, the rest of the frame as it
was. mask is [1, H, W] with 1 for the subject; background is its inverse; the
edge is softened by `feather` pixels. No mask: the whole frame, said once."""
if limit not in ("subject", "background"):
return after
if mask is None:
if not _LIMIT_SAID["no_mask"]:
print("[RedNode Post] %s is limited to the %s but there is no mask; it ran "
"on the whole frame" % (name or "a card", limit), flush=True)
_LIMIT_SAID["no_mask"] = True
return after
m = mask.float()
while m.ndim > 3:
m = m[0]
if m.ndim == 2:
m = m.unsqueeze(0)
m = m[:1].unsqueeze(0).to(after.device) # [1, 1, H, W]
if m.shape[-2:] != after.shape[1:3]:
m = F.interpolate(m, size=after.shape[1:3], mode="bilinear", align_corners=False)
if feather and feather > 0:
m = gaussian_blur(m, float(feather) / 2.0)
m = m.clamp(0, 1)
if limit == "background":
m = 1.0 - m
m = m.permute(0, 2, 3, 1).to(after.dtype) # [1, H, W, 1]
return before * (1.0 - m) + after * m
def _blend(base, top, mode):
"""Composite `top` over `base`, both NCHW in 0..1."""
if mode == "normal":
return top
if mode == "overlay":
return torch.where(base <= 0.5, 2 * base * top,
1 - 2 * (1 - base) * (1 - top))
if mode == "linear light":
return base + 2 * top - 1
# soft light, the W3C/photoshop formulation
d = torch.where(base <= 0.25, ((16 * base - 12) * base + 4) * base, torch.sqrt(base.clamp_min(0)))
return torch.where(top <= 0.5,
base - (1 - 2 * top) * base * (1 - base),
base + (2 * top - 1) * (d - base))
def _blend_if(lum, dark, light):
"""The 'blend if' limiter: 0 below `dark`, 1 above `light`, smooth between.
dark and light arrive on the familiar 0..255 scale.
"""
lo = float(dark) / 255.0
hi = float(light) / 255.0
if hi <= lo:
return torch.ones_like(lum)
return ((lum - lo) / (hi - lo)).clamp(0.0, 1.0)
def clarity(img, radius=3, offset=2.0, strength=0.4, blend_mode="soft light",
blend_if_dark=50, blend_if_light=205, dark_intensity=0.4,
light_intensity=0.0):
"""Local contrast: a wide unsharp mask composited through a blend mode.
radius x offset is the blur reach, so the detail it lifts is broad shapes
rather than pixel edges. dark_intensity and light_intensity weight the two
ends of the tonal range separately, gated by the blend-if window.
"""
t = _nchw(img)
sigma = max(0.1, float(radius) * float(offset) / 3.0)
blurred = gaussian_blur(t, sigma)
detail = _clamp01((t - blurred) * float(strength) + 0.5)
mixed = _blend(t, detail, blend_mode if blend_mode in BLEND_MODES else "soft light")
lum = _luma(t)
upper = _blend_if(lum, blend_if_dark, blend_if_light) # 1 in the highlights
weight = upper * float(light_intensity) + (1.0 - upper) * float(dark_intensity)
return _clamp01(_nhwc(t + (mixed - t) * weight))
def sharpen(img, mode="lucy", iterations=1, kernel_size=3, amount=0.5, radius=1.0,
edge_preserve=0.02, noise_gate=0.055, shadow_protect=0.35,
highlight_protect=0.5, fringe_hold=0.5, skin_protect=0.0):
"""Richardson-Lucy deconvolution, a plain unsharp mask, or a guarded detail band.
Lucy assumes the image was blurred by a Gaussian point spread function and
walks an estimate back towards the sharp original, one multiplicative step
per iteration. It recovers real detail rather than just raising edge
contrast, which is why one or two iterations beat a heavy unsharp pass.
The detail band splits the picture into a soft base (0.45 guided filter on
luma plus 0.55 box blur) and the detail above it, soft-clips the detail with a
tanh whose ceiling rises slower than its gain, so a strong setting stops
growing halos, gates out the finest noise, and holds back in the shadows, the
highlights, where luma already jumps a long way (hair edges) and on skin.
"""
t = _nchw(img)
if mode == "band":
amt = max(0.0, min(3.0, float(amount)))
if amt <= 0:
return img
r = max(1, int(round(float(radius))))
y = _luma(t)
eps = max(1e-6, float(edge_preserve) ** 2)
low = 0.45 * _guided(y.expand_as(t), t, r, eps) + 0.55 * _box(t, r)
d = t - low
cap = 0.035 + 0.045 * amt
band = cap * torch.tanh(amt * d / cap)
ng = max(0.0, float(noise_gate))
if ng > 0:
band = band * _smoothstep(d.abs(), 0.3 * ng, ng)
w = (1.0 - float(shadow_protect) * (1.0 - _smoothstep(y, 0.06, 0.28)))
w = w * (1.0 - float(highlight_protect) * _smoothstep(y, 0.72, 0.95))
w = w * (1.0 - float(fringe_hold) * _smoothstep((y - _luma(low)).abs(), 0.10, 0.30))
if float(skin_protect) > 0:
w = w * (1.0 - float(skin_protect) * _skin_weight(t.clamp(0, 1)))
return _clamp01(_nhwc(t + band * w))
if mode == "unsharp":
blurred = gaussian_blur(t, max(0.1, float(radius)))
return _clamp01(_nhwc(t + (t - blurred) * float(amount)))
sigma = max(0.3, float(kernel_size) / 3.0)
est = t.clamp_min(1e-6)
obs = t.clamp_min(1e-6)
for _ in range(max(1, min(20, int(iterations)))):
conv = gaussian_blur(est, sigma).clamp_min(1e-6)
est = est * gaussian_blur(obs / conv, sigma)
est = est.clamp(0.0, 4.0)
return _clamp01(_nhwc(est))
def bloom(img, intensity=1.16, threshold=0.62, smoothing=0.23, radius_multiplier=1.0,
saturation=0.77, exposure=1.0):
"""Screen a blurred copy of the bright areas back over the image.
smoothing is the soft knee: how gradually a pixel starts counting as bright,
so a lit edge glows instead of switching on. saturation controls how coloured
the glow is, exposure scales the source brightness feeding it.
"""
t = _nchw(img) * float(exposure)
lum = _luma(t)
thr = float(threshold)
knee = max(1e-4, float(smoothing))
mask = ((lum - thr) / knee).clamp(0.0, 1.0) # soft knee ramp
mask = mask * mask * (3 - 2 * mask) # smoothstep
bright = t * mask
if saturation != 1.0:
bl = _luma(bright)
bright = bl + (bright - bl) * float(saturation)
sigma = max(0.5, 8.0 * float(radius_multiplier))
glow = gaussian_blur(bright, sigma) * float(intensity)
base = _nchw(img)
screened = 1 - (1 - base) * (1 - glow.clamp(0.0, 1.0)) # screen composite
return _clamp01(_nhwc(screened))