-
Notifications
You must be signed in to change notification settings - Fork 3
/
image_blend.py
2177 lines (1869 loc) · 89.8 KB
/
image_blend.py
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
# TODO: Improve blend modes
# TODO: Add nodes like Hue Adjust for Saturation/Contrast/etc... ?
# TODO: Continue implementing more blend modes/color spaces(?)
# TODO: Custom ICC profiles with PIL.ImageCms?
# TODO: Blend multiple layers all crammed into a tensor(?) or list
# Copyright (c) 2023 Darren Ringer <dwringer@gmail.com>
# Parts based on Oklab: Copyright (c) 2021 Björn Ottosson <https://bottosson.github.io/>
# HSL code based on CPython: Copyright (c) 2001-2023 Python Software Foundation; All Rights Reserved
import os.path
from io import BytesIO
from math import pi as PI
from typing import Literal, Optional
import PIL.Image
import PIL.ImageCms
import PIL.ImageOps
import torch
from torchvision.transforms.functional import to_pil_image as pil_image_from_tensor
from invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor
from invokeai.invocation_api import (
BaseInvocation,
ImageField,
ImageOutput,
InputField,
InvocationContext,
WithBoard,
WithMetadata,
invocation,
)
MAX_FLOAT = torch.finfo(torch.tensor(1.0).dtype).max
def tensor_from_pil_image(img, normalize=True):
return image_resized_to_grid_as_tensor(img, normalize=normalize, multiple_of=1)
def remove_nans(tensor, replace_with=MAX_FLOAT):
return torch.where(torch.isnan(tensor), replace_with, tensor)
HUE_COLOR_SPACES = [
"HSV / HSL / RGB",
"Okhsl",
"Okhsv",
"*Oklch / Oklab",
"*LCh / CIELab",
"*UPLab (w/CIELab_to_UPLab.icc)",
]
BLEND_MODES = [
"Normal",
"Lighten Only",
"Darken Only",
"Lighten Only (EAL)",
"Darken Only (EAL)",
"Hue",
"Saturation",
"Color",
"Luminosity",
"Linear Dodge (Add)",
"Subtract",
"Multiply",
"Divide",
"Screen",
"Overlay",
"Linear Burn",
"Difference",
"Hard Light",
"Soft Light",
"Vivid Light",
"Linear Light",
"Color Burn",
"Color Dodge",
]
BLEND_COLOR_SPACES = ["RGB", "Linear RGB", "HSL (RGB)", "HSV (RGB)", "Okhsl", "Okhsv", "Oklch (Oklab)", "LCh (CIELab)"]
@invocation(
"img_blend",
title="Image Layer Blend",
tags=["image", "blend", "layer", "alpha", "composite", "dodge", "burn"],
category="image",
version="1.2.0",
)
class ImageBlendInvocation(BaseInvocation, WithMetadata, WithBoard):
"""Blend two images together, with optional opacity, mask, and blend modes"""
layer_upper: ImageField = InputField(description="The top image to blend", ui_order=1)
blend_mode: Literal[tuple(BLEND_MODES)] = InputField(
default=BLEND_MODES[0], description="Available blend modes", ui_order=2
)
opacity: float = InputField(default=1.0, description="Desired opacity of the upper layer", ui_order=3)
mask: Optional[ImageField] = InputField(
default=None, description="Optional mask, used to restrict areas from blending", ui_order=4
)
fit_to_width: bool = InputField(default=False, description="Scale upper layer to fit base width", ui_order=5)
fit_to_height: bool = InputField(default=True, description="Scale upper layer to fit base height", ui_order=6)
layer_base: ImageField = InputField(description="The bottom image to blend", ui_order=7)
color_space: Literal[tuple(BLEND_COLOR_SPACES)] = InputField(
default=BLEND_COLOR_SPACES[1], description="Available color spaces for blend computations", ui_order=8
)
adaptive_gamut: float = InputField(
default=0.0, description="Adaptive gamut clipping (0=off). Higher prioritizes chroma over lightness", ui_order=9
)
high_precision: bool = InputField(
default=True, description="Use more steps in computing gamut when possible", ui_order=10
)
def scale_and_pad_or_crop_to_base(self, image_upper, image_base):
"""Rescale upper image based on self.fill_x and self.fill_y params"""
aspect_base = image_base.width / image_base.height
aspect_upper = image_upper.width / image_upper.height
if self.fit_to_width and self.fit_to_height:
image_upper = image_upper.resize((image_base.width, image_base.height))
elif (self.fit_to_width and (aspect_base < aspect_upper)) or (
self.fit_to_height and (aspect_upper <= aspect_base)
):
image_upper = PIL.ImageOps.pad(
image_upper, (image_base.width, image_base.height), color=tuple([0 for band in image_upper.getbands()])
)
elif (self.fit_to_width and (aspect_upper <= aspect_base)) or (
self.fit_to_height and (aspect_base < aspect_upper)
):
image_upper = PIL.ImageOps.fit(image_upper, (image_base.width, image_base.height))
return image_upper
def image_convert_with_xform(self, image_in, from_mode, to_mode):
"""Use PIL ImageCms color management to convert 3-channel image from one mode to another"""
def fixed_mode(mode):
if mode.lower() == "srgb":
return "rgb"
elif mode.lower() == "cielab":
return "lab"
else:
return mode.lower()
from_mode, to_mode = fixed_mode(from_mode), fixed_mode(to_mode)
profile_srgb = None
profile_uplab = None
profile_lab = None
if (from_mode.lower() == "rgb") or (to_mode.lower() == "rgb"):
profile_srgb = PIL.ImageCms.createProfile("sRGB")
if (from_mode.lower() == "uplab") or (to_mode.lower() == "uplab"):
if os.path.isfile("CIELab_to_UPLab.icc"):
profile_uplab = PIL.ImageCms.getOpenProfile("CIELab_to_UPLab.icc")
if (from_mode.lower() in ["lab", "cielab", "uplab"]) or (to_mode.lower() in ["lab", "cielab", "uplab"]):
if profile_uplab is None:
profile_lab = PIL.ImageCms.createProfile("LAB", colorTemp=6500)
else:
profile_lab = PIL.ImageCms.createProfile("LAB", colorTemp=5000)
xform_rgb_to_lab = None
xform_uplab_to_lab = None
xform_lab_to_uplab = None
xform_lab_to_rgb = None
if from_mode == "rgb":
xform_rgb_to_lab = PIL.ImageCms.buildTransformFromOpenProfiles(
profile_srgb, profile_lab, "RGB", "LAB", renderingIntent=2, flags=0x2400
)
elif from_mode == "uplab":
xform_uplab_to_lab = PIL.ImageCms.buildTransformFromOpenProfiles(
profile_uplab, profile_lab, "LAB", "LAB", renderingIntent=2, flags=0x2400
)
if to_mode == "uplab":
xform_lab_to_uplab = PIL.ImageCms.buildTransformFromOpenProfiles(
profile_lab, profile_uplab, "LAB", "LAB", renderingIntent=2, flags=0x2400
)
elif to_mode == "rgb":
xform_lab_to_rgb = PIL.ImageCms.buildTransformFromOpenProfiles(
profile_lab, profile_srgb, "LAB", "RGB", renderingIntent=2, flags=0x2400
)
image_out = None
if (from_mode == "rgb") and (to_mode == "lab"):
image_out = PIL.ImageCms.applyTransform(image_in, xform_rgb_to_lab)
elif (from_mode == "rgb") and (to_mode == "uplab"):
image_out = PIL.ImageCms.applyTransform(image_in, xform_rgb_to_lab)
image_out = PIL.ImageCms.applyTransform(image_out, xform_lab_to_uplab)
elif (from_mode == "lab") and (to_mode == "uplab"):
image_out = PIL.ImageCms.applyTransform(image_in, xform_lab_to_uplab)
elif (from_mode == "lab") and (to_mode == "rgb"):
image_out = PIL.ImageCms.applyTransform(image_in, xform_lab_to_rgb)
elif (from_mode == "uplab") and (to_mode == "lab"):
image_out = PIL.ImageCms.applyTransform(image_in, xform_uplab_to_lab)
elif (from_mode == "uplab") and (to_mode == "rgb"):
image_out = PIL.ImageCms.applyTransform(image_in, xform_uplab_to_lab)
image_out = PIL.ImageCms.applyTransform(image_out, xform_lab_to_rgb)
return image_out
def prepare_tensors_from_images(
self,
image_upper,
image_lower,
mask_image=None,
required=["hsv", "hsl", "lch", "oklch", "okhsl", "okhsv", "l_eal"],
):
"""Convert image to the necessary image space representations for blend calculations"""
alpha_upper, alpha_lower = None, None
if image_upper.mode == "RGBA":
# Prepare tensors to compute blend
image_rgba_upper = image_upper.convert("RGBA")
alpha_upper = image_rgba_upper.getchannel("A")
image_upper = image_upper.convert("RGB")
else:
if not (image_upper.mode == "RGB"):
image_upper = image_upper.convert("RGB")
if image_lower.mode == "RGBA":
# Prepare tensors to compute blend
image_rgba_lower = image_lower.convert("RGBA")
alpha_lower = image_rgba_lower.getchannel("A")
image_lower = image_lower.convert("RGB")
else:
if not (image_lower.mode == "RGB"):
image_lower = image_lower.convert("RGB")
image_lab_upper, image_lab_lower = None, None
upper_lab_tensor, lower_lab_tensor = None, None
upper_lch_tensor, lower_lch_tensor = None, None
if "lch" in required:
image_lab_upper, image_lab_lower = (
self.image_convert_with_xform(image_upper, "rgb", "lab"),
self.image_convert_with_xform(image_lower, "rgb", "lab"),
)
upper_lab_tensor = torch.stack(
[
tensor_from_pil_image(image_lab_upper.getchannel("L"), normalize=False)[0, :, :],
tensor_from_pil_image(image_lab_upper.getchannel("A"), normalize=True)[0, :, :],
tensor_from_pil_image(image_lab_upper.getchannel("B"), normalize=True)[0, :, :],
]
)
lower_lab_tensor = torch.stack(
[
tensor_from_pil_image(image_lab_lower.getchannel("L"), normalize=False)[0, :, :],
tensor_from_pil_image(image_lab_lower.getchannel("A"), normalize=True)[0, :, :],
tensor_from_pil_image(image_lab_lower.getchannel("B"), normalize=True)[0, :, :],
]
)
upper_lch_tensor = torch.stack(
[
upper_lab_tensor[0, :, :],
torch.sqrt(
torch.add(torch.pow(upper_lab_tensor[1, :, :], 2.0), torch.pow(upper_lab_tensor[2, :, :], 2.0))
),
torch.atan2(upper_lab_tensor[2, :, :], upper_lab_tensor[1, :, :]),
]
)
lower_lch_tensor = torch.stack(
[
lower_lab_tensor[0, :, :],
torch.sqrt(
torch.add(torch.pow(lower_lab_tensor[1, :, :], 2.0), torch.pow(lower_lab_tensor[2, :, :], 2.0))
),
torch.atan2(lower_lab_tensor[2, :, :], lower_lab_tensor[1, :, :]),
]
)
upper_l_eal_tensor, lower_l_eal_tensor = None, None
if "l_eal" in required:
upper_l_eal_tensor = equivalent_achromatic_lightness(upper_lch_tensor)
lower_l_eal_tensor = equivalent_achromatic_lightness(lower_lch_tensor)
image_hsv_upper, image_hsv_lower = None, None
upper_hsv_tensor, lower_hsv_tensor = None, None
if "hsv" in required:
image_hsv_upper, image_hsv_lower = image_upper.convert("HSV"), image_lower.convert("HSV")
upper_hsv_tensor = torch.stack(
[
tensor_from_pil_image(image_hsv_upper.getchannel("H"), normalize=False)[0, :, :],
tensor_from_pil_image(image_hsv_upper.getchannel("S"), normalize=False)[0, :, :],
tensor_from_pil_image(image_hsv_upper.getchannel("V"), normalize=False)[0, :, :],
]
)
lower_hsv_tensor = torch.stack(
[
tensor_from_pil_image(image_hsv_lower.getchannel("H"), normalize=False)[0, :, :],
tensor_from_pil_image(image_hsv_lower.getchannel("S"), normalize=False)[0, :, :],
tensor_from_pil_image(image_hsv_lower.getchannel("V"), normalize=False)[0, :, :],
]
)
upper_rgb_tensor = tensor_from_pil_image(image_upper, normalize=False)
lower_rgb_tensor = tensor_from_pil_image(image_lower, normalize=False)
alpha_upper_tensor, alpha_lower_tensor = None, None
if alpha_upper is None:
alpha_upper_tensor = torch.ones(upper_rgb_tensor[0, :, :].shape)
else:
alpha_upper_tensor = tensor_from_pil_image(alpha_upper, normalize=False)[0, :, :]
if alpha_lower is None:
alpha_lower_tensor = torch.ones(lower_rgb_tensor[0, :, :].shape)
else:
alpha_lower_tensor = tensor_from_pil_image(alpha_lower, normalize=False)[0, :, :]
mask_tensor = None
if not (mask_image is None):
mask_tensor = tensor_from_pil_image(mask_image.convert("L"), normalize=False)[0, :, :]
upper_hsl_tensor, lower_hsl_tensor = None, None
if "hsl" in required:
upper_hsl_tensor = hsl_from_srgb(upper_rgb_tensor)
lower_hsl_tensor = hsl_from_srgb(lower_rgb_tensor)
upper_okhsl_tensor, lower_okhsl_tensor = None, None
if "okhsl" in required:
upper_okhsl_tensor = okhsl_from_srgb(upper_rgb_tensor, steps=(3 if self.high_precision else 1))
lower_okhsl_tensor = okhsl_from_srgb(lower_rgb_tensor, steps=(3 if self.high_precision else 1))
upper_okhsv_tensor, lower_okhsv_tensor = None, None
if "okhsv" in required:
upper_okhsv_tensor = okhsv_from_srgb(upper_rgb_tensor, steps=(3 if self.high_precision else 1))
lower_okhsv_tensor = okhsv_from_srgb(lower_rgb_tensor, steps=(3 if self.high_precision else 1))
upper_rgb_l_tensor = linear_srgb_from_srgb(upper_rgb_tensor)
lower_rgb_l_tensor = linear_srgb_from_srgb(lower_rgb_tensor)
upper_oklab_tensor, lower_oklab_tensor = None, None
upper_oklch_tensor, lower_oklch_tensor = None, None
if "oklch" in required:
upper_oklab_tensor = oklab_from_linear_srgb(upper_rgb_l_tensor)
lower_oklab_tensor = oklab_from_linear_srgb(lower_rgb_l_tensor)
upper_oklch_tensor = torch.stack(
[
upper_oklab_tensor[0, :, :],
torch.sqrt(
torch.add(
torch.pow(upper_oklab_tensor[1, :, :], 2.0), torch.pow(upper_oklab_tensor[2, :, :], 2.0)
)
),
torch.atan2(upper_oklab_tensor[2, :, :], upper_oklab_tensor[1, :, :]),
]
)
lower_oklch_tensor = torch.stack(
[
lower_oklab_tensor[0, :, :],
torch.sqrt(
torch.add(
torch.pow(lower_oklab_tensor[1, :, :], 2.0), torch.pow(lower_oklab_tensor[2, :, :], 2.0)
)
),
torch.atan2(lower_oklab_tensor[2, :, :], lower_oklab_tensor[1, :, :]),
]
)
return (
upper_rgb_l_tensor,
lower_rgb_l_tensor,
upper_rgb_tensor,
lower_rgb_tensor,
alpha_upper_tensor,
alpha_lower_tensor,
mask_tensor,
upper_hsv_tensor,
lower_hsv_tensor,
upper_hsl_tensor,
lower_hsl_tensor,
upper_lab_tensor,
lower_lab_tensor,
upper_lch_tensor,
lower_lch_tensor,
upper_l_eal_tensor,
lower_l_eal_tensor,
upper_oklab_tensor,
lower_oklab_tensor,
upper_oklch_tensor,
lower_oklch_tensor,
upper_okhsv_tensor,
lower_okhsv_tensor,
upper_okhsl_tensor,
lower_okhsl_tensor,
)
def apply_blend(self, image_tensors):
"""Apply the selected blend mode using the appropriate color space representations"""
blend_mode = self.blend_mode
color_space = self.color_space.split()[0]
if (color_space in ["RGB", "Linear"]) and (blend_mode in ["Hue", "Saturation", "Luminosity", "Color"]):
color_space = "HSL"
def adaptive_clipped(rgb_tensor, clamp=True, replace_with=MAX_FLOAT):
"""Keep elements of the tensor finite"""
rgb_tensor = remove_nans(rgb_tensor, replace_with=replace_with)
if 0 < self.adaptive_gamut:
rgb_tensor = gamut_clip_tensor(
rgb_tensor, alpha=self.adaptive_gamut, steps=(3 if self.high_precision else 1)
)
rgb_tensor = remove_nans(rgb_tensor, replace_with=replace_with)
if clamp: # Use of MAX_FLOAT seems to lead to NaN's coming back in some cases:
rgb_tensor = rgb_tensor.clamp(0.0, 1.0)
return rgb_tensor
reassembly_function = {
"RGB": lambda t: linear_srgb_from_srgb(t),
"Linear": lambda t: t,
"HSL": lambda t: linear_srgb_from_srgb(srgb_from_hsl(t)),
"HSV": lambda t: linear_srgb_from_srgb(
tensor_from_pil_image(
pil_image_from_tensor(t.clamp(0.0, 1.0), mode="HSV").convert("RGB"), normalize=False
)
),
"Okhsl": lambda t: linear_srgb_from_srgb(
srgb_from_okhsl(t, alpha=self.adaptive_gamut, steps=(3 if self.high_precision else 1))
),
"Okhsv": lambda t: linear_srgb_from_srgb(
srgb_from_okhsv(t, alpha=self.adaptive_gamut, steps=(3 if self.high_precision else 1))
),
"Oklch": lambda t: linear_srgb_from_oklab(
torch.stack(
[
t[0, :, :],
torch.mul(t[1, :, :], torch.cos(t[2, :, :])),
torch.mul(t[1, :, :], torch.sin(t[2, :, :])),
]
)
),
"LCh": lambda t: linear_srgb_from_srgb(
tensor_from_pil_image(
self.image_convert_with_xform(
PIL.Image.merge(
"LAB",
tuple(
map(
lambda u: pil_image_from_tensor(u),
[
t[0, :, :].clamp(0.0, 1.0),
torch.div(torch.add(torch.mul(t[1, :, :], torch.cos(t[2, :, :])), 1.0), 2.0),
torch.div(torch.add(torch.mul(t[1, :, :], torch.sin(t[2, :, :])), 1.0), 2.0),
],
)
),
),
"lab",
"rgb",
),
normalize=False,
)
),
}[color_space]
(
upper_rgb_l_tensor, # linear-light sRGB
lower_rgb_l_tensor, # linear-light sRGB
upper_rgb_tensor,
lower_rgb_tensor,
alpha_upper_tensor,
alpha_lower_tensor,
mask_tensor,
upper_hsv_tensor, # h_rgb, s_hsv, v_hsv
lower_hsv_tensor,
upper_hsl_tensor, # , s_hsl, l_hsl
lower_hsl_tensor,
upper_lab_tensor, # l_lab, a_lab, b_lab
lower_lab_tensor,
upper_lch_tensor, # , c_lab, h_lab
lower_lch_tensor,
upper_l_eal_tensor, # l_eal
lower_l_eal_tensor,
upper_oklab_tensor, # l_oklab, a_oklab, b_oklab
lower_oklab_tensor,
upper_oklch_tensor, # , c_oklab, h_oklab
lower_oklch_tensor,
upper_okhsv_tensor, # h_okhsv, s_okhsv, v_okhsv
lower_okhsv_tensor,
upper_okhsl_tensor, # h_okhsl, s_okhsl, l_r_oklab
lower_okhsl_tensor,
) = image_tensors
current_space_tensors = {
"RGB": [upper_rgb_tensor, lower_rgb_tensor],
"Linear": [upper_rgb_l_tensor, lower_rgb_l_tensor],
"HSL": [upper_hsl_tensor, lower_hsl_tensor],
"HSV": [upper_hsv_tensor, lower_hsv_tensor],
"Okhsl": [upper_okhsl_tensor, lower_okhsl_tensor],
"Okhsv": [upper_okhsv_tensor, lower_okhsv_tensor],
"Oklch": [upper_oklch_tensor, lower_oklch_tensor],
"LCh": [upper_lch_tensor, lower_lch_tensor],
}[color_space]
upper_space_tensor = current_space_tensors[0]
lower_space_tensor = current_space_tensors[1]
lightness_index = {
"RGB": None,
"Linear": None,
"HSL": 2,
"HSV": 2,
"Okhsl": 2,
"Okhsv": 2,
"Oklch": 0,
"LCh": 0,
}[color_space]
saturation_index = {
"RGB": None,
"Linear": None,
"HSL": 1,
"HSV": 1,
"Okhsl": 1,
"Okhsv": 1,
"Oklch": 1,
"LCh": 1,
}[color_space]
hue_index = {
"RGB": None,
"Linear": None,
"HSL": 0,
"HSV": 0,
"Okhsl": 0,
"Okhsv": 0,
"Oklch": 2,
"LCh": 2,
}[color_space]
if blend_mode == "Normal":
upper_rgb_l_tensor = reassembly_function(upper_space_tensor)
elif blend_mode == "Multiply":
upper_rgb_l_tensor = reassembly_function(torch.mul(lower_space_tensor, upper_space_tensor))
elif blend_mode == "Screen":
upper_rgb_l_tensor = reassembly_function(
torch.add(
torch.mul(
torch.mul(
torch.add(torch.mul(upper_space_tensor, -1.0), 1.0),
torch.add(torch.mul(lower_space_tensor, -1.0), 1.0),
),
-1.0,
),
1.0,
)
)
elif (blend_mode == "Overlay") or (blend_mode == "Hard Light"):
subject_of_cond_tensor = lower_space_tensor if (blend_mode == "Overlay") else upper_space_tensor
if lightness_index is None:
upper_space_tensor = torch.where(
torch.lt(subject_of_cond_tensor, 0.5),
torch.mul(torch.mul(lower_space_tensor, upper_space_tensor), 2.0),
torch.add(
torch.mul(
torch.mul(
torch.mul(
torch.add(torch.mul(lower_space_tensor, -1.0), 1.0),
torch.add(torch.mul(upper_space_tensor, -1.0), 1.0),
),
2.0,
),
-1.0,
),
1.0,
),
)
else: # TODO: Currently blending only the lightness channel, not really ideal.
upper_space_tensor[lightness_index, :, :] = torch.where(
torch.lt(subject_of_cond_tensor[lightness_index, :, :], 0.5),
torch.mul(
torch.mul(lower_space_tensor[lightness_index, :, :], upper_space_tensor[lightness_index, :, :]),
2.0,
),
torch.add(
torch.mul(
torch.mul(
torch.mul(
torch.add(torch.mul(lower_space_tensor[lightness_index, :, :], -1.0), 1.0),
torch.add(torch.mul(upper_space_tensor[lightness_index, :, :], -1.0), 1.0),
),
2.0,
),
-1.0,
),
1.0,
),
)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(upper_space_tensor))
elif blend_mode == "Soft Light":
if lightness_index is None:
g_tensor = torch.where(
torch.le(lower_space_tensor, 0.25),
torch.mul(
torch.add(
torch.mul(torch.sub(torch.mul(lower_space_tensor, 16.0), 12.0), lower_space_tensor), 4.0
),
lower_space_tensor,
),
torch.sqrt(lower_space_tensor),
)
lower_space_tensor = torch.where(
torch.le(upper_space_tensor, 0.5),
torch.sub(
lower_space_tensor,
torch.mul(
torch.mul(torch.add(torch.mul(lower_space_tensor, -1.0), 1.0), lower_space_tensor),
torch.add(torch.mul(torch.mul(upper_space_tensor, 2.0), -1.0), 1.0),
),
),
torch.add(
lower_space_tensor,
torch.mul(
torch.sub(torch.mul(upper_space_tensor, 2.0), 1.0), torch.sub(g_tensor, lower_space_tensor)
),
),
)
else:
print(
"\r\nCOND SHAPE:"
+ str(torch.le(lower_space_tensor[lightness_index, :, :], 0.25).unsqueeze(0).shape)
+ "\r\n"
)
g_tensor = torch.where( # Calculates all 3 channels but only one is currently used
torch.le(lower_space_tensor[lightness_index, :, :], 0.25).expand(upper_space_tensor.shape),
torch.mul(
torch.add(
torch.mul(torch.sub(torch.mul(lower_space_tensor, 16.0), 12.0), lower_space_tensor), 4.0
),
lower_space_tensor,
),
torch.sqrt(lower_space_tensor),
)
lower_space_tensor[lightness_index, :, :] = torch.where(
torch.le(upper_space_tensor[lightness_index, :, :], 0.5),
torch.sub(
lower_space_tensor[lightness_index, :, :],
torch.mul(
torch.mul(
torch.add(torch.mul(lower_space_tensor[lightness_index, :, :], -1.0), 1.0),
lower_space_tensor[lightness_index, :, :],
),
torch.add(torch.mul(torch.mul(upper_space_tensor[lightness_index, :, :], 2.0), -1.0), 1.0),
),
),
torch.add(
lower_space_tensor[lightness_index, :, :],
torch.mul(
torch.sub(torch.mul(upper_space_tensor[lightness_index, :, :], 2.0), 1.0),
torch.sub(g_tensor[lightness_index, :, :], lower_space_tensor[lightness_index, :, :]),
),
),
)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Linear Dodge (Add)":
lower_space_tensor = torch.add(lower_space_tensor, upper_space_tensor)
if hue_index is not None:
lower_space_tensor[hue_index, :, :] = torch.remainder(lower_space_tensor[hue_index, :, :], 1.0)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Color Dodge":
lower_space_tensor = torch.div(lower_space_tensor, torch.add(torch.mul(upper_space_tensor, -1.0), 1.0))
if hue_index is not None:
lower_space_tensor[hue_index, :, :] = torch.remainder(lower_space_tensor[hue_index, :, :], 1.0)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Divide":
lower_space_tensor = torch.div(lower_space_tensor, upper_space_tensor)
if hue_index is not None:
lower_space_tensor[hue_index, :, :] = torch.remainder(lower_space_tensor[hue_index, :, :], 1.0)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Linear Burn":
# We compute the result in the lower image's current space tensor and return that:
if lightness_index is None: # Elementwise
lower_space_tensor = torch.sub(torch.add(lower_space_tensor, upper_space_tensor), 1.0)
else: # Operate only on the selected lightness channel
lower_space_tensor[lightness_index, :, :] = torch.sub(
torch.add(lower_space_tensor[lightness_index, :, :], upper_space_tensor[lightness_index, :, :]), 1.0
)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Color Burn":
upper_rgb_l_tensor = adaptive_clipped(
reassembly_function(
torch.add(
torch.mul(
torch.min(
torch.div(torch.add(torch.mul(lower_space_tensor, -1.0), 1.0), upper_space_tensor),
torch.ones(lower_space_tensor.shape),
),
-1.0,
),
1.0,
)
)
)
elif blend_mode == "Vivid Light":
if lightness_index is None:
lower_space_tensor = adaptive_clipped(
reassembly_function(
torch.where(
torch.lt(upper_space_tensor, 0.5),
torch.div(
torch.add(
torch.mul(
torch.div(
torch.add(torch.mul(lower_space_tensor, -1.0), 1.0), upper_space_tensor
),
-1.0,
),
1.0,
),
2.0,
),
torch.div(
torch.div(lower_space_tensor, torch.add(torch.mul(upper_space_tensor, -1.0), 1.0)), 2.0
),
)
)
)
else:
lower_space_tensor[lightness_index, :, :] = torch.where(
torch.lt(upper_space_tensor[lightness_index, :, :], 0.5),
torch.div(
torch.add(
torch.mul(
torch.div(
torch.add(torch.mul(lower_space_tensor[lightness_index, :, :], -1.0), 1.0),
upper_space_tensor[lightness_index, :, :],
),
-1.0,
),
1.0,
),
2.0,
),
torch.div(
torch.div(
lower_space_tensor[lightness_index, :, :],
torch.add(torch.mul(upper_space_tensor[lightness_index, :, :], -1.0), 1.0),
),
2.0,
),
)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Linear Light":
if lightness_index is None:
lower_space_tensor = torch.sub(torch.add(lower_space_tensor, torch.mul(upper_space_tensor, 2.0)), 1.0)
else:
lower_space_tensor[lightness_index, :, :] = torch.sub(
torch.add(
lower_space_tensor[lightness_index, :, :],
torch.mul(upper_space_tensor[lightness_index, :, :], 2.0),
),
1.0,
)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Subtract":
lower_space_tensor = torch.sub(lower_space_tensor, upper_space_tensor)
if hue_index is not None:
lower_space_tensor[hue_index, :, :] = torch.remainder(lower_space_tensor[hue_index, :, :], 1.0)
upper_rgb_l_tensor = adaptive_clipped(reassembly_function(lower_space_tensor))
elif blend_mode == "Difference":
upper_rgb_l_tensor = adaptive_clipped(
reassembly_function(torch.abs(torch.sub(lower_space_tensor, upper_space_tensor)))
)
elif (blend_mode == "Darken Only") or (blend_mode == "Lighten Only"):
extrema_fn = torch.min if (blend_mode == "Darken Only") else torch.max
comparator_fn = torch.ge if (blend_mode == "Darken Only") else torch.lt
if lightness_index is None:
upper_space_tensor = torch.stack(
[
extrema_fn(upper_space_tensor[0, :, :], lower_space_tensor[0, :, :]),
extrema_fn(upper_space_tensor[1, :, :], lower_space_tensor[1, :, :]),
extrema_fn(upper_space_tensor[2, :, :], lower_space_tensor[2, :, :]),
]
)
else:
upper_space_tensor = torch.where(
comparator_fn(
upper_space_tensor[lightness_index, :, :], lower_space_tensor[lightness_index, :, :]
).expand(upper_space_tensor.shape),
lower_space_tensor,
upper_space_tensor,
)
upper_rgb_l_tensor = reassembly_function(upper_space_tensor)
elif blend_mode in [
"Hue",
"Saturation",
"Color",
"Luminosity",
]:
if blend_mode == "Hue": # l, c: lower / h: upper
upper_space_tensor[lightness_index, :, :] = lower_space_tensor[lightness_index, :, :]
upper_space_tensor[saturation_index, :, :] = lower_space_tensor[saturation_index, :, :]
elif blend_mode == "Saturation": # l, h: lower / c: upper
upper_space_tensor[lightness_index, :, :] = lower_space_tensor[lightness_index, :, :]
upper_space_tensor[hue_index, :, :] = lower_space_tensor[hue_index, :, :]
elif blend_mode == "Color": # l: lower / c, h: upper
upper_space_tensor[lightness_index, :, :] = lower_space_tensor[lightness_index, :, :]
elif blend_mode == "Luminosity": # h, c: lower / l: upper
upper_space_tensor[saturation_index, :, :] = lower_space_tensor[saturation_index, :, :]
upper_space_tensor[hue_index, :, :] = lower_space_tensor[hue_index, :, :]
upper_rgb_l_tensor = reassembly_function(upper_space_tensor)
elif blend_mode in ["Lighten Only (EAL)", "Darken Only (EAL)"]:
comparator_fn = torch.lt if (blend_mode == "Lighten Only (EAL)") else torch.ge
upper_space_tensor = torch.where(
comparator_fn(upper_l_eal_tensor, lower_l_eal_tensor).expand(upper_space_tensor.shape),
lower_space_tensor,
upper_space_tensor,
)
upper_rgb_l_tensor = reassembly_function(upper_space_tensor)
return upper_rgb_l_tensor
def alpha_composite(self, upper_tensor, alpha_upper_tensor, lower_tensor, alpha_lower_tensor, mask_tensor=None):
"""Alpha compositing of upper on lower tensor with alpha channels, mask and scalar"""
upper_tensor = remove_nans(upper_tensor)
alpha_upper_tensor = torch.mul(alpha_upper_tensor, self.opacity)
if not (mask_tensor is None):
alpha_upper_tensor = torch.mul(alpha_upper_tensor, torch.add(torch.mul(mask_tensor, -1.0), 1.0))
alpha_tensor = torch.add(
alpha_upper_tensor, torch.mul(alpha_lower_tensor, torch.add(torch.mul(alpha_upper_tensor, -1.0), 1.0))
)
return (
torch.div(
torch.add(
torch.mul(upper_tensor, alpha_upper_tensor),
torch.mul(
torch.mul(lower_tensor, alpha_lower_tensor), torch.add(torch.mul(alpha_upper_tensor, -1.0), 1.0)
),
),
alpha_tensor,
),
alpha_tensor,
)
def invoke(self, context: InvocationContext) -> ImageOutput:
"""Main execution of the ImageBlendInvocation node"""
image_upper = context.images.get_pil(self.layer_upper.image_name)
image_base = context.images.get_pil(self.layer_base.image_name)
# Keep the modes for restoration after processing:
image_mode_upper = image_upper.mode
image_mode_base = image_base.mode
# Get rid of ICC profiles by converting to sRGB, but save for restoration:
cms_profile_srgb = None
if "icc_profile" in image_upper.info:
cms_profile_upper = BytesIO(image_upper.info["icc_profile"])
cms_profile_srgb = PIL.ImageCms.createProfile("sRGB")
cms_xform = PIL.ImageCms.buildTransformFromOpenProfiles(
cms_profile_upper, cms_profile_srgb, image_upper.mode, "RGBA"
)
image_upper = PIL.ImageCms.applyTransform(image_upper, cms_xform)
cms_profile_base = None
icc_profile_bytes = None
if "icc_profile" in image_base.info:
icc_profile_bytes = image_base.info["icc_profile"]
cms_profile_base = BytesIO(icc_profile_bytes)
if cms_profile_srgb is None:
cms_profile_srgb = PIL.ImageCms.createProfile("sRGB")
cms_xform = PIL.ImageCms.buildTransformFromOpenProfiles(
cms_profile_base, cms_profile_srgb, image_base.mode, "RGBA"
)
image_base = PIL.ImageCms.applyTransform(image_base, cms_xform)
image_mask = None
if not (self.mask is None):
image_mask = context.images.get_pil(self.mask.image_name)
color_space = self.color_space.split()[0]
image_upper = self.scale_and_pad_or_crop_to_base(image_upper, image_base)
if image_mask is not None:
image_mask = self.scale_and_pad_or_crop_to_base(image_mask, image_base)
tensor_requirements = []
# Hue, Saturation, Color, and Luminosity won't work in sRGB, require HSL
if self.blend_mode in ["Hue", "Saturation", "Color", "Luminosity"] and self.color_space in [
"RGB",
"Linear RGB",
]:
tensor_requirements = ["hsl"]
if self.blend_mode in ["Lighten Only (EAL)", "Darken Only (EAL)"]:
tensor_requirements = tensor_requirements + ["lch", "l_eal"]
tensor_requirements += {
"Linear": [],
"RGB": [],
"HSL": ["hsl"],
"HSV": ["hsv"],
"Okhsl": ["okhsl"],
"Okhsv": ["okhsv"],
"Oklch": ["oklch"],
"LCh": ["lch"],
}[color_space]
image_tensors = (
upper_rgb_l_tensor, # linear-light sRGB
lower_rgb_l_tensor, # linear-light sRGB
upper_rgb_tensor,
lower_rgb_tensor,
alpha_upper_tensor,
alpha_lower_tensor,
mask_tensor,
upper_hsv_tensor,
lower_hsv_tensor,
upper_hsl_tensor,
lower_hsl_tensor,
upper_lab_tensor,
lower_lab_tensor,
upper_lch_tensor,
lower_lch_tensor,
upper_l_eal_tensor,
lower_l_eal_tensor,
upper_oklab_tensor,
lower_oklab_tensor,
upper_oklch_tensor,
lower_oklch_tensor,
upper_okhsv_tensor,
lower_okhsv_tensor,
upper_okhsl_tensor,
lower_okhsl_tensor,
) = self.prepare_tensors_from_images(
image_upper, image_base, mask_image=image_mask, required=tensor_requirements
)
# if not (self.blend_mode == "Normal"):
upper_rgb_l_tensor = self.apply_blend(image_tensors)
output_tensor, alpha_tensor = self.alpha_composite(
srgb_from_linear_srgb(
upper_rgb_l_tensor, alpha=self.adaptive_gamut, steps=(3 if self.high_precision else 1)
),
alpha_upper_tensor,
lower_rgb_tensor,
alpha_lower_tensor,
mask_tensor=mask_tensor,
)
# Restore alpha channel and base mode:
output_tensor = torch.stack(
[output_tensor[0, :, :], output_tensor[1, :, :], output_tensor[2, :, :], alpha_tensor]
)
image_out = pil_image_from_tensor(output_tensor, mode="RGBA")
# Restore ICC profile if base image had one:
if not (cms_profile_base is None):
cms_xform = PIL.ImageCms.buildTransformFromOpenProfiles(
cms_profile_srgb, BytesIO(icc_profile_bytes), "RGBA", image_out.mode
)
image_out = PIL.ImageCms.applyTransform(image_out, cms_xform)
else:
image_out = image_out.convert(image_mode_base)
image_dto = context.images.save(image_out)
return ImageOutput.build(image_dto)
@invocation(
"img_hue_adjust_plus",
title="Adjust Image Hue Plus",
tags=["image", "hue", "oklab", "cielab", "uplab", "lch", "hsv", "hsl", "lab"],
category="image",
version="1.2.0",
)
class AdjustImageHuePlusInvocation(BaseInvocation, WithMetadata, WithBoard):
"""Adjusts the Hue of an image by rotating it in the selected color space"""
image: ImageField = InputField(description="The image to adjust")
space: Literal[tuple(HUE_COLOR_SPACES)] = InputField(
default=HUE_COLOR_SPACES[1],
description="Color space in which to rotate hue by polar coords (*: non-invertible)",
)
degrees: float = InputField(default=0.0, description="Degrees by which to rotate image hue")
preserve_lightness: bool = InputField(default=False, description="Whether to preserve CIELAB lightness values")
ok_adaptive_gamut: float = InputField(
default=0.05, description="Higher preserves chroma at the expense of lightness (Oklab)"
)
ok_high_precision: bool = InputField(