forked from cubiq/ComfyUI_essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.py
1770 lines (1457 loc) · 64.1 KB
/
image.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
from .utils import max_, min_
from nodes import MAX_RESOLUTION
import comfy.utils
from nodes import SaveImage
from node_helpers import pillow
from PIL import Image, ImageOps
import kornia
import torch
import torch.nn.functional as F
import torchvision.transforms.v2 as T
#import warnings
#warnings.filterwarnings('ignore', module="torchvision")
import math
import os
import numpy as np
import folder_paths
from pathlib import Path
import random
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Image analysis
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
class ImageEnhanceDifference:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image1": ("IMAGE",),
"image2": ("IMAGE",),
"exponent": ("FLOAT", { "default": 0.75, "min": 0.00, "max": 1.00, "step": 0.05, }),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image analysis"
def execute(self, image1, image2, exponent):
if image1.shape[1:] != image2.shape[1:]:
image2 = comfy.utils.common_upscale(image2.permute([0,3,1,2]), image1.shape[2], image1.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
diff_image = image1 - image2
diff_image = torch.pow(diff_image, exponent)
diff_image = torch.clamp(diff_image, 0, 1)
return(diff_image,)
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Batch tools
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
class ImageBatchMultiple:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image_1": ("IMAGE",),
"method": (["nearest-exact", "bilinear", "area", "bicubic", "lanczos"], { "default": "lanczos" }),
}, "optional": {
"image_2": ("IMAGE",),
"image_3": ("IMAGE",),
"image_4": ("IMAGE",),
"image_5": ("IMAGE",),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image batch"
def execute(self, image_1, method, image_2=None, image_3=None, image_4=None, image_5=None):
out = image_1
if image_2 is not None:
if image_1.shape[1:] != image_2.shape[1:]:
image_2 = comfy.utils.common_upscale(image_2.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
out = torch.cat((image_1, image_2), dim=0)
if image_3 is not None:
if image_1.shape[1:] != image_3.shape[1:]:
image_3 = comfy.utils.common_upscale(image_3.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
out = torch.cat((out, image_3), dim=0)
if image_4 is not None:
if image_1.shape[1:] != image_4.shape[1:]:
image_4 = comfy.utils.common_upscale(image_4.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
out = torch.cat((out, image_4), dim=0)
if image_5 is not None:
if image_1.shape[1:] != image_5.shape[1:]:
image_5 = comfy.utils.common_upscale(image_5.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
out = torch.cat((out, image_5), dim=0)
return (out,)
class ImageExpandBatch:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"size": ("INT", { "default": 16, "min": 1, "step": 1, }),
"method": (["expand", "repeat all", "repeat first", "repeat last"],)
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image batch"
def execute(self, image, size, method):
orig_size = image.shape[0]
if orig_size == size:
return (image,)
if size <= 1:
return (image[:size],)
if 'expand' in method:
out = torch.empty([size] + list(image.shape)[1:], dtype=image.dtype, device=image.device)
if size < orig_size:
scale = (orig_size - 1) / (size - 1)
for i in range(size):
out[i] = image[min(round(i * scale), orig_size - 1)]
else:
scale = orig_size / size
for i in range(size):
out[i] = image[min(math.floor((i + 0.5) * scale), orig_size - 1)]
elif 'all' in method:
out = image.repeat([math.ceil(size / image.shape[0])] + [1] * (len(image.shape) - 1))[:size]
elif 'first' in method:
if size < image.shape[0]:
out = image[:size]
else:
out = torch.cat([image[:1].repeat(size-image.shape[0], 1, 1, 1), image], dim=0)
elif 'last' in method:
if size < image.shape[0]:
out = image[:size]
else:
out = torch.cat((image, image[-1:].repeat((size-image.shape[0], 1, 1, 1))), dim=0)
return (out,)
class ImageFromBatch:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE", ),
"start": ("INT", { "default": 0, "min": 0, "step": 1, }),
"length": ("INT", { "default": -1, "min": -1, "step": 1, }),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image batch"
def execute(self, image, start, length):
if length<0:
length = image.shape[0]
start = min(start, image.shape[0]-1)
length = min(image.shape[0]-start, length)
return (image[start:start + length], )
class ImageListToBatch:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
INPUT_IS_LIST = True
CATEGORY = "essentials/image batch"
def execute(self, image):
shape = image[0].shape[1:3]
out = []
for i in range(len(image)):
img = image[i]
if image[i].shape[1:3] != shape:
img = comfy.utils.common_upscale(img.permute([0,3,1,2]), shape[1], shape[0], upscale_method='bicubic', crop='center').permute([0,2,3,1])
out.append(img)
out = torch.cat(out, dim=0)
return (out,)
class ImageBatchToList:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE",)
OUTPUT_IS_LIST = (True,)
FUNCTION = "execute"
CATEGORY = "essentials/image batch"
def execute(self, image):
return ([image[i].unsqueeze(0) for i in range(image.shape[0])], )
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Image manipulation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
class ImageCompositeFromMaskBatch:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image_from": ("IMAGE", ),
"image_to": ("IMAGE", ),
"mask": ("MASK", )
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, image_from, image_to, mask):
frames = mask.shape[0]
if image_from.shape[1] != image_to.shape[1] or image_from.shape[2] != image_to.shape[2]:
image_to = comfy.utils.common_upscale(image_to.permute([0,3,1,2]), image_from.shape[2], image_from.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
if frames < image_from.shape[0]:
image_from = image_from[:frames]
elif frames > image_from.shape[0]:
image_from = torch.cat((image_from, image_from[-1].unsqueeze(0).repeat(frames-image_from.shape[0], 1, 1, 1)), dim=0)
mask = mask.unsqueeze(3).repeat(1, 1, 1, 3)
if image_from.shape[1] != mask.shape[1] or image_from.shape[2] != mask.shape[2]:
mask = comfy.utils.common_upscale(mask.permute([0,3,1,2]), image_from.shape[2], image_from.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
out = mask * image_to + (1 - mask) * image_from
return (out, )
class ImageComposite:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"destination": ("IMAGE",),
"source": ("IMAGE",),
"x": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
"y": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
"offset_x": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
"offset_y": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
},
"optional": {
"mask": ("MASK",),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, destination, source, x, y, offset_x, offset_y, mask=None):
if mask is None:
mask = torch.ones_like(source)[:,:,:,0]
mask = mask.unsqueeze(-1).repeat(1, 1, 1, 3)
if mask.shape[1:3] != source.shape[1:3]:
mask = F.interpolate(mask.permute([0, 3, 1, 2]), size=(source.shape[1], source.shape[2]), mode='bicubic')
mask = mask.permute([0, 2, 3, 1])
if mask.shape[0] > source.shape[0]:
mask = mask[:source.shape[0]]
elif mask.shape[0] < source.shape[0]:
mask = torch.cat((mask, mask[-1:].repeat((source.shape[0]-mask.shape[0], 1, 1, 1))), dim=0)
if destination.shape[0] > source.shape[0]:
destination = destination[:source.shape[0]]
elif destination.shape[0] < source.shape[0]:
destination = torch.cat((destination, destination[-1:].repeat((source.shape[0]-destination.shape[0], 1, 1, 1))), dim=0)
if not isinstance(x, list):
x = [x]
if not isinstance(y, list):
y = [y]
if len(x) < destination.shape[0]:
x = x + [x[-1]] * (destination.shape[0] - len(x))
if len(y) < destination.shape[0]:
y = y + [y[-1]] * (destination.shape[0] - len(y))
x = [i + offset_x for i in x]
y = [i + offset_y for i in y]
output = []
for i in range(destination.shape[0]):
d = destination[i].clone()
s = source[i]
m = mask[i]
if x[i]+source.shape[2] > destination.shape[2]:
s = s[:, :, :destination.shape[2]-x[i], :]
m = m[:, :, :destination.shape[2]-x[i], :]
if y[i]+source.shape[1] > destination.shape[1]:
s = s[:, :destination.shape[1]-y[i], :, :]
m = m[:destination.shape[1]-y[i], :, :]
#output.append(s * m + d[y[i]:y[i]+s.shape[0], x[i]:x[i]+s.shape[1], :] * (1 - m))
d[y[i]:y[i]+s.shape[0], x[i]:x[i]+s.shape[1], :] = s * m + d[y[i]:y[i]+s.shape[0], x[i]:x[i]+s.shape[1], :] * (1 - m)
output.append(d)
output = torch.stack(output)
# apply the source to the destination at XY position using the mask
#for i in range(destination.shape[0]):
# output[i, y[i]:y[i]+source.shape[1], x[i]:x[i]+source.shape[2], :] = source * mask + destination[i, y[i]:y[i]+source.shape[1], x[i]:x[i]+source.shape[2], :] * (1 - mask)
#for x_, y_ in zip(x, y):
# output[:, y_:y_+source.shape[1], x_:x_+source.shape[2], :] = source * mask + destination[:, y_:y_+source.shape[1], x_:x_+source.shape[2], :] * (1 - mask)
#output[:, y:y+source.shape[1], x:x+source.shape[2], :] = source * mask + destination[:, y:y+source.shape[1], x:x+source.shape[2], :] * (1 - mask)
#output = destination * (1 - mask) + source * mask
return (output,)
class ImageResize:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }),
"height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }),
"interpolation": (["nearest", "bilinear", "bicubic", "area", "nearest-exact", "lanczos"],),
"method": (["stretch", "keep proportion", "fill / crop", "pad"],),
"condition": (["always", "downscale if bigger", "upscale if smaller", "if bigger area", "if smaller area"],),
"multiple_of": ("INT", { "default": 0, "min": 0, "max": 512, "step": 1, }),
}
}
RETURN_TYPES = ("IMAGE", "INT", "INT",)
RETURN_NAMES = ("IMAGE", "width", "height",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, image, width, height, method="stretch", interpolation="nearest", condition="always", multiple_of=0, keep_proportion=False):
_, oh, ow, _ = image.shape
x = y = x2 = y2 = 0
pad_left = pad_right = pad_top = pad_bottom = 0
if keep_proportion:
method = "keep proportion"
if multiple_of > 1:
width = width - (width % multiple_of)
height = height - (height % multiple_of)
if method == 'keep proportion' or method == 'pad':
if width == 0 and oh < height:
width = MAX_RESOLUTION
elif width == 0 and oh >= height:
width = ow
if height == 0 and ow < width:
height = MAX_RESOLUTION
elif height == 0 and ow >= width:
height = oh
ratio = min(width / ow, height / oh)
new_width = round(ow*ratio)
new_height = round(oh*ratio)
if method == 'pad':
pad_left = (width - new_width) // 2
pad_right = width - new_width - pad_left
pad_top = (height - new_height) // 2
pad_bottom = height - new_height - pad_top
width = new_width
height = new_height
elif method.startswith('fill'):
width = width if width > 0 else ow
height = height if height > 0 else oh
ratio = max(width / ow, height / oh)
new_width = round(ow*ratio)
new_height = round(oh*ratio)
x = (new_width - width) // 2
y = (new_height - height) // 2
x2 = x + width
y2 = y + height
if x2 > new_width:
x -= (x2 - new_width)
if x < 0:
x = 0
if y2 > new_height:
y -= (y2 - new_height)
if y < 0:
y = 0
width = new_width
height = new_height
else:
width = width if width > 0 else ow
height = height if height > 0 else oh
if "always" in condition \
or ("downscale if bigger" == condition and (oh > height or ow > width)) or ("upscale if smaller" == condition and (oh < height or ow < width)) \
or ("bigger area" in condition and (oh * ow > height * width)) or ("smaller area" in condition and (oh * ow < height * width)):
outputs = image.permute(0,3,1,2)
if interpolation == "lanczos":
outputs = comfy.utils.lanczos(outputs, width, height)
else:
outputs = F.interpolate(outputs, size=(height, width), mode=interpolation)
if method == 'pad':
if pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0:
outputs = F.pad(outputs, (pad_left, pad_right, pad_top, pad_bottom), value=0)
outputs = outputs.permute(0,2,3,1)
if method.startswith('fill'):
if x > 0 or y > 0 or x2 > 0 or y2 > 0:
outputs = outputs[:, y:y2, x:x2, :]
else:
outputs = image
if multiple_of > 1 and (outputs.shape[2] % multiple_of != 0 or outputs.shape[1] % multiple_of != 0):
width = outputs.shape[2]
height = outputs.shape[1]
x = (width % multiple_of) // 2
y = (height % multiple_of) // 2
x2 = width - ((width % multiple_of) - x)
y2 = height - ((height % multiple_of) - y)
outputs = outputs[:, y:y2, x:x2, :]
outputs = torch.clamp(outputs, 0, 1)
return(outputs, outputs.shape[2], outputs.shape[1],)
class ImageFlip:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"axis": (["x", "y", "xy"],),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, image, axis):
dim = ()
if "y" in axis:
dim += (1,)
if "x" in axis:
dim += (2,)
image = torch.flip(image, dim)
return(image,)
class ImageCrop:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"width": ("INT", { "default": 256, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
"height": ("INT", { "default": 256, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
"position": (["top-left", "top-center", "top-right", "right-center", "bottom-right", "bottom-center", "bottom-left", "left-center", "center"],),
"x_offset": ("INT", { "default": 0, "min": -99999, "step": 1, }),
"y_offset": ("INT", { "default": 0, "min": -99999, "step": 1, }),
}
}
RETURN_TYPES = ("IMAGE","INT","INT",)
RETURN_NAMES = ("IMAGE","x","y",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, image, width, height, position, x_offset, y_offset):
_, oh, ow, _ = image.shape
width = min(ow, width)
height = min(oh, height)
if "center" in position:
x = round((ow-width) / 2)
y = round((oh-height) / 2)
if "top" in position:
y = 0
if "bottom" in position:
y = oh-height
if "left" in position:
x = 0
if "right" in position:
x = ow-width
x += x_offset
y += y_offset
x2 = x+width
y2 = y+height
if x2 > ow:
x2 = ow
if x < 0:
x = 0
if y2 > oh:
y2 = oh
if y < 0:
y = 0
image = image[:, y:y2, x:x2, :]
return(image, x, y, )
class ImageTile:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"rows": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
"cols": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
"overlap": ("FLOAT", { "default": 0, "min": 0, "max": 0.5, "step": 0.01, }),
"overlap_x": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
"overlap_y": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
}
}
RETURN_TYPES = ("IMAGE", "INT", "INT", "INT", "INT")
RETURN_NAMES = ("IMAGE", "tile_width", "tile_height", "overlap_x", "overlap_y",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, image, rows, cols, overlap, overlap_x, overlap_y):
h, w = image.shape[1:3]
tile_h = h // rows
tile_w = w // cols
h = tile_h * rows
w = tile_w * cols
overlap_h = int(tile_h * overlap) + overlap_y
overlap_w = int(tile_w * overlap) + overlap_x
# max overlap is half of the tile size
overlap_h = min(tile_h // 2, overlap_h)
overlap_w = min(tile_w // 2, overlap_w)
if rows == 1:
overlap_h = 0
if cols == 1:
overlap_w = 0
tiles = []
for i in range(rows):
for j in range(cols):
y1 = i * tile_h
x1 = j * tile_w
if i > 0:
y1 -= overlap_h
if j > 0:
x1 -= overlap_w
y2 = y1 + tile_h + overlap_h
x2 = x1 + tile_w + overlap_w
if y2 > h:
y2 = h
y1 = y2 - tile_h - overlap_h
if x2 > w:
x2 = w
x1 = x2 - tile_w - overlap_w
tiles.append(image[:, y1:y2, x1:x2, :])
tiles = torch.cat(tiles, dim=0)
return(tiles, tile_w+overlap_w, tile_h+overlap_h, overlap_w, overlap_h,)
class ImageUntile:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"tiles": ("IMAGE",),
"overlap_x": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
"overlap_y": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
"rows": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
"cols": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, tiles, overlap_x, overlap_y, rows, cols):
tile_h, tile_w = tiles.shape[1:3]
tile_h -= overlap_y
tile_w -= overlap_x
out_w = cols * tile_w
out_h = rows * tile_h
out = torch.zeros((1, out_h, out_w, tiles.shape[3]), device=tiles.device, dtype=tiles.dtype)
for i in range(rows):
for j in range(cols):
y1 = i * tile_h
x1 = j * tile_w
if i > 0:
y1 -= overlap_y
if j > 0:
x1 -= overlap_x
y2 = y1 + tile_h + overlap_y
x2 = x1 + tile_w + overlap_x
if y2 > out_h:
y2 = out_h
y1 = y2 - tile_h - overlap_y
if x2 > out_w:
x2 = out_w
x1 = x2 - tile_w - overlap_x
mask = torch.ones((1, tile_h+overlap_y, tile_w+overlap_x), device=tiles.device, dtype=tiles.dtype)
# feather the overlap on top
if i > 0 and overlap_y > 0:
mask[:, :overlap_y, :] *= torch.linspace(0, 1, overlap_y, device=tiles.device, dtype=tiles.dtype).unsqueeze(1)
# feather the overlap on bottom
#if i < rows - 1:
# mask[:, -overlap_y:, :] *= torch.linspace(1, 0, overlap_y, device=tiles.device, dtype=tiles.dtype).unsqueeze(1)
# feather the overlap on left
if j > 0 and overlap_x > 0:
mask[:, :, :overlap_x] *= torch.linspace(0, 1, overlap_x, device=tiles.device, dtype=tiles.dtype).unsqueeze(0)
# feather the overlap on right
#if j < cols - 1:
# mask[:, :, -overlap_x:] *= torch.linspace(1, 0, overlap_x, device=tiles.device, dtype=tiles.dtype).unsqueeze(0)
mask = mask.unsqueeze(-1).repeat(1, 1, 1, tiles.shape[3])
tile = tiles[i * cols + j] * mask
out[:, y1:y2, x1:x2, :] = out[:, y1:y2, x1:x2, :] * (1 - mask) + tile
return(out, )
class ImageSeamCarving:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"width": ("INT", { "default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1, }),
"height": ("INT", { "default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1, }),
"energy": (["backward", "forward"],),
"order": (["width-first", "height-first"],),
},
"optional": {
"keep_mask": ("MASK",),
"drop_mask": ("MASK",),
}
}
RETURN_TYPES = ("IMAGE",)
CATEGORY = "essentials/image manipulation"
FUNCTION = "execute"
def execute(self, image, width, height, energy, order, keep_mask=None, drop_mask=None):
from .carve import seam_carving
img = image.permute([0, 3, 1, 2])
if keep_mask is not None:
#keep_mask = keep_mask.reshape((-1, 1, keep_mask.shape[-2], keep_mask.shape[-1])).movedim(1, -1)
keep_mask = keep_mask.unsqueeze(1)
if keep_mask.shape[2] != img.shape[2] or keep_mask.shape[3] != img.shape[3]:
keep_mask = F.interpolate(keep_mask, size=(img.shape[2], img.shape[3]), mode="bilinear")
if drop_mask is not None:
drop_mask = drop_mask.unsqueeze(1)
if drop_mask.shape[2] != img.shape[2] or drop_mask.shape[3] != img.shape[3]:
drop_mask = F.interpolate(drop_mask, size=(img.shape[2], img.shape[3]), mode="bilinear")
out = []
for i in range(img.shape[0]):
resized = seam_carving(
T.ToPILImage()(img[i]),
size=(width, height),
energy_mode=energy,
order=order,
keep_mask=T.ToPILImage()(keep_mask[i]) if keep_mask is not None else None,
drop_mask=T.ToPILImage()(drop_mask[i]) if drop_mask is not None else None,
)
out.append(T.ToTensor()(resized))
out = torch.stack(out).permute([0, 2, 3, 1])
return(out, )
class ImageRandomTransform:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"repeat": ("INT", { "default": 1, "min": 1, "max": 256, "step": 1, }),
"variation": ("FLOAT", { "default": 0.1, "min": 0.0, "max": 1.0, "step": 0.05, }),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, image, seed, repeat, variation):
h, w = image.shape[1:3]
image = image.repeat(repeat, 1, 1, 1).permute([0, 3, 1, 2])
distortion = 0.2 * variation
rotation = 5 * variation
brightness = 0.5 * variation
contrast = 0.5 * variation
saturation = 0.5 * variation
hue = 0.2 * variation
scale = 0.5 * variation
torch.manual_seed(seed)
out = []
for i in image:
tramsforms = T.Compose([
T.RandomPerspective(distortion_scale=distortion, p=0.5),
T.RandomRotation(degrees=rotation, interpolation=T.InterpolationMode.BILINEAR, expand=True),
T.ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation, hue=(-hue, hue)),
T.RandomHorizontalFlip(p=0.5),
T.RandomResizedCrop((h, w), scale=(1-scale, 1+scale), ratio=(w/h, w/h), interpolation=T.InterpolationMode.BICUBIC),
])
out.append(tramsforms(i.unsqueeze(0)))
out = torch.cat(out, dim=0).permute([0, 2, 3, 1]).clamp(0, 1)
return (out,)
class RemBGSession:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": (["u2net: general purpose", "u2netp: lightweight general purpose", "u2net_human_seg: human segmentation", "u2net_cloth_seg: cloths Parsing", "silueta: very small u2net", "isnet-general-use: general purpose", "isnet-anime: anime illustrations", "sam: general purpose"],),
"providers": (['CPU', 'CUDA', 'ROCM', 'DirectML', 'OpenVINO', 'CoreML', 'Tensorrt', 'Azure'],),
},
}
RETURN_TYPES = ("REMBG_SESSION",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, model, providers):
from rembg import new_session, remove
model = model.split(":")[0]
class Session:
def __init__(self, model, providers):
self.session = new_session(model, providers=[providers+"ExecutionProvider"])
def process(self, image):
return remove(image, session=self.session)
return (Session(model, providers),)
class TransparentBGSession:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"mode": (["base", "fast", "base-nightly"],),
"use_jit": ("BOOLEAN", { "default": True }),
},
}
RETURN_TYPES = ("REMBG_SESSION",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, mode, use_jit):
from transparent_background import Remover
class Session:
def __init__(self, mode, use_jit):
self.session = Remover(mode=mode, jit=use_jit)
def process(self, image):
return self.session.process(image)
return (Session(mode, use_jit),)
class ImageRemoveBackground:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"rembg_session": ("REMBG_SESSION",),
"image": ("IMAGE",),
},
}
RETURN_TYPES = ("IMAGE", "MASK",)
FUNCTION = "execute"
CATEGORY = "essentials/image manipulation"
def execute(self, rembg_session, image):
image = image.permute([0, 3, 1, 2])
output = []
for img in image:
img = T.ToPILImage()(img)
img = rembg_session.process(img)
output.append(T.ToTensor()(img))
output = torch.stack(output, dim=0)
output = output.permute([0, 2, 3, 1])
mask = output[:, :, :, 3] if output.shape[3] == 4 else torch.ones_like(output[:, :, :, 0])
# output = output[:, :, :, :3]
return(output, mask,)
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Image processing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
class ImageDesaturate:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"factor": ("FLOAT", { "default": 1.00, "min": 0.00, "max": 1.00, "step": 0.05, }),
"method": (["luminance (Rec.709)", "luminance (Rec.601)", "average", "lightness"],),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image processing"
def execute(self, image, factor, method):
if method == "luminance (Rec.709)":
grayscale = 0.2126 * image[..., 0] + 0.7152 * image[..., 1] + 0.0722 * image[..., 2]
elif method == "luminance (Rec.601)":
grayscale = 0.299 * image[..., 0] + 0.587 * image[..., 1] + 0.114 * image[..., 2]
elif method == "average":
grayscale = image.mean(dim=3)
elif method == "lightness":
grayscale = (torch.max(image, dim=3)[0] + torch.min(image, dim=3)[0]) / 2
grayscale = (1.0 - factor) * image + factor * grayscale.unsqueeze(-1).repeat(1, 1, 1, 3)
grayscale = torch.clamp(grayscale, 0, 1)
return(grayscale,)
class PixelOEPixelize:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"downscale_mode": (["contrast", "bicubic", "nearest", "center", "k-centroid"],),
"target_size": ("INT", { "default": 128, "min": 0, "max": MAX_RESOLUTION, "step": 8 }),
"patch_size": ("INT", { "default": 16, "min": 4, "max": 32, "step": 2 }),
"thickness": ("INT", { "default": 2, "min": 1, "max": 16, "step": 1 }),
"color_matching": ("BOOLEAN", { "default": True }),
"upscale": ("BOOLEAN", { "default": True }),
#"contrast": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
#"saturation": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image processing"
def execute(self, image, downscale_mode, target_size, patch_size, thickness, color_matching, upscale):
from pixeloe.pixelize import pixelize
image = image.clone().mul(255).clamp(0, 255).byte().cpu().numpy()
output = []
for img in image:
img = pixelize(img,
mode=downscale_mode,
target_size=target_size,
patch_size=patch_size,
thickness=thickness,
contrast=1.0,
saturation=1.0,
color_matching=color_matching,
no_upscale=not upscale)
output.append(T.ToTensor()(img))
output = torch.stack(output, dim=0).permute([0, 2, 3, 1])
return(output,)
class ImagePosterize:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"threshold": ("FLOAT", { "default": 0.50, "min": 0.00, "max": 1.00, "step": 0.05, }),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image processing"
def execute(self, image, threshold):
image = image.mean(dim=3, keepdim=True)
image = (image > threshold).float()
image = image.repeat(1, 1, 1, 3)
return(image,)
# From https://github.com/yoonsikp/pycubelut/blob/master/pycubelut.py (MIT license)
class ImageApplyLUT:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"lut_file": (folder_paths.get_filename_list("luts"),),
"gamma_correction": ("BOOLEAN", { "default": True }),
"clip_values": ("BOOLEAN", { "default": True }),
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.1 }),
}}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "essentials/image processing"
# TODO: check if we can do without numpy
def execute(self, image, lut_file, gamma_correction, clip_values, strength):
lut_file_path = folder_paths.get_full_path("luts", lut_file)
if not lut_file_path or not Path(lut_file_path).exists():
print(f"Could not find LUT file: {lut_file_path}")
return (image,)
from colour.io.luts.iridas_cube import read_LUT_IridasCube
device = image.device
lut = read_LUT_IridasCube(lut_file_path)
lut.name = lut_file
if clip_values:
if lut.domain[0].max() == lut.domain[0].min() and lut.domain[1].max() == lut.domain[1].min():
lut.table = np.clip(lut.table, lut.domain[0, 0], lut.domain[1, 0])
else:
if len(lut.table.shape) == 2: # 3x1D
for dim in range(3):
lut.table[:, dim] = np.clip(lut.table[:, dim], lut.domain[0, dim], lut.domain[1, dim])
else: # 3D
for dim in range(3):
lut.table[:, :, :, dim] = np.clip(lut.table[:, :, :, dim], lut.domain[0, dim], lut.domain[1, dim])
out = []
for img in image: # TODO: is this more resource efficient? should we use a batch instead?
lut_img = img.cpu().numpy().copy()
is_non_default_domain = not np.array_equal(lut.domain, np.array([[0., 0., 0.], [1., 1., 1.]]))
dom_scale = None
if is_non_default_domain:
dom_scale = lut.domain[1] - lut.domain[0]
lut_img = lut_img * dom_scale + lut.domain[0]
if gamma_correction:
lut_img = lut_img ** (1/2.2)
lut_img = lut.apply(lut_img)