-
Notifications
You must be signed in to change notification settings - Fork 352
Expand file tree
/
Copy pathcore.py
More file actions
2136 lines (1594 loc) · 83.2 KB
/
core.py
File metadata and controls
2136 lines (1594 loc) · 83.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import os
import warnings
import numpy
import torch
from segment_anything import SamPredictor
from comfy_extras.nodes_custom_sampler import Noise_RandomNoise
from impact.utils import *
from collections import namedtuple
import numpy as np
from skimage.measure import label
import nodes
import comfy_extras.nodes_upscale_model as model_upscale
from server import PromptServer
import comfy
import impact.wildcards as wildcards
import math
import cv2
import time
from comfy import model_management
from impact import utils
from impact import impact_sampling
from concurrent.futures import ThreadPoolExecutor
try:
from comfy_extras import nodes_differential_diffusion
except Exception:
print(f"\n#############################################\n[Impact Pack] ComfyUI is an outdated version.\n#############################################\n")
raise Exception("[Impact Pack] ComfyUI is an outdated version.")
SEG = namedtuple("SEG",
['cropped_image', 'cropped_mask', 'confidence', 'crop_region', 'bbox', 'label', 'control_net_wrapper'],
defaults=[None])
pb_id_cnt = time.time()
preview_bridge_image_id_map = {}
preview_bridge_image_name_map = {}
preview_bridge_cache = {}
SCHEDULERS = comfy.samplers.KSampler.SCHEDULERS + ['AYS SDXL', 'AYS SD1', 'AYS SVD']
def set_previewbridge_image(node_id, file, item):
global pb_id_cnt
if file in preview_bridge_image_name_map:
pb_id = preview_bridge_image_name_map[node_id, file]
if pb_id.startswith(f"${node_id}"):
return pb_id
pb_id = f"${node_id}-{pb_id_cnt}"
preview_bridge_image_id_map[pb_id] = (file, item)
preview_bridge_image_name_map[node_id, file] = (pb_id, item)
pb_id_cnt += 1
return pb_id
def erosion_mask(mask, grow_mask_by):
mask = make_2d_mask(mask)
w = mask.shape[1]
h = mask.shape[0]
device = comfy.model_management.get_torch_device()
mask = mask.clone().to(device)
mask2 = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(w, h), mode="bilinear").to(device)
if grow_mask_by == 0:
mask_erosion = mask2
else:
kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by)).to(device)
padding = math.ceil((grow_mask_by - 1) / 2)
mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask2.round(), kernel_tensor, padding=padding), 0, 1)
return mask_erosion[:, :, :w, :h].round().cpu()
# CREDIT: https://github.com/BlenderNeko/ComfyUI_Noise/blob/afb14757216257b12268c91845eac248727a55e2/nodes.py#L68
# https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
def slerp(val, low, high):
dims = low.shape
low = low.reshape(dims[0], -1)
high = high.reshape(dims[0], -1)
low_norm = low/torch.norm(low, dim=1, keepdim=True)
high_norm = high/torch.norm(high, dim=1, keepdim=True)
low_norm[low_norm != low_norm] = 0.0
high_norm[high_norm != high_norm] = 0.0
omega = torch.acos((low_norm*high_norm).sum(1))
so = torch.sin(omega)
res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
return res.reshape(dims)
def mix_noise(from_noise, to_noise, strength, variation_method):
if variation_method == 'slerp':
mixed_noise = slerp(strength, from_noise, to_noise)
else:
# linear
mixed_noise = (1 - strength) * from_noise + strength * to_noise
# NOTE: Since the variance of the Gaussian noise in mixed_noise has changed, it must be corrected through scaling.
scale_factor = math.sqrt((1 - strength) ** 2 + strength ** 2)
mixed_noise /= scale_factor
return mixed_noise
class REGIONAL_PROMPT:
def __init__(self, mask, sampler, variation_seed=0, variation_strength=0.0, variation_method='linear'):
mask = make_2d_mask(mask)
self.mask = mask
self.sampler = sampler
self.mask_erosion = None
self.erosion_factor = None
self.variation_seed = variation_seed
self.variation_strength = variation_strength
self.variation_method = variation_method
def clone_with_sampler(self, sampler):
rp = REGIONAL_PROMPT(self.mask, sampler)
rp.mask_erosion = self.mask_erosion
rp.erosion_factor = self.erosion_factor
rp.variation_seed = self.variation_seed
rp.variation_strength = self.variation_strength
rp.variation_method = self.variation_method
return rp
def get_mask_erosion(self, factor):
if self.mask_erosion is None or self.erosion_factor != factor:
self.mask_erosion = erosion_mask(self.mask, factor)
self.erosion_factor = factor
return self.mask_erosion
def touch_noise(self, noise):
if self.variation_strength > 0.0:
mask = utils.make_3d_mask(self.mask)
mask = utils.resize_mask(mask, (noise.shape[2], noise.shape[3])).unsqueeze(0)
regional_noise = Noise_RandomNoise(self.variation_seed).generate_noise({'samples': noise})
mixed_noise = mix_noise(noise, regional_noise, self.variation_strength, variation_method=self.variation_method)
return (mask == 1).float() * mixed_noise + (mask == 0).float() * noise
return noise
class NO_BBOX_DETECTOR:
pass
class NO_SEGM_DETECTOR:
pass
def create_segmasks(results):
bboxs = results[1]
segms = results[2]
confidence = results[3]
results = []
for i in range(len(segms)):
item = (bboxs[i], segms[i].astype(np.float32), confidence[i])
results.append(item)
return results
def gen_detection_hints_from_mask_area(x, y, mask, threshold, use_negative):
mask = make_2d_mask(mask)
points = []
plabs = []
# minimum sampling step >= 3
y_step = max(3, int(mask.shape[0] / 20))
x_step = max(3, int(mask.shape[1] / 20))
for i in range(0, len(mask), y_step):
for j in range(0, len(mask[i]), x_step):
if mask[i][j] > threshold:
points.append((x + j, y + i))
plabs.append(1)
elif use_negative and mask[i][j] == 0:
points.append((x + j, y + i))
plabs.append(0)
return points, plabs
def gen_negative_hints(w, h, x1, y1, x2, y2):
npoints = []
nplabs = []
# minimum sampling step >= 3
y_step = max(3, int(w / 20))
x_step = max(3, int(h / 20))
for i in range(10, h - 10, y_step):
for j in range(10, w - 10, x_step):
if not (x1 - 10 <= j and j <= x2 + 10 and y1 - 10 <= i and i <= y2 + 10):
npoints.append((j, i))
nplabs.append(0)
return npoints, nplabs
def enhance_detail(image, model, clip, vae, guide_size, guide_size_for_bbox, max_size, bbox, seed, steps, cfg,
sampler_name,
scheduler, positive, negative, denoise, noise_mask, force_inpaint,
wildcard_opt=None, wildcard_opt_concat_mode=None,
detailer_hook=None,
refiner_ratio=None, refiner_model=None, refiner_clip=None, refiner_positive=None,
refiner_negative=None, control_net_wrapper=None, cycle=1,
inpaint_model=False, noise_mask_feather=0):
if noise_mask is not None:
noise_mask = utils.tensor_gaussian_blur_mask(noise_mask, noise_mask_feather)
noise_mask = noise_mask.squeeze(3)
if noise_mask_feather > 0:
model = nodes_differential_diffusion.DifferentialDiffusion().execute(model)[0]
if wildcard_opt is not None and wildcard_opt != "":
model, _, wildcard_positive = wildcards.process_with_loras(wildcard_opt, model, clip)
if wildcard_opt_concat_mode == "concat":
positive = nodes.ConditioningConcat().concat(positive, wildcard_positive)[0]
else:
positive = wildcard_positive
h = image.shape[1]
w = image.shape[2]
bbox_h = bbox[3] - bbox[1]
bbox_w = bbox[2] - bbox[0]
# Skip processing if the detected bbox is already larger than the guide_size
if not force_inpaint and bbox_h >= guide_size and bbox_w >= guide_size:
print(f"Detailer: segment skip (enough big)")
return None, None
if guide_size_for_bbox: # == "bbox"
# Scale up based on the smaller dimension between width and height.
upscale = guide_size / min(bbox_w, bbox_h)
else:
# for cropped_size
upscale = guide_size / min(w, h)
new_w = int(w * upscale)
new_h = int(h * upscale)
# safeguard
if 'aitemplate_keep_loaded' in model.model_options:
max_size = min(4096, max_size)
if new_w > max_size or new_h > max_size:
upscale *= max_size / max(new_w, new_h)
new_w = int(w * upscale)
new_h = int(h * upscale)
if not force_inpaint:
if upscale <= 1.0:
print(f"Detailer: segment skip [determined upscale factor={upscale}]")
return None, None
if new_w == 0 or new_h == 0:
print(f"Detailer: segment skip [zero size={new_w, new_h}]")
return None, None
else:
if upscale <= 1.0 or new_w == 0 or new_h == 0:
print(f"Detailer: force inpaint")
upscale = 1.0
new_w = w
new_h = h
if detailer_hook is not None:
new_w, new_h = detailer_hook.touch_scaled_size(new_w, new_h)
print(f"Detailer: segment upscale for ({bbox_w, bbox_h}) | crop region {w, h} x {upscale} -> {new_w, new_h}")
# upscale
upscaled_image = tensor_resize(image, new_w, new_h)
cnet_pils = None
if control_net_wrapper is not None:
positive, negative, cnet_pils = control_net_wrapper.apply(positive, negative, upscaled_image, noise_mask)
model, cnet_pils2 = control_net_wrapper.doit_ipadapter(model)
cnet_pils.extend(cnet_pils2)
# prepare mask
if noise_mask is not None and inpaint_model:
positive, negative, latent_image = nodes.InpaintModelConditioning().encode(positive, negative, upscaled_image, vae, noise_mask)
else:
latent_image = to_latent_image(upscaled_image, vae)
if noise_mask is not None:
latent_image['noise_mask'] = noise_mask
if detailer_hook is not None:
latent_image = detailer_hook.post_encode(latent_image)
refined_latent = latent_image
# ksampler
for i in range(0, cycle):
if detailer_hook is not None:
if detailer_hook is not None:
detailer_hook.set_steps((i, cycle))
refined_latent = detailer_hook.cycle_latent(refined_latent)
model2, seed2, steps2, cfg2, sampler_name2, scheduler2, positive2, negative2, upscaled_latent2, denoise2 = \
detailer_hook.pre_ksample(model, seed+i, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise)
noise, is_touched = detailer_hook.get_custom_noise(seed+i, torch.zeros(latent_image['samples'].size()), is_touched=False)
if not is_touched:
noise = None
else:
model2, seed2, steps2, cfg2, sampler_name2, scheduler2, positive2, negative2, upscaled_latent2, denoise2 = \
model, seed + i, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise
noise = None
refined_latent = impact_sampling.ksampler_wrapper(model2, seed2, steps2, cfg2, sampler_name2, scheduler2, positive2, negative2,
refined_latent, denoise2, refiner_ratio, refiner_model, refiner_clip, refiner_positive, refiner_negative, noise=noise)
if detailer_hook is not None:
refined_latent = detailer_hook.pre_decode(refined_latent)
# non-latent downscale - latent downscale cause bad quality
try:
# try to decode image normally
refined_image = vae.decode(refined_latent['samples'])
except Exception as e:
#usually an out-of-memory exception from the decode, so try a tiled approach
refined_image = vae.decode_tiled(refined_latent["samples"], tile_x=64, tile_y=64, )
if detailer_hook is not None:
refined_image = detailer_hook.post_decode(refined_image)
# downscale
refined_image = tensor_resize(refined_image, w, h)
# prevent mixing of device
refined_image = refined_image.cpu()
# don't convert to latent - latent break image
# preserving pil is much better
return refined_image, cnet_pils
def enhance_detail_for_animatediff(image_frames, model, clip, vae, guide_size, guide_size_for_bbox, max_size, bbox, seed, steps, cfg,
sampler_name,
scheduler, positive, negative, denoise, noise_mask,
wildcard_opt=None, wildcard_opt_concat_mode=None,
detailer_hook=None,
refiner_ratio=None, refiner_model=None, refiner_clip=None, refiner_positive=None,
refiner_negative=None, control_net_wrapper=None, noise_mask_feather=0):
if noise_mask is not None:
noise_mask = utils.tensor_gaussian_blur_mask(noise_mask, noise_mask_feather)
noise_mask = noise_mask.squeeze(3)
if noise_mask_feather > 0:
model = nodes_differential_diffusion.DifferentialDiffusion().execute(model)[0]
if wildcard_opt is not None and wildcard_opt != "":
model, _, wildcard_positive = wildcards.process_with_loras(wildcard_opt, model, clip)
if wildcard_opt_concat_mode == "concat":
positive = nodes.ConditioningConcat().concat(positive, wildcard_positive)[0]
else:
positive = wildcard_positive
h = image_frames.shape[1]
w = image_frames.shape[2]
bbox_h = bbox[3] - bbox[1]
bbox_w = bbox[2] - bbox[0]
# Skip processing if the detected bbox is already larger than the guide_size
if guide_size_for_bbox: # == "bbox"
# Scale up based on the smaller dimension between width and height.
upscale = guide_size / min(bbox_w, bbox_h)
else:
# for cropped_size
upscale = guide_size / min(w, h)
new_w = int(w * upscale)
new_h = int(h * upscale)
# safeguard
if 'aitemplate_keep_loaded' in model.model_options:
max_size = min(4096, max_size)
if new_w > max_size or new_h > max_size:
upscale *= max_size / max(new_w, new_h)
new_w = int(w * upscale)
new_h = int(h * upscale)
if upscale <= 1.0 or new_w == 0 or new_h == 0:
print(f"Detailer: force inpaint")
upscale = 1.0
new_w = w
new_h = h
if detailer_hook is not None:
new_w, new_h = detailer_hook.touch_scaled_size(new_w, new_h)
print(f"Detailer: segment upscale for ({bbox_w, bbox_h}) | crop region {w, h} x {upscale} -> {new_w, new_h}")
# upscale the mask tensor by a factor of 2 using bilinear interpolation
if isinstance(noise_mask, np.ndarray):
noise_mask = torch.from_numpy(noise_mask)
if len(noise_mask.shape) == 2:
noise_mask = noise_mask.unsqueeze(0)
else: # == 3
noise_mask = noise_mask
upscaled_mask = None
for single_mask in noise_mask:
single_mask = single_mask.unsqueeze(0).unsqueeze(0)
upscaled_single_mask = torch.nn.functional.interpolate(single_mask, size=(new_h, new_w), mode='bilinear', align_corners=False)
upscaled_single_mask = upscaled_single_mask.squeeze(0)
if upscaled_mask is None:
upscaled_mask = upscaled_single_mask
else:
upscaled_mask = torch.cat((upscaled_mask, upscaled_single_mask), dim=0)
latent_frames = None
for image in image_frames:
image = torch.from_numpy(image).unsqueeze(0)
# upscale
upscaled_image = tensor_resize(image, new_w, new_h)
# ksampler
samples = to_latent_image(upscaled_image, vae)['samples']
if latent_frames is None:
latent_frames = samples
else:
latent_frames = torch.concat((latent_frames, samples), dim=0)
cnet_images = None
if control_net_wrapper is not None:
positive, negative, cnet_images = control_net_wrapper.apply(positive, negative, torch.from_numpy(image_frames), noise_mask, use_acn=True)
if len(upscaled_mask) != len(image_frames) and len(upscaled_mask) > 1:
print(f"[Impact Pack] WARN: DetailerForAnimateDiff - The number of the mask frames({len(upscaled_mask)}) and the image frames({len(image_frames)}) are different. Combine the mask frames and apply.")
combined_mask = upscaled_mask[0].to(torch.uint8)
for frame_mask in upscaled_mask[1:]:
combined_mask |= (frame_mask * 255).to(torch.uint8)
combined_mask = (combined_mask/255.0).to(torch.float32)
upscaled_mask = combined_mask.expand(len(image_frames), -1, -1)
upscaled_mask = utils.to_binary_mask(upscaled_mask, 0.1)
latent = {
'noise_mask': upscaled_mask,
'samples': latent_frames
}
if detailer_hook is not None:
latent = detailer_hook.post_encode(latent)
refined_latent = impact_sampling.ksampler_wrapper(model, seed, steps, cfg, sampler_name, scheduler, positive, negative,
latent, denoise, refiner_ratio, refiner_model, refiner_clip, refiner_positive, refiner_negative)
if detailer_hook is not None:
refined_latent = detailer_hook.pre_decode(refined_latent)
refined_image_frames = None
for refined_sample in refined_latent['samples']:
refined_sample = refined_sample.unsqueeze(0)
# non-latent downscale - latent downscale cause bad quality
refined_image = vae.decode(refined_sample)
if refined_image_frames is None:
refined_image_frames = refined_image
else:
refined_image_frames = torch.concat((refined_image_frames, refined_image), dim=0)
if detailer_hook is not None:
refined_image_frames = detailer_hook.post_decode(refined_image_frames)
refined_image_frames = nodes.ImageScale().upscale(image=refined_image_frames, upscale_method='lanczos', width=w, height=h, crop='disabled')[0]
return refined_image_frames, cnet_images
def composite_to(dest_latent, crop_region, src_latent):
x1 = crop_region[0]
y1 = crop_region[1]
# composite to original latent
lc = nodes.LatentComposite()
orig_image = lc.composite(dest_latent, src_latent, x1, y1)
return orig_image[0]
def sam_predict(predictor, points, plabs, bbox, threshold):
point_coords = None if not points else np.array(points)
point_labels = None if not plabs else np.array(plabs)
box = np.array([bbox]) if bbox is not None else None
cur_masks, scores, _ = predictor.predict(point_coords=point_coords, point_labels=point_labels, box=box)
total_masks = []
selected = False
max_score = 0
max_mask = None
for idx in range(len(scores)):
if scores[idx] > max_score:
max_score = scores[idx]
max_mask = cur_masks[idx]
if scores[idx] >= threshold:
selected = True
total_masks.append(cur_masks[idx])
else:
pass
if not selected and max_mask is not None:
total_masks.append(max_mask)
return total_masks
class SAMWrapper:
def __init__(self, model, is_auto_mode, safe_to_gpu=None):
self.model = model
self.safe_to_gpu = safe_to_gpu if safe_to_gpu is not None else SafeToGPU_stub()
self.is_auto_mode = is_auto_mode
def prepare_device(self):
if self.is_auto_mode:
device = comfy.model_management.get_torch_device()
self.safe_to_gpu.to_device(self.model, device=device)
def release_device(self):
if self.is_auto_mode:
self.model.to(device="cpu")
def predict(self, image, points, plabs, bbox, threshold):
predictor = SamPredictor(self.model)
predictor.set_image(image, "RGB")
return sam_predict(predictor, points, plabs, bbox, threshold)
class ESAMWrapper:
def __init__(self, model, device):
self.model = model
self.func_inference = nodes.NODE_CLASS_MAPPINGS['Yoloworld_ESAM_Zho']
self.device = device
def prepare_device(self):
pass
def release_device(self):
pass
def predict(self, image, points, plabs, bbox, threshold):
if self.device == 'CPU':
self.device = 'cpu'
else:
self.device = 'cuda'
detected_masks = self.func_inference.inference_sam_with_boxes(image=image, xyxy=[bbox], model=self.model, device=self.device)
return [detected_masks.squeeze(0)]
def make_sam_mask(sam, segs, image, detection_hint, dilation,
threshold, bbox_expansion, mask_hint_threshold, mask_hint_use_negative):
sam_obj = sam.sam_wrapper
sam_obj.prepare_device()
try:
image = np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
total_masks = []
use_small_negative = mask_hint_use_negative == "Small"
# seg_shape = segs[0]
segs = segs[1]
if detection_hint == "mask-points":
points = []
plabs = []
for i in range(len(segs)):
bbox = segs[i].bbox
center = center_of_bbox(segs[i].bbox)
points.append(center)
# small point is background, big point is foreground
if use_small_negative and bbox[2] - bbox[0] < 10:
plabs.append(0)
else:
plabs.append(1)
detected_masks = sam_obj.predict(image, points, plabs, None, threshold)
total_masks += detected_masks
else:
for i in range(len(segs)):
bbox = segs[i].bbox
center = center_of_bbox(bbox)
x1 = max(bbox[0] - bbox_expansion, 0)
y1 = max(bbox[1] - bbox_expansion, 0)
x2 = min(bbox[2] + bbox_expansion, image.shape[1])
y2 = min(bbox[3] + bbox_expansion, image.shape[0])
dilated_bbox = [x1, y1, x2, y2]
points = []
plabs = []
if detection_hint == "center-1":
points.append(center)
plabs = [1] # 1 = foreground point, 0 = background point
elif detection_hint == "horizontal-2":
gap = (x2 - x1) / 3
points.append((x1 + gap, center[1]))
points.append((x1 + gap * 2, center[1]))
plabs = [1, 1]
elif detection_hint == "vertical-2":
gap = (y2 - y1) / 3
points.append((center[0], y1 + gap))
points.append((center[0], y1 + gap * 2))
plabs = [1, 1]
elif detection_hint == "rect-4":
x_gap = (x2 - x1) / 3
y_gap = (y2 - y1) / 3
points.append((x1 + x_gap, center[1]))
points.append((x1 + x_gap * 2, center[1]))
points.append((center[0], y1 + y_gap))
points.append((center[0], y1 + y_gap * 2))
plabs = [1, 1, 1, 1]
elif detection_hint == "diamond-4":
x_gap = (x2 - x1) / 3
y_gap = (y2 - y1) / 3
points.append((x1 + x_gap, y1 + y_gap))
points.append((x1 + x_gap * 2, y1 + y_gap))
points.append((x1 + x_gap, y1 + y_gap * 2))
points.append((x1 + x_gap * 2, y1 + y_gap * 2))
plabs = [1, 1, 1, 1]
elif detection_hint == "mask-point-bbox":
center = center_of_bbox(segs[i].bbox)
points.append(center)
plabs = [1]
elif detection_hint == "mask-area":
points, plabs = gen_detection_hints_from_mask_area(segs[i].crop_region[0], segs[i].crop_region[1],
segs[i].cropped_mask,
mask_hint_threshold, use_small_negative)
if mask_hint_use_negative == "Outter":
npoints, nplabs = gen_negative_hints(image.shape[0], image.shape[1],
segs[i].crop_region[0], segs[i].crop_region[1],
segs[i].crop_region[2], segs[i].crop_region[3])
points += npoints
plabs += nplabs
detected_masks = sam_obj.predict(image, points, plabs, dilated_bbox, threshold)
total_masks += detected_masks
# merge every collected masks
mask = combine_masks2(total_masks)
finally:
sam_obj.release_device()
if mask is not None:
mask = mask.float()
mask = dilate_mask(mask.cpu().numpy(), dilation)
mask = torch.from_numpy(mask)
else:
size = image.shape[0], image.shape[1]
mask = torch.zeros(size, dtype=torch.float32, device="cpu") # empty mask
mask = utils.make_3d_mask(mask)
return mask
def generate_detection_hints(image, seg, center, detection_hint, dilated_bbox, mask_hint_threshold, use_small_negative,
mask_hint_use_negative):
[x1, y1, x2, y2] = dilated_bbox
points = []
plabs = []
if detection_hint == "center-1":
points.append(center)
plabs = [1] # 1 = foreground point, 0 = background point
elif detection_hint == "horizontal-2":
gap = (x2 - x1) / 3
points.append((x1 + gap, center[1]))
points.append((x1 + gap * 2, center[1]))
plabs = [1, 1]
elif detection_hint == "vertical-2":
gap = (y2 - y1) / 3
points.append((center[0], y1 + gap))
points.append((center[0], y1 + gap * 2))
plabs = [1, 1]
elif detection_hint == "rect-4":
x_gap = (x2 - x1) / 3
y_gap = (y2 - y1) / 3
points.append((x1 + x_gap, center[1]))
points.append((x1 + x_gap * 2, center[1]))
points.append((center[0], y1 + y_gap))
points.append((center[0], y1 + y_gap * 2))
plabs = [1, 1, 1, 1]
elif detection_hint == "diamond-4":
x_gap = (x2 - x1) / 3
y_gap = (y2 - y1) / 3
points.append((x1 + x_gap, y1 + y_gap))
points.append((x1 + x_gap * 2, y1 + y_gap))
points.append((x1 + x_gap, y1 + y_gap * 2))
points.append((x1 + x_gap * 2, y1 + y_gap * 2))
plabs = [1, 1, 1, 1]
elif detection_hint == "mask-point-bbox":
center = center_of_bbox(seg.bbox)
points.append(center)
plabs = [1]
elif detection_hint == "mask-area":
points, plabs = gen_detection_hints_from_mask_area(seg.crop_region[0], seg.crop_region[1],
seg.cropped_mask,
mask_hint_threshold, use_small_negative)
if mask_hint_use_negative == "Outter":
npoints, nplabs = gen_negative_hints(image.shape[0], image.shape[1],
seg.crop_region[0], seg.crop_region[1],
seg.crop_region[2], seg.crop_region[3])
points += npoints
plabs += nplabs
return points, plabs
def convert_and_stack_masks(masks):
if len(masks) == 0:
return None
mask_tensors = []
for mask in masks:
mask_array = np.array(mask, dtype=np.uint8)
mask_tensor = torch.from_numpy(mask_array)
mask_tensors.append(mask_tensor)
stacked_masks = torch.stack(mask_tensors, dim=0)
stacked_masks = stacked_masks.unsqueeze(1)
return stacked_masks
def merge_and_stack_masks(stacked_masks, group_size):
if stacked_masks is None:
return None
num_masks = stacked_masks.size(0)
merged_masks = []
for i in range(0, num_masks, group_size):
subset_masks = stacked_masks[i:i + group_size]
merged_mask = torch.any(subset_masks, dim=0)
merged_masks.append(merged_mask)
if len(merged_masks) > 0:
merged_masks = torch.stack(merged_masks, dim=0)
return merged_masks
def segs_scale_match(segs, target_shape):
h = segs[0][0]
w = segs[0][1]
th = target_shape[1]
tw = target_shape[2]
if (h == th and w == tw) or h == 0 or w == 0:
return segs
rh = th / h
rw = tw / w
new_segs = []
for seg in segs[1]:
cropped_image = seg.cropped_image
cropped_mask = seg.cropped_mask
x1, y1, x2, y2 = seg.crop_region
bx1, by1, bx2, by2 = seg.bbox
crop_region = int(x1*rw), int(y1*rw), int(x2*rh), int(y2*rh)
bbox = int(bx1*rw), int(by1*rw), int(bx2*rh), int(by2*rh)
new_w = crop_region[2] - crop_region[0]
new_h = crop_region[3] - crop_region[1]
if isinstance(cropped_mask, np.ndarray):
cropped_mask = torch.from_numpy(cropped_mask)
if isinstance(cropped_mask, torch.Tensor) and len(cropped_mask.shape) == 3:
cropped_mask = torch.nn.functional.interpolate(cropped_mask.unsqueeze(0), size=(new_h, new_w), mode='bilinear', align_corners=False)
cropped_mask = cropped_mask.squeeze(0)
else:
cropped_mask = torch.nn.functional.interpolate(cropped_mask.unsqueeze(0).unsqueeze(0), size=(new_h, new_w), mode='bilinear', align_corners=False)
cropped_mask = cropped_mask.squeeze(0).squeeze(0).numpy()
if cropped_image is not None:
cropped_image = tensor_resize(cropped_image if isinstance(cropped_image, torch.Tensor) else torch.from_numpy(cropped_image), new_w, new_h)
cropped_image = cropped_image.numpy()
new_seg = SEG(cropped_image, cropped_mask, seg.confidence, crop_region, bbox, seg.label, seg.control_net_wrapper)
new_segs.append(new_seg)
return (th, tw), new_segs
# Used Python's slicing feature. stacked_masks[2::3] means starting from index 2, selecting every third tensor with a step size of 3.
# This allows for quickly obtaining the last tensor of every three tensors in stacked_masks.
def every_three_pick_last(stacked_masks):
selected_masks = stacked_masks[2::3]
return selected_masks
def make_sam_mask_segmented(sam, segs, image, detection_hint, dilation,
threshold, bbox_expansion, mask_hint_threshold, mask_hint_use_negative):
sam_obj = sam.sam_wrapper
sam_obj.prepare_device()
try:
image = np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
total_masks = []
use_small_negative = mask_hint_use_negative == "Small"
# seg_shape = segs[0]
segs = segs[1]
if detection_hint == "mask-points":
points = []
plabs = []
for i in range(len(segs)):
bbox = segs[i].bbox
center = center_of_bbox(bbox)
points.append(center)
# small point is background, big point is foreground
if use_small_negative and bbox[2] - bbox[0] < 10:
plabs.append(0)
else:
plabs.append(1)
detected_masks = sam_obj.predict(image, points, plabs, None, threshold)
total_masks += detected_masks
else:
for i in range(len(segs)):
bbox = segs[i].bbox
center = center_of_bbox(bbox)
x1 = max(bbox[0] - bbox_expansion, 0)
y1 = max(bbox[1] - bbox_expansion, 0)
x2 = min(bbox[2] + bbox_expansion, image.shape[1])
y2 = min(bbox[3] + bbox_expansion, image.shape[0])
dilated_bbox = [x1, y1, x2, y2]
points, plabs = generate_detection_hints(image, segs[i], center, detection_hint, dilated_bbox,
mask_hint_threshold, use_small_negative,
mask_hint_use_negative)
detected_masks = sam_obj.predict(image, points, plabs, dilated_bbox, threshold)
total_masks += detected_masks
# merge every collected masks
mask = combine_masks2(total_masks)
finally:
sam_obj.release_device()
mask_working_device = torch.device("cpu")
if mask is not None:
mask = mask.float()
mask = dilate_mask(mask.cpu().numpy(), dilation)
mask = torch.from_numpy(mask)
mask = mask.to(device=mask_working_device)
else:
# Extracting batch, height and width
height, width, _ = image.shape
mask = torch.zeros(
(height, width), dtype=torch.float32, device=mask_working_device
) # empty mask
stacked_masks = convert_and_stack_masks(total_masks)
return (mask, merge_and_stack_masks(stacked_masks, group_size=3))
# return every_three_pick_last(stacked_masks)
def segs_bitwise_and_mask(segs, mask):
mask = make_2d_mask(mask)
if mask is None:
print("[SegsBitwiseAndMask] Cannot operate: MASK is empty.")
return ([],)
items = []
mask = (mask.cpu().numpy() * 255).astype(np.uint8)
for seg in segs[1]:
cropped_mask = (seg.cropped_mask * 255).astype(np.uint8)
crop_region = seg.crop_region
cropped_mask2 = mask[crop_region[1]:crop_region[3], crop_region[0]:crop_region[2]]
new_mask = np.bitwise_and(cropped_mask.astype(np.uint8), cropped_mask2)
new_mask = new_mask.astype(np.float32) / 255.0
item = SEG(seg.cropped_image, new_mask, seg.confidence, seg.crop_region, seg.bbox, seg.label, None)
items.append(item)
return segs[0], items
def segs_bitwise_subtract_mask(segs, mask):
mask = make_2d_mask(mask)
if mask is None:
print("[SegsBitwiseSubtractMask] Cannot operate: MASK is empty.")
return ([],)
items = []
mask = (mask.cpu().numpy() * 255).astype(np.uint8)
for seg in segs[1]:
cropped_mask = (seg.cropped_mask * 255).astype(np.uint8)
crop_region = seg.crop_region
cropped_mask2 = mask[crop_region[1]:crop_region[3], crop_region[0]:crop_region[2]]
new_mask = cv2.subtract(cropped_mask.astype(np.uint8), cropped_mask2)
new_mask = new_mask.astype(np.float32) / 255.0
item = SEG(seg.cropped_image, new_mask, seg.confidence, seg.crop_region, seg.bbox, seg.label, None)
items.append(item)
return segs[0], items
def apply_mask_to_each_seg(segs, masks):
if masks is None:
print("[SegsBitwiseAndMask] Cannot operate: MASK is empty.")
return (segs[0], [],)
items = []
masks = masks.squeeze(1)
for seg, mask in zip(segs[1], masks):
cropped_mask = (seg.cropped_mask * 255).astype(np.uint8)
crop_region = seg.crop_region
cropped_mask2 = (mask.cpu().numpy() * 255).astype(np.uint8)