-
Notifications
You must be signed in to change notification settings - Fork 16
/
ComfyI2I.py
1500 lines (1200 loc) · 58.1 KB
/
ComfyI2I.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
# By ManglerFTW (Discord: ManglerFTW)
#
# Copyright 2023 Peter Mango (ManglerFTW)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to
# deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import numpy as np
from collections import namedtuple
import cv2
import torch
import sys
import os
import folder_paths as comfy_paths
from torchvision.ops import masks_to_boxes
import torchvision.transforms.functional as TF
import torch.nn.functional as F
from PIL import Image, ImageFilter, ImageOps
import subprocess
import math
# Check for CUDA availability
device = 'cuda' if torch.cuda.is_available() else 'cpu'
ARRAY_DATATYPE = torch.int32 # Corresponding to 'l'
Rgb = namedtuple('Rgb', ('r', 'g', 'b'))
Hsl = namedtuple('Hsl', ('h', 's', 'l'))
VERY_BIG_SIZE = 1024 * 1024
MAX_RESOLUTION=8192
MODELS_DIR = comfy_paths.models_dir
class cstr(str):
class color:
END = '\33[0m'
BOLD = '\33[1m'
ITALIC = '\33[3m'
UNDERLINE = '\33[4m'
BLINK = '\33[5m'
BLINK2 = '\33[6m'
SELECTED = '\33[7m'
BLACK = '\33[30m'
RED = '\33[31m'
GREEN = '\33[32m'
YELLOW = '\33[33m'
BLUE = '\33[34m'
VIOLET = '\33[35m'
BEIGE = '\33[36m'
WHITE = '\33[37m'
BLACKBG = '\33[40m'
REDBG = '\33[41m'
GREENBG = '\33[42m'
YELLOWBG = '\33[43m'
BLUEBG = '\33[44m'
VIOLETBG = '\33[45m'
BEIGEBG = '\33[46m'
WHITEBG = '\33[47m'
GREY = '\33[90m'
LIGHTRED = '\33[91m'
LIGHTGREEN = '\33[92m'
LIGHTYELLOW = '\33[93m'
LIGHTBLUE = '\33[94m'
LIGHTVIOLET = '\33[95m'
LIGHTBEIGE = '\33[96m'
LIGHTWHITE = '\33[97m'
GREYBG = '\33[100m'
LIGHTREDBG = '\33[101m'
LIGHTGREENBG = '\33[102m'
LIGHTYELLOWBG = '\33[103m'
LIGHTBLUEBG = '\33[104m'
LIGHTVIOLETBG = '\33[105m'
LIGHTBEIGEBG = '\33[106m'
LIGHTWHITEBG = '\33[107m'
@staticmethod
def add_code(name, code):
if not hasattr(cstr.color, name.upper()):
setattr(cstr.color, name.upper(), code)
else:
raise ValueError(f"'cstr' object already contains a code with the name '{name}'.")
def __new__(cls, text):
return super().__new__(cls, text)
def __getattr__(self, attr):
if attr.lower().startswith("_cstr"):
code = getattr(self.color, attr.upper().lstrip("_cstr"))
modified_text = self.replace(f"__{attr[1:]}__", f"{code}")
return cstr(modified_text)
elif attr.upper() in dir(self.color):
code = getattr(self.color, attr.upper())
modified_text = f"{code}{self}{self.color.END}"
return cstr(modified_text)
elif attr.lower() in dir(cstr):
return getattr(cstr, attr.lower())
else:
raise AttributeError(f"'cstr' object has no attribute '{attr}'")
def print(self, **kwargs):
print(self, **kwargs)
def tensor2rgb(t: torch.Tensor) -> torch.Tensor:
size = t.size()
if (len(size) < 4):
return t.unsqueeze(3).repeat(1, 1, 1, 3)
if size[3] == 1:
return t.repeat(1, 1, 1, 3)
elif size[3] == 4:
return t[:, :, :, :3]
else:
return t
def tensor2rgba(t: torch.Tensor) -> torch.Tensor:
size = t.size()
if (len(size) < 4):
return t.unsqueeze(3).repeat(1, 1, 1, 4)
elif size[3] == 1:
return t.repeat(1, 1, 1, 4)
elif size[3] == 3:
alpha_tensor = torch.ones((size[0], size[1], size[2], 1))
return torch.cat((t, alpha_tensor), dim=3)
else:
return t
def tensor2mask(t: torch.Tensor) -> torch.Tensor:
size = t.size()
if (len(size) < 4):
return t
if size[3] == 1:
return t[:,:,:,0]
elif size[3] == 4:
# Not sure what the right thing to do here is. Going to try to be a little smart and use alpha unless all alpha is 1 in case we'll fallback to RGB behavior
if torch.min(t[:, :, :, 3]).item() != 1.:
return t[:,:,:,3]
return TF.rgb_to_grayscale(tensor2rgb(t).permute(0,3,1,2), num_output_channels=1)[:,0,:,:]
def tensor2batch(t: torch.Tensor, bs: torch.Size) -> torch.Tensor:
if len(t.size()) < len(bs):
t = t.unsqueeze(3)
if t.size()[0] < bs[0]:
t.repeat(bs[0], 1, 1, 1)
dim = bs[3]
if dim == 1:
return tensor2mask(t)
elif dim == 3:
return tensor2rgb(t)
elif dim == 4:
return tensor2rgba(t)
def tensors2common(t1: torch.Tensor, t2: torch.Tensor) -> (torch.Tensor, torch.Tensor):
t1s = t1.size()
t2s = t2.size()
if len(t1s) < len(t2s):
t1 = t1.unsqueeze(3)
elif len(t1s) > len(t2s):
t2 = t2.unsqueeze(3)
if len(t1.size()) == 3:
if t1s[0] < t2s[0]:
t1 = t1.repeat(t2s[0], 1, 1)
elif t1s[0] > t2s[0]:
t2 = t2.repeat(t1s[0], 1, 1)
else:
if t1s[0] < t2s[0]:
t1 = t1.repeat(t2s[0], 1, 1, 1)
elif t1s[0] > t2s[0]:
t2 = t2.repeat(t1s[0], 1, 1, 1)
t1s = t1.size()
t2s = t2.size()
if len(t1s) > 3 and t1s[3] < t2s[3]:
return tensor2batch(t1, t2s), t2
elif len(t1s) > 3 and t1s[3] > t2s[3]:
return t1, tensor2batch(t2, t1s)
else:
return t1, t2
# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
# PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
# PIL to Tensor
def pil2tensor_stacked(image):
if isinstance(image, Image.Image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0)
elif isinstance(image, torch.Tensor):
return image
else:
raise ValueError(f"Unexpected datatype for input to 'pil2tensor_stacked'. Expected a PIL Image or tensor, but received type: {type(image)}")
class Color(object):
def __init__(self, r, g, b, proportion):
self.rgb = Rgb(r, g, b)
self.proportion = proportion
def __repr__(self):
return "<colorgram.py Color: {}, {}%>".format(
str(self.rgb), str(self.proportion * 100))
@property
def hsl(self):
try:
return self._hsl
except AttributeError:
self._hsl = Hsl(*hsl(*self.rgb))
return self._hsl
def extract(image_np, number_of_colors, mask_np=None):
# Check and convert the image if needed
if len(image_np.shape) == 2 or image_np.shape[2] != 3: # If grayscale or not RGB
image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
samples = sample(image_np, mask_np)
used = pick_used(samples)
used.sort(key=lambda x: x[0], reverse=True)
return get_colors(samples, used, number_of_colors)
def sample(image, mask=None):
top_two_bits = 0b11000000
sides = 1 << 2
cubes = sides ** 7
samples = torch.zeros((cubes,), dtype=torch.float32, device=device) # Make sure samples is of float32 type
# Handle mask
if mask is not None:
mask_values = (torch.rand_like(mask, dtype=torch.float32) * 255).int()
active_pixels = mask_values > mask
else:
active_pixels = torch.ones_like(image[:, :, 0], dtype=torch.bool)
# Calculate RGB, HSL, and Y
r, g, b = image[:, :, 0], image[:, :, 1], image[:, :, 2]
h, s, l = hsl(r, g, b) # We need to convert the hsl function to use PyTorch
Y = (r * 0.2126 + g * 0.7152 + b * 0.0722).int()
# Packing
packed = ((Y & top_two_bits) << 4) | ((h & top_two_bits) << 2) | (l & top_two_bits)
packed *= 4
# Accumulate samples
packed_active = packed[active_pixels]
r_active, g_active, b_active = r[active_pixels], g[active_pixels], b[active_pixels]
samples.index_add_(0, packed_active, r_active)
samples.index_add_(0, packed_active + 1, g_active)
samples.index_add_(0, packed_active + 2, b_active)
samples.index_add_(0, packed_active + 3, torch.ones_like(packed_active, dtype=torch.float32))
return samples
def pick_used(samples):
# Find indices where count (every 4th value) is non-zero
non_zero_indices = torch.arange(0, samples.size(0), 4, device=samples.device)[samples[3::4] > 0]
# Get counts for non-zero indices
counts = samples[non_zero_indices + 3]
# Combine counts and indices
used = torch.stack((counts, non_zero_indices), dim=-1)
# Convert torch tensors to list of tuples on CPU
used_tuples = [(int(count.item()), int(idx.item())) for count, idx in zip(used[:, 0], used[:, 1])]
return used_tuples
def get_colors(samples, used, number_of_colors):
number_of_colors = min(number_of_colors, len(used))
used = used[:number_of_colors]
# Extract counts and indices
counts, indices = zip(*used)
counts = torch.tensor(counts, dtype=torch.long, device=device)
indices = torch.tensor(indices, dtype=torch.long, device=device)
# Calculate total pixels
total_pixels = torch.sum(counts)
# Get RGB values
r_vals = samples[indices] // counts
g_vals = samples[indices + 1] // counts
b_vals = samples[indices + 2] // counts
# Convert Torch tensors to lists
r_vals_list = r_vals.tolist()
g_vals_list = g_vals.tolist()
b_vals_list = b_vals.tolist()
counts_list = counts.tolist()
# Create Color objects
colors = [Color(r, g, b, count) for r, g, b, count in zip(r_vals_list, g_vals_list, b_vals_list, counts_list)]
# Update proportions
for color in colors:
color.proportion /= total_pixels.item()
return colors
def hsl(r, g, b):
r, g, b = r / 255.0, g / 255.0, b / 255.0
max_val, _ = torch.max(torch.stack([r, g, b]), dim=0)
min_val, _ = torch.min(torch.stack([r, g, b]), dim=0)
diff = max_val - min_val
# Luminance
l = (max_val + min_val) / 2.0
# Saturation
s = torch.where(
(max_val == min_val) | (l == 0),
torch.zeros_like(l),
torch.where(l < 0.5, diff / (max_val + min_val), diff / (2.0 - max_val - min_val))
)
# Hue
conditions = [
max_val == r,
max_val == g,
max_val == b
]
values = [
((g - b) / diff) % 6,
((b - r) / diff) + 2,
((r - g) / diff) + 4
]
h = torch.zeros_like(r)
for condition, value in zip(conditions, values):
h = torch.where(condition, value, h)
h /= 6.0
return (h * 255).int(), (s * 255).int(), (l * 255).int()
def color_distance(pixel_color, palette_color):
return torch.norm(pixel_color - palette_color)
def segment_image(image_torch, palette_colors, mask_torch=None, threshold=128):
"""
Segment the image based on the color similarity of each color in the palette using PyTorch.
"""
if mask_torch is None:
mask_torch = torch.ones(image_torch.shape[:2], device='cuda') * 255
output_image_torch = torch.zeros_like(image_torch)
# Convert palette colors to PyTorch tensor
palette_torch = torch.tensor([list(color.rgb) for color in palette_colors], device='cuda').float()
distances = torch.norm(image_torch.unsqueeze(-2) - palette_torch, dim=-1)
closest_color_indices = torch.argmin(distances, dim=-1)
for idx, palette_color in enumerate(palette_torch):
output_image_torch[closest_color_indices == idx] = palette_color
output_image_torch[mask_torch < threshold] = image_torch[mask_torch < threshold]
# Convert the PyTorch tensor back to a numpy array for saving or further operations
output_image_np = output_image_torch.cpu().numpy().astype('uint8')
return output_image_np
def calculate_luminance_vectorized(colors):
"""Calculate the luminance of an array of RGB colors using PyTorch."""
R, G, B = colors[:, 0], colors[:, 1], colors[:, 2]
return 0.299 * R + 0.587 * G + 0.114 * B
def luminance_match(palette1, palette2):
# Convert palettes to PyTorch tensors
palette1_rgb = torch.tensor([color.rgb for color in palette1], device='cuda').float()
palette2_rgb = torch.tensor([color.rgb for color in palette2], device='cuda').float()
luminance1 = calculate_luminance_vectorized(palette1_rgb)
luminance2 = calculate_luminance_vectorized(palette2_rgb)
# Sort luminances and get the sorted indices
sorted_indices1 = torch.argsort(luminance1)
sorted_indices2 = torch.argsort(luminance2)
reordered_palette2 = [None] * len(palette2)
# Match colors based on sorted luminance order
for idx1, idx2 in zip(sorted_indices1.cpu().numpy(), sorted_indices2.cpu().numpy()):
print(f"idx1: {idx1}, idx2: {idx2}") # Add this to debug
reordered_palette2[idx1] = palette2[idx2]
return reordered_palette2
def apply_blur(image_torch, blur_radius, blur_amount):
image_torch = image_torch.float().div(255.0)
channels = image_torch.shape[2]
kernel_size = int(6 * blur_radius + 1)
kernel_size += 1 if kernel_size % 2 == 0 else 0
# Calculate the padding required to keep the output size the same
padding = kernel_size // 2
# Create a Gaussian kernel
x = torch.linspace(-blur_amount, blur_amount, kernel_size).to(image_torch.device)
x = torch.exp(-x**2 / (2 * blur_radius**2))
x /= x.sum()
kernel = x[:, None] * x[None, :]
# Apply the kernel using depthwise convolution
channels = image_torch.shape[-1]
kernel = kernel[None, None, ...].repeat(channels, 1, 1, 1)
blurred = F.conv2d(image_torch.permute(2, 0, 1)[None, ...], kernel, groups=channels, padding=padding)
# Convert the tensor back to byte and de-normalize
blurred = (blurred * 255.0).byte().squeeze(0).permute(1, 2, 0)
return blurred
def refined_replace_and_blend_colors(Source_np, img_np, palette1, modified_palette2, blur_radius=0, blur_amount=0, mask_torch=None):
# Convert numpy arrays to torch tensors on GPU
device = 'cuda' if torch.cuda.is_available() else 'cpu'
Source = torch.from_numpy(Source_np).float().to(device)
img_torch = torch.tensor(img_np, device=device).float()
palette1_rgb = torch.stack([torch.tensor(color.rgb, device=device).float() if hasattr(color, 'rgb') else torch.tensor(color, device=device).float() for color in palette1])
modified_palette2_rgb = torch.stack([torch.tensor(color.rgb, device=device).float() if hasattr(color, 'rgb') else torch.tensor(color, device=device).float() for color in modified_palette2])
# Direct color replacement using broadcasting
distances = torch.norm(img_torch[:, :, None] - palette1_rgb, dim=-1)
closest_indices = torch.argmin(distances, dim=-1)
intermediate_output = modified_palette2_rgb[closest_indices]
# Convert to uint8 if not already
intermediate_output = torch.clamp(intermediate_output, 0, 255).byte()
# Apply blur if needed
if blur_radius > 0 and blur_amount > 0:
blurred_output = apply_blur(intermediate_output, blur_radius, blur_amount)
else:
blurred_output = intermediate_output
# Blend based on the mask's intensity values if provided
if mask_torch is not None:
three_channel_mask = mask_torch[:, :, None].expand_as(Source)
output_torch = Source * (1 - three_channel_mask) + blurred_output.float() * three_channel_mask
else:
output_torch = blurred_output
output_np = output_torch.cpu().numpy().astype(np.uint8)
return output_np
def torch_rgb_to_hsv(rgb):
"""
Convert an RGB image to HSV.
Assumes rgb is a PyTorch tensor with values in [0, 1].
"""
# Get R, G, B values
r = rgb[..., 0]
g = rgb[..., 1]
b = rgb[..., 2]
max_val, _ = torch.max(rgb, dim=-1)
min_val, _ = torch.min(rgb, dim=-1)
diff = max_val - min_val
# Calculate Hue
h = torch.zeros_like(r)
h[diff == 0] = 0
mask = (max_val == r) & (diff != 0)
h[mask] = (60 * ((g[mask] - b[mask]) / diff[mask]) + 360) % 360
mask = max_val == g
h[mask] = (60 * ((b[mask] - r[mask]) / diff[mask]) + 120) % 360
mask = max_val == b
h[mask] = (60 * ((r[mask] - g[mask]) / diff[mask]) + 240) % 360
h = h / 360. # Normalize to [0, 1]
# Calculate Saturation
s = torch.zeros_like(r)
s[max_val != 0] = diff[max_val != 0] / max_val[max_val != 0]
# Value
v = max_val
hsv = torch.stack([h, s, v], dim=-1)
return hsv
def torch_hsv_to_rgb(hsv):
"""
Convert an HSV image to RGB.
Assumes hsv is a PyTorch tensor with values in [0, 1] for hue and [0, 1] for saturation/value.
"""
h = hsv[..., 0] * 360.
s = hsv[..., 1]
v = hsv[..., 2]
c = v * s
hh = h / 60.
x = c * (1 - torch.abs(hh % 2 - 1))
m = v - c
r, g, b = v, v, v # Initialize with value
mask = (hh >= 0) & (hh < 1)
r[mask] = c[mask]
g[mask] = x[mask]
mask = (hh >= 1) & (hh < 2)
r[mask] = x[mask]
g[mask] = c[mask]
mask = (hh >= 2) & (hh < 3)
g[mask] = c[mask]
b[mask] = x[mask]
mask = (hh >= 3) & (hh < 4)
g[mask] = x[mask]
b[mask] = c[mask]
mask = (hh >= 4) & (hh < 5)
r[mask] = x[mask]
b[mask] = c[mask]
mask = (hh >= 5) & (hh < 6)
r[mask] = c[mask]
b[mask] = x[mask]
r += m
g += m
b += m
rgb = torch.stack([r, g, b], dim=-1)
return rgb
def retain_luminance_hsv_swap(img1_np, img2_np, strength):
"""
Blend two images while retaining the luminance of the first.
The blending is controlled by the strength parameter.
Assumes img1_np and img2_np are numpy arrays in BGR format.
"""
# Convert BGR to RGB
img1_rgb_np = cv2.cvtColor(img1_np, cv2.COLOR_BGR2RGB).astype(float) / 255.0
img2_rgb_np = cv2.cvtColor(img2_np, cv2.COLOR_BGR2RGB).astype(float) / 255.0
# Blend the two RGB images linearly based on the strength
blended_rgb_np = (1 - strength) * img1_rgb_np + strength * img2_rgb_np
# Convert the blended RGB image and the original RGB image to YUV
blended_yuv_np = cv2.cvtColor((blended_rgb_np * 255).astype(np.uint8), cv2.COLOR_RGB2YUV)
img1_yuv_np = cv2.cvtColor(img1_np, cv2.COLOR_BGR2YUV)
# Replace the Y channel (luminance) of the blended image with the original image's luminance
blended_yuv_np[:,:,0] = img1_yuv_np[:,:,0]
# Convert back to BGR
result_bgr_np = cv2.cvtColor(blended_yuv_np, cv2.COLOR_YUV2BGR)
return result_bgr_np
def adjust_gamma_contrast(image_np, gamma, contrast, brightness, mask_np=None):
# Ensure CUDA is available
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Transfer data to PyTorch tensors and move to the appropriate device
image_torch = torch.tensor(image_np, dtype=torch.float32).to(device)
# Gamma correction using a lookup table
inv_gamma = 1.0 / gamma
table = torch.tensor([(i / 255.0) ** inv_gamma * 255 for i in range(256)], device=device).float()
gamma_corrected = torch.index_select(table, 0, image_torch.long().flatten()).reshape_as(image_torch)
# Contrast and brightness adjustment
contrast_adjusted = contrast * gamma_corrected + brightness
contrast_adjusted = torch.clamp(contrast_adjusted, 0, 255).byte()
# If mask is provided, blend the original and adjusted images
if mask_np is not None:
mask_torch = torch.tensor(mask_np, device=device).float() / 255.0
three_channel_mask = mask_torch.unsqueeze(-1).expand_as(image_torch)
contrast_adjusted = image_torch * (1 - three_channel_mask) + contrast_adjusted.float() * three_channel_mask
# Transfer data back to numpy array
result_np = contrast_adjusted.cpu().numpy()
return result_np
def CutByMask(image, mask, force_resize_width, force_resize_height, mask_mapping_optional):
if len(image.shape) < 4:
C = 1
else:
C = image.shape[3]
# We operate on RGBA to keep the code clean and then convert back after
image = tensor2rgba(image)
mask = tensor2mask(mask)
if mask_mapping_optional is not None:
mask_mapping_optional = mask_mapping_optional.long()
image = image[mask_mapping_optional]
# Scale the mask to match the image size if it isn't
B, H, W, _ = image.shape
mask = F.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest')[:,0,:,:]
MB, _, _ = mask.shape
if MB < B:
assert(B % MB == 0)
mask = mask.repeat(B // MB, 1, 1)
# Masks to boxes
is_empty = ~torch.gt(torch.max(torch.reshape(mask, [B, H * W]), dim=1).values, 0.)
mask[is_empty,0,0] = 1.
boxes = masks_to_boxes(mask)
mask[is_empty,0,0] = 0.
min_x = boxes[:,0]
min_y = boxes[:,1]
max_x = boxes[:,2]
max_y = boxes[:,3]
width = max_x - min_x + 1
height = max_y - min_y + 1
use_width = int(torch.max(width).item())
use_height = int(torch.max(height).item())
if force_resize_width > 0:
use_width = force_resize_width
if force_resize_height > 0:
use_height = force_resize_height
print("use_width: ", use_width)
print("use_height: ", use_height)
alpha_mask = torch.ones((B, H, W, 4))
alpha_mask[:,:,:,3] = mask
image = image * alpha_mask
result = torch.zeros((B, use_height, use_width, 4))
for i in range(0, B):
if not is_empty[i]:
ymin = int(min_y[i].item())
ymax = int(max_y[i].item())
xmin = int(min_x[i].item())
xmax = int(max_x[i].item())
single = (image[i, ymin:ymax+1, xmin:xmax+1,:]).unsqueeze(0)
resized = F.interpolate(single.permute(0, 3, 1, 2), size=(use_height, use_width), mode='bicubic').permute(0, 2, 3, 1)
result[i] = resized[0]
# Preserve our type unless we were previously RGB and added non-opaque alpha due to the mask size
if C == 1:
print("C == 1 output image shape: ", tensor2mask(result).shape)
return tensor2mask(result)
elif C == 3 and torch.min(result[:,:,:,3]) == 1:
print("C == 3 output image shape: ", tensor2rgb(result).shape)
return tensor2rgb(result)
else:
print("else result shape: ", result.shape)
return result
def combine(image1, image2, op, clamp_result, round_result):
image1, image2 = tensors2common(image1, image2)
if op == "union (max)":
result = torch.max(image1, image2)
elif op == "intersection (min)":
result = torch.min(image1, image2)
elif op == "difference":
result = image1 - image2
elif op == "multiply":
result = image1 * image2
elif op == "multiply_alpha":
image1 = tensor2rgba(image1)
image2 = tensor2mask(image2)
result = torch.cat((image1[:, :, :, :3], (image1[:, :, :, 3] * image2).unsqueeze(3)), dim=3)
elif op == "add":
result = image1 + image2
elif op == "greater_or_equal":
result = torch.where(image1 >= image2, 1., 0.)
elif op == "greater":
result = torch.where(image1 > image2, 1., 0.)
if clamp_result == "yes":
result = torch.min(torch.max(result, torch.tensor(0.)), torch.tensor(1.))
if round_result == "yes":
result = torch.round(result)
return result
def apply_color_correction(target_image, source_image, factor=1):
if not isinstance(source_image, (torch.Tensor, Image.Image)):
raise ValueError(f"Unexpected datatype for 'source_image' at method start. Expected a tensor or PIL Image, but received type: {type(source_image)}")
# Ensure source_image is a tensor
if isinstance(source_image, Image.Image): # Check if it's a PIL Image
source_image = pil2tensor_stacked(source_image) # Convert it to tensor
if not isinstance(source_image, (torch.Tensor, Image.Image)):
raise ValueError(f"Unexpected datatype for 'source_image'. Expected a tensor or PIL Image, but received type: {type(source_image)}")
# Get the batch size
batch_size = source_image.shape[0]
output_images = []
for i in range(batch_size):
# Convert the source and target images to NumPy arrays for the i-th image in the batch
source_numpy = source_image[i, ...].numpy()
target_numpy = target_image[i, ...].numpy()
# Convert to float32
source_numpy = source_numpy.astype(np.float32)
target_numpy = target_numpy.astype(np.float32)
# If the images have an alpha channel, remove it for the color transformations
if source_numpy.shape[-1] == 4:
source_numpy = source_numpy[..., :3]
if target_numpy.shape[-1] == 4:
target_numpy = target_numpy[..., :3]
# Compute the mean and standard deviation of the color channels for both images
target_mean, target_std = np.mean(source_numpy, axis=(0, 1)), np.std(source_numpy, axis=(0, 1))
source_mean, source_std = np.mean(target_numpy, axis=(0, 1)), np.std(target_numpy, axis=(0, 1))
adjusted_source_mean = target_mean + factor * (target_mean - source_mean)
adjusted_source_std = target_std + factor * (target_std - source_std)
# Normalize the target image (zero mean and unit variance)
target_norm = (target_numpy - target_mean) / target_std
# Scale and shift the normalized target image to match the exaggerated source image statistics
matched_rgb = target_norm * adjusted_source_std + adjusted_source_mean
# Clip values to [0, 1] and convert to PIL Image
img = Image.fromarray(np.clip(matched_rgb * 255, 0, 255).astype('uint8'), 'RGB')
# Convert the PIL Image to a tensor and append to the list
img_tensor = pil2tensor_stacked(img)
output_images.append(img_tensor)
# Stack the list of tensors to get the batch of corrected images
stacked_images = torch.stack(output_images)
return stacked_images
def PasteByMask(image_base, image_to_paste, mask, resize_behavior, mask_mapping_optional):
image_base = tensor2rgba(image_base)
image_to_paste = tensor2rgba(image_to_paste)
mask = tensor2mask(mask)
# Scale the mask to be a matching size if it isn't
B, H, W, C = image_base.shape
MB = mask.shape[0]
PB = image_to_paste.shape[0]
if mask_mapping_optional is None:
if B < PB:
assert(PB % B == 0)
image_base = image_base.repeat(PB // B, 1, 1, 1)
B, H, W, C = image_base.shape
if MB < B:
assert(B % MB == 0)
mask = mask.repeat(B // MB, 1, 1)
elif B < MB:
assert(MB % B == 0)
image_base = image_base.repeat(MB // B, 1, 1, 1)
if PB < B:
assert(B % PB == 0)
image_to_paste = image_to_paste.repeat(B // PB, 1, 1, 1)
mask = F.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest')[:,0,:,:]
MB, MH, MW = mask.shape
# masks_to_boxes errors if the tensor is all zeros, so we'll add a single pixel and zero it out at the end
is_empty = ~torch.gt(torch.max(torch.reshape(mask,[MB, MH * MW]), dim=1).values, 0.)
mask[is_empty,0,0] = 1.
boxes = masks_to_boxes(mask)
mask[is_empty,0,0] = 0.
min_x = boxes[:,0]
min_y = boxes[:,1]
max_x = boxes[:,2]
max_y = boxes[:,3]
mid_x = (min_x + max_x) / 2
mid_y = (min_y + max_y) / 2
target_width = max_x - min_x + 1
target_height = max_y - min_y + 1
result = image_base.detach().clone()
for i in range(0, MB):
if i >= len(image_to_paste):
raise ValueError(f"image_to_paste does not have an entry for mask index {i}")
if is_empty[i]:
continue
else:
image_index = i
if mask_mapping_optional is not None:
image_index = mask_mapping_optional[i].item()
source_size = image_to_paste.size()
SB, SH, SW, _ = image_to_paste.shape
# Figure out the desired size
width = int(target_width[i].item())
height = int(target_height[i].item())
if resize_behavior == "keep_ratio_fill":
target_ratio = width / height
actual_ratio = SW / SH
if actual_ratio > target_ratio:
width = int(height * actual_ratio)
elif actual_ratio < target_ratio:
height = int(width / actual_ratio)
elif resize_behavior == "keep_ratio_fit":
target_ratio = width / height
actual_ratio = SW / SH
if actual_ratio > target_ratio:
height = int(width / actual_ratio)
elif actual_ratio < target_ratio:
width = int(height * actual_ratio)
elif resize_behavior == "source_size" or resize_behavior == "source_size_unmasked":
width = SW
height = SH
# Resize the image we're pasting if needed
resized_image = image_to_paste[i].unsqueeze(0)
if SH != height or SW != width:
resized_image = F.interpolate(resized_image.permute(0, 3, 1, 2), size=(height,width), mode='bicubic').permute(0, 2, 3, 1)
pasting = torch.ones([H, W, C])
ymid = float(mid_y[i].item())
ymin = int(math.floor(ymid - height / 2)) + 1
ymax = int(math.floor(ymid + height / 2)) + 1
xmid = float(mid_x[i].item())
xmin = int(math.floor(xmid - width / 2)) + 1
xmax = int(math.floor(xmid + width / 2)) + 1
_, source_ymax, source_xmax, _ = resized_image.shape
source_ymin, source_xmin = 0, 0
if xmin < 0:
source_xmin = abs(xmin)
xmin = 0
if ymin < 0:
source_ymin = abs(ymin)
ymin = 0
if xmax > W:
source_xmax -= (xmax - W)
xmax = W
if ymax > H:
source_ymax -= (ymax - H)
ymax = H
pasting[ymin:ymax, xmin:xmax, :] = resized_image[0, source_ymin:source_ymax, source_xmin:source_xmax, :]
pasting[:, :, 3] = 1.
pasting_alpha = torch.zeros([H, W])
pasting_alpha[ymin:ymax, xmin:xmax] = resized_image[0, source_ymin:source_ymax, source_xmin:source_xmax, 3]
if resize_behavior == "keep_ratio_fill" or resize_behavior == "source_size_unmasked":
# If we explicitly want to fill the area, we are ok with extending outside
paste_mask = pasting_alpha.unsqueeze(2).repeat(1, 1, 4)
else:
paste_mask = torch.min(pasting_alpha, mask[i]).unsqueeze(2).repeat(1, 1, 4)
result[image_index] = pasting * paste_mask + result[image_index] * (1. - paste_mask)
return result
class Mask_Ops:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"text": ("STRING", {"default":"", "multiline": False}),
"separate_mask": ("INT", {"default":0, "min":0, "max":1, "step":1}),
"text_sigma": ("INT", {"default":30, "min":0, "max":150, "step":1}),
"use_text": ("INT", {"default":0, "min":0, "max":1, "step":1}),
"blend_percentage": ("FLOAT", {"default": 0, "min": 0.0, "max": 1.0, "step": 0.01}),
"black_level": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 255.0, "step": 0.1}),
"mid_level": ("FLOAT", {"default": 127.5, "min": 0.0, "max": 255.0, "step": 0.1}),
"white_level": ("FLOAT", {"default": 255, "min": 0.0, "max": 255.0, "step": 0.1}),
"channel": (["red", "green", "blue"],),
"shrink_grow": ("INT", {"default": 0, "min": -128, "max": 128, "step": 1}),
"invert": ("INT", {"default":0, "min":0, "max":1, "step":1}),
"blur_radius": ("FLOAT", {"default": 5.0, "min": 0.0, "max": 1024, "step": 0.1}),
},
"optional": {
"mask": ("MASK",),
},
}
CATEGORY = "I2I"
RETURN_TYPES = ("IMAGE", "MASK", "MASK_MAPPING",)
RETURN_NAMES = ("mask_image", "mask", "mask mapping")
FUNCTION = "Mask_Ops"
def Mask_Ops(self, image, text, separate_mask, text_sigma, use_text, blend_percentage, black_level, mid_level, white_level, channel, shrink_grow, invert=0, blur_radius=5.0, mask=None):
channels = ["red", "green", "blue"]
# Freeze PIP modules
def packages(versions=False):
import sys
import subprocess
return [( r.decode().split('==')[0] if not versions else r.decode() ) for r in subprocess.check_output([sys.executable, '-s', '-m', 'pip', 'freeze']).split()]
# PIL to Mask
def pil2mask(image):
image_np = np.array(image.convert("L")).astype(np.float32) / 255.0
mask = torch.from_numpy(image_np)
return 1.0 - mask
def gaussian_region(image, radius=5.0):
image = ImageOps.invert(image.convert("L"))
image = image.filter(ImageFilter.GaussianBlur(radius=int(radius)))
return image.convert("RGB")
# scipy handling
if 'scipy' not in packages():
cstr("Installing `scipy` ...").msg.print()
subprocess.check_call([sys.executable, '-s', '-m', 'pip', 'install', 'scipy'])
try:
import scipy
except ImportError as e:
cstr("Unable to import tools for certain masking procedures.").msg.print()
print(e)
def smooth_region(image, tolerance):
from scipy.ndimage import gaussian_filter
image = image.convert("L")
mask_array = np.array(image)
smoothed_array = gaussian_filter(mask_array, sigma=tolerance)
threshold = np.max(smoothed_array) / 2
smoothed_mask = np.where(smoothed_array >= threshold, 255, 0).astype(np.uint8)
smoothed_image = Image.fromarray(smoothed_mask, mode="L")
return ImageOps.invert(smoothed_image.convert("RGB"))
def erode_region(image, iterations):
from scipy.ndimage import binary_erosion
image = image.convert("L")
binary_mask = np.array(image) > 0
eroded_mask = binary_erosion(binary_mask, iterations=iterations)
eroded_image = Image.fromarray(eroded_mask.astype(np.uint8) * 255, mode="L")
return ImageOps.invert(eroded_image.convert("RGB"))
def dilate_region(image, iterations):
from scipy.ndimage import binary_dilation
image = image.convert("L")
binary_mask = np.array(image) > 0
dilated_mask = binary_dilation(binary_mask, iterations=iterations)
dilated_image = Image.fromarray(dilated_mask.astype(np.uint8) * 255, mode="L")
return ImageOps.invert(dilated_image.convert("RGB"))
def erode(masks, iterations):
iterations = iterations * -1
if masks.ndim > 3:
regions = []
for mask in masks:
mask_np = np.clip(255. * mask.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
pil_image = Image.fromarray(mask_np, mode="L")
region_mask = erode_region(pil_image, iterations)
region_tensor = pil2mask(region_mask).unsqueeze(0).unsqueeze(1)
regions.append(region_tensor)
regions_tensor = torch.cat(regions, dim=0)
return regions_tensor
else:
mask_np = np.clip(255. * masks.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
pil_image = Image.fromarray(mask_np, mode="L")
region_mask = erode_region(pil_image, iterations)
region_tensor = pil2mask(region_mask).unsqueeze(0).unsqueeze(1)
return region_tensor