-
Notifications
You must be signed in to change notification settings - Fork 11
/
cv_nodes.py
2341 lines (1922 loc) · 83.4 KB
/
cv_nodes.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 abc import ABC
import numpy as np
import cv2 as cv
import math
from .utils.dry import (tensor2opencv, opencv2tensor, image_output_formats_options, rect_modes, rect_modes_map,
maybe_convert_img, image_output_formats_options_map, prepare_text_for_eval, cache_with_ids,
filter_expression_names, base_category_path, images_category_path, print_yellow)
from .utils.color import (ImageColor, setup_color_to_correct_type, find_complementary_color, HSV_Samples, Interval)
from .utils.templates import ComboWrapperNode
# TODO these nodes return the mask, not the image with the background removed!
# this is somewhat misleading. Consider changing the methods names.
# ( but to what? GrabCutMask? FramedMaskGrabCutMask? ...)
# region types and constants
thresh_types_map = {
'BINARY': cv.THRESH_BINARY,
'BINARY_INV': cv.THRESH_BINARY_INV,
'TRUNC': cv.THRESH_TRUNC,
'TOZERO': cv.THRESH_TOZERO,
'TOZERO_INV': cv.THRESH_TOZERO_INV,
}
thresh_types = list(thresh_types_map.keys())
border_types_map = {
'BORDER_CONSTANT': cv.BORDER_CONSTANT,
'BORDER_REPLICATE': cv.BORDER_REPLICATE,
'BORDER_REFLECT': cv.BORDER_REFLECT,
'BORDER_REFLECT101': cv.BORDER_REFLECT101,
'BORDER_WRAP': cv.BORDER_WRAP,
'BORDER_TRANSPARENT': cv.BORDER_TRANSPARENT,
'BORDER_DEFAULT': cv.BORDER_DEFAULT,
'BORDER_ISOLATED': cv.BORDER_ISOLATED
}
border_types = list(border_types_map.keys())
border_types_excluding_transparent = border_types_map.copy()
border_types_excluding_transparent.pop("BORDER_TRANSPARENT")
border_types_excluding_transparent = list(border_types_excluding_transparent.keys())
interpolation_types_map = {
"INTER_NEAREST": cv.INTER_NEAREST,
"INTER_LINEAR": cv.INTER_LINEAR,
"INTER_AREA": cv.INTER_AREA,
"INTER_LANCZOS4": cv.INTER_LANCZOS4,
"INTER_CUBIC": cv.INTER_CUBIC,
# "INTER_LINEAR_EXACT": cv.INTER_LINEAR_EXACT,
# "INTER_NEAREST_EXACT": cv.INTER_NEAREST_EXACT,
}
interpolation_types = list(interpolation_types_map.keys())
cv_category_path = f"{base_category_path}/CV"
# endregion
# region misc
class CopyMakeBorderSimple:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"border_size": ("INT", {"default": 64}),
"border_type": (border_types_excluding_transparent, {"default": border_types[0]})
}}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "make_border"
CATEGORY = f"{cv_category_path}/Misc"
def make_border(self, image, border_size, border_type):
image = tensor2opencv(image, 0)
image = cv.copyMakeBorder(image, border_size, border_size, border_size, border_size,
border_types_map[border_type])
image = opencv2tensor(image)
return (image,)
class ConvertImg:
""" An explicit conversion, instead of using workarounds when using certain custom nodes. """
options_map = {
"RGBA": 4,
"RGB": 3,
"GRAY": 1,
}
options = list(options_map.keys())
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"image": ("IMAGE",),
"to": (cls.options, {"default": cls.options[1]})
}}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "convert"
CATEGORY = f"{cv_category_path}"
def convert(self, image, to):
image = tensor2opencv(image, self.options_map[to])
return (opencv2tensor(image),)
class AddAlpha:
method = ["default", "invert"]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"rgb_image": ("IMAGE",),
},
"optional": {
"alpha": ("IMAGE",),
"method": (cls.method, {"default": cls.method[0]}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "add_alpha"
CATEGORY = images_category_path
def add_alpha(self, rgb_image, alpha=None, method=None):
rgb_image = tensor2opencv(rgb_image, 3)
rgba = cv.cvtColor(rgb_image, cv.COLOR_RGB2RGBA)
if alpha is not None:
alpha = tensor2opencv(alpha, 1)
rgba[:, :, 3] = alpha if method == self.method[0] else 255 - alpha
rgba = opencv2tensor(rgba)
return (rgba,)
class FadeMaskEdges:
"""
The original intent is to premultiply and alpha blend a subject's edges to avoid outer pixels creeping in.
A very slight blur near the edges afterwards when using paste_original_blacks and low tightness may be required,
but this should be done after premultiplying and setting the alpha.
Stylized subject's, such as drawings with black outlines, may benefit from using different 2 edge fades:
1. a fade with higher edge size for the premultiplication, fading the subject into blackness
2. a tighter fade for the alpha
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"binary_image": ("IMAGE",),
"edge_size": ("FLOAT", {"default": 5.0, "min": 1.0, "step": 1.0}),
# how quick does it fade to black
"edge_tightness": ("FLOAT", {"default": 1.1, "min": 1.0, "max": 10.0, "step": 0.05}),
# how does it fade, may be used to weaken small lines; 1 = linear transition
"edge_exponent": ("FLOAT", {"default": 1, "min": 0.1, "max": 10.0, "step": 0.1}),
"smoothing_diameter": ("INT", {"default": 10, "min": 2, "max": 256, "step": 1}),
"paste_original_blacks": ("BOOLEAN", {"default": True})
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "apply"
CATEGORY = f"{cv_category_path}/Misc"
def apply(self, binary_image, edge_size, edge_tightness, edge_exponent, smoothing_diameter, paste_original_blacks):
binary_image = tensor2opencv(binary_image, 1)
# _, binary_image = cv.threshold(gray_image, 128, 255, cv.THRESH_BINARY) # suppose it's already binary
# compute L2 (euclidean) distance -> normalize with respect to edge size -> smooth
distance_transform = cv.distanceTransform(binary_image, cv.DIST_L2, cv.DIST_MASK_3)
normalized_distance = distance_transform / edge_size
smoothed_distance = cv.bilateralFilter(normalized_distance, smoothing_diameter, 75, 75)
# darken the white pixels based on smoothed distance and "edge tightness"
diff = 1 - smoothed_distance
darkened_image = (abs(diff * edge_tightness) ** (1 / edge_exponent)) * np.sign(diff)
darkened_image = np.clip(darkened_image, 0, 1)
darkened_image = (darkened_image * 255).astype(np.uint8)
if paste_original_blacks: # mask original black pixels
black_mask = binary_image < 1
darkened_image[black_mask] = 0
output_image = binary_image - darkened_image # darken original image
output_image = opencv2tensor(output_image)
return (output_image,)
# endregion
# region grabcut nodes
class FramedMaskGrabCut:
frame_options_values = {
'FULL_FRAME': 0,
'IGNORE_BOTTOM': 1,
'IGNORE_TOP': 2,
'IGNORE_RIGHT': 4,
'IGNORE_LEFT': 8,
'IGNORE_HORIZONTAL': 12,
'IGNORE_VERTICAL': 3,
}
frame_options = list(frame_options_values.keys())
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"thresh": ("IMAGE",),
"iterations": ("INT", {
"default": 25,
"min": 0,
"max": 200,
"step": 1
}),
"margin": ("INT", {
"default": 2,
"min": 1,
"max": 100,
"step": 1
}),
"frame_option": (cls.frame_options, {
"default": cls.frame_options[0]
}),
# to only use PR FGD set threshold_FGD to 0
# to only use only FGD set threshold_FGD to a lower value than threshold_PR_FGD
# using one of these also works as a safeguard in case thresh has other values besides 0s and 1s
"threshold_FGD": ("INT", {
"default": 250,
"min": 0,
"max": 255,
"step": 1
}),
"threshold_PR_FGD": ("INT", {
"default": 128,
"min": 1,
"max": 255,
"step": 1
}),
"output_format": (image_output_formats_options, {
"default": image_output_formats_options[0]
})
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "grab_cut"
CATEGORY = f"{cv_category_path}/GrabCut"
def grab_cut(self, image, thresh, iterations, margin, frame_option, threshold_FGD, threshold_PR_FGD, output_format):
image = tensor2opencv(image)
thresh = tensor2opencv(thresh, 1)
assert image.shape[:2] == thresh.shape
fg_model = np.zeros((1, 65), dtype="float")
bg_model = np.zeros((1, 65), dtype="float")
mask = np.full(image.shape[:2], cv.GC_PR_BGD, dtype=np.uint8) # probable background
# foreground and probable foreground
if threshold_FGD > threshold_PR_FGD:
mask[thresh >= threshold_PR_FGD] = cv.GC_PR_FGD
if threshold_FGD > 0:
mask[thresh >= threshold_FGD] = cv.GC_FGD
# check what borders should be painted
frame_option = self.frame_options_values[frame_option]
include_bottom = not (frame_option & self.frame_options_values['IGNORE_BOTTOM'])
include_top = not (frame_option & self.frame_options_values['IGNORE_TOP'])
include_right = not (frame_option & self.frame_options_values['IGNORE_RIGHT'])
include_left = not (frame_option & self.frame_options_values['IGNORE_LEFT'])
# paint the borders as being background
if include_bottom:
mask[-margin:, :] = cv.GC_BGD
if include_top:
mask[0:margin, :] = cv.GC_BGD
if include_right:
mask[:, -margin:] = cv.GC_BGD
if include_left:
mask[:, 0:margin] = cv.GC_BGD
mask, bg_model, fg_model = cv.grabCut(image, mask, None, bg_model, fg_model, iterCount=iterations,
mode=cv.GC_INIT_WITH_MASK)
# generate mask with "pixels" classified as background/foreground
output_mask = np.where((mask == cv.GC_BGD) | (mask == cv.GC_PR_BGD), 0, 1)
output_mask = (output_mask * 255).astype("uint8")
output_mask = maybe_convert_img(output_mask, 1, image_output_formats_options_map[output_format])
image = opencv2tensor(output_mask)
return (image,)
class RectGrabCut:
# TODO add option to crop or just leave as 0 the section outside the rect
# TODO maybe add option to exclude PR_BGD or include PR_FGD in outputMask
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"x1": ("INT", {
"default": 5,
"min": 0,
"max": 2000,
"step": 1
}),
"y1": ("INT", {
"default": 5,
"min": 0,
"max": 2000,
"step": 1
}),
"x2": ("INT", {
"default": 5,
"min": 0,
"max": 2000,
"step": 1
}),
"y2": ("INT", {
"default": 5,
"min": 0,
"max": 2000,
"step": 1
}),
"iterations": ("INT", {
"default": 25,
"min": 0,
"max": 200,
"step": 1
}),
"output_format": (image_output_formats_options, {
"default": image_output_formats_options[0]
})
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "grab_cut"
CATEGORY = f"{cv_category_path}/GrabCut"
def grab_cut(self, image, iterations, x1, y1, x2, y2, output_format):
image = tensor2opencv(image)
fg_model = np.zeros((1, 65), dtype="float")
bg_model = np.zeros((1, 65), dtype="float")
mask = np.zeros(image.shape[:2], dtype="uint8")
rect = (x1, y1, x2, y2)
mask, bg_model, fg_model = cv.grabCut(image, mask, rect, bg_model,
fg_model, iterCount=iterations, mode=cv.GC_INIT_WITH_RECT)
# generate mask with "pixels" classified as background/foreground
output_mask = np.where((mask == cv.GC_BGD) | (mask == cv.GC_PR_BGD),
0, 1)
output_mask = (output_mask * 255).astype("uint8")
output_mask = maybe_convert_img(output_mask, 1, image_output_formats_options_map[output_format])
image = opencv2tensor(output_mask)
# image = image[y1:y2, x1:x2] #TODO maybe add option whether to crop or not
return (image,)
class FramedMaskGrabCut2:
# TODO option to ignore probable background in sure_thresh
frame_options = ['FULL_FRAME', 'IGNORE_BOTTOM', 'IGNORE_TOP', 'IGNORE_RIGHT', 'IGNORE_LEFT', 'IGNORE_HORIZONTAL'
, 'IGNORE_VERTICAL']
frame_options_values = {
'FULL_FRAME': 0,
'IGNORE_BOTTOM': 1,
'IGNORE_TOP': 2,
'IGNORE_RIGHT': 4,
'IGNORE_LEFT': 8,
'IGNORE_HORIZONTAL': 12,
'IGNORE_VERTICAL': 3,
}
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"thresh_maybe": ("IMAGE",),
"thresh_sure": ("IMAGE",),
"iterations": ("INT", {
"default": 25,
"min": 0,
"max": 200,
"step": 1
}),
"margin": ("INT", {
"default": 2,
"min": 1,
"max": 100,
"step": 1
}),
"frame_option": (cls.frame_options, {
"default": 'FULL_FRAME'
}),
# source thresh may not be only 0s and 1s, use this as a safeguard
"binary_threshold": ("INT", {
"default": 128,
"min": 1,
"max": 255,
"step": 1
}),
"maybe_black_is_sure_background": ("BOOLEAN", {"default": False}),
"output_format": (image_output_formats_options, {
"default": image_output_formats_options[0]
})
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "grab_cut"
CATEGORY = f"{cv_category_path}/GrabCut"
def grab_cut(self, image, thresh_maybe, thresh_sure, iterations,
margin, frame_option, binary_threshold,
maybe_black_is_sure_background, output_format):
image = tensor2opencv(image)
thresh_maybe = tensor2opencv(thresh_maybe, 1)
thresh_sure = tensor2opencv(thresh_sure, 1)
fg_model = np.zeros((1, 65), dtype="float")
bg_model = np.zeros((1, 65), dtype="float")
mask = np.full(image.shape[:2], cv.GC_PR_BGD, dtype=np.uint8) # probable background
mask[thresh_maybe >= binary_threshold] = cv.GC_PR_FGD # probable foreground
mask[thresh_sure >= binary_threshold] = cv.GC_FGD # foreground
frame_option = self.frame_options_values[frame_option]
include_bottom = not (frame_option & self.frame_options_values['IGNORE_BOTTOM'])
include_top = not (frame_option & self.frame_options_values['IGNORE_TOP'])
include_right = not (frame_option & self.frame_options_values['IGNORE_RIGHT'])
include_left = not (frame_option & self.frame_options_values['IGNORE_LEFT'])
if include_bottom:
mask[-margin:, :] = cv.GC_BGD
if include_top:
mask[0:margin, :] = cv.GC_BGD
if include_right:
mask[:, -margin:] = cv.GC_BGD
if include_left:
mask[:, 0:margin] = cv.GC_BGD
if maybe_black_is_sure_background:
mask[thresh_maybe < binary_threshold] = cv.GC_BGD # background
mask, bg_model, fg_model = cv.grabCut(image, mask, None, bg_model, fg_model, iterCount=iterations,
mode=cv.GC_INIT_WITH_MASK)
# generate mask with "pixels" classified as background/foreground
output_mask = np.where((mask == cv.GC_BGD) | (mask == cv.GC_PR_BGD), 0, 1)
output_mask = (output_mask * 255).astype("uint8")
output_mask = maybe_convert_img(output_mask, 1, image_output_formats_options_map[output_format])
image = opencv2tensor(output_mask)
return (image,)
# endregion grabcut nodes
# region contour nodes
class Contours:
"""
Note:
The image is converted to grey, but no threshold is applied.
Apply the thresholding before using and feed a black and white image.
"""
approximation_modes_map = {
'CHAIN_APPROX_NONE': cv.CHAIN_APPROX_NONE,
'CHAIN_APPROX_SIMPLE': cv.CHAIN_APPROX_SIMPLE,
'CHAIN_APPROX_TC89_L1': cv.CHAIN_APPROX_TC89_L1,
'CHAIN_APPROX_TC89_KCOS': cv.CHAIN_APPROX_TC89_KCOS
}
approximation_modes = list(approximation_modes_map.keys())
retrieval_modes_map = {
'RETR_EXTERNAL': cv.RETR_EXTERNAL,
'RETR_LIST': cv.RETR_LIST,
'RETR_CCOMP': cv.RETR_CCOMP,
'RETR_TREE': cv.RETR_TREE,
'RETR_FLOODFILL': cv.RETR_FLOODFILL
}
retrieval_modes = list(retrieval_modes_map.keys())
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"retrieval_mode": (cls.retrieval_modes, {"default": "RETR_LIST"}),
"approximation_mode": (cls.approximation_modes, {"default": "CHAIN_APPROX_SIMPLE"}),
},
}
RETURN_TYPES = ("CV_CONTOURS", "CV_CONTOUR", "CV_CONTOURS_HIERARCHY")
FUNCTION = "find_contours"
CATEGORY = f"{cv_category_path}/Contour"
OUTPUT_IS_LIST = (False, True, False)
def find_contours(self, image, retrieval_mode, approximation_mode):
image = tensor2opencv(image)
thresh = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
# no thresh applied here, non zeroes are treated as 1 according to documentation;
# thresh should have been already applied to the image, before passing it to this node.
contours, hierarchy = cv.findContours(
thresh,
self.retrieval_modes_map[retrieval_mode],
self.approximation_modes_map[approximation_mode])
return (contours, contours, hierarchy,)
class DrawContours:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"contours": ("CV_CONTOURS",),
"index_to_draw": ("INT", {
"default": -1,
"min": -1,
"max": 1000,
"step": 1
}),
"thickness": ("INT", {
"default": 5,
"min": -1,
"max": 32,
"step": 1
}),
"color": ("COLOR",),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "draw"
CATEGORY = f"{cv_category_path}/Contour"
def draw(self, image, contours, index_to_draw, color, thickness):
background = tensor2opencv(image)
um_image = cv.UMat(background)
cv.drawContours(um_image, contours, index_to_draw, ImageColor.getcolor(color, "RGB"), thickness)
contour_image = um_image.get()
image = opencv2tensor(contour_image)
return (image,)
class GetContourFromList:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"contours": ("CV_CONTOURS",),
"index": ("INT", {"default": 0, "min": 0, "step": 1})
}
}
RETURN_TYPES = ("CV_CONTOUR",)
FUNCTION = "get_contour"
CATEGORY = f"{cv_category_path}/Contour"
def get_contour(self, contours, index):
if index >= len(contours):
return (None,)
return (contours[index],)
class ContourGetBoundingRect:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"contour": ("CV_CONTOUR",),
"return_mode": (rect_modes, {"default": rect_modes[1]})
},
}
RETURN_TYPES = tuple(["INT" for _ in range(4)])
FUNCTION = "compute"
CATEGORY = f"{cv_category_path}/Contour"
def compute(self, contour, return_mode):
if contour is None:
print("Contour = None !")
return (0, 0, 0, 0,)
# convert opencv boundingRect format to bounds
bounds = rect_modes_map[rect_modes[0]]["toBounds"](*cv.boundingRect(contour))
# convert from bounds to desired output format on return
return rect_modes_map[return_mode]["fromBounds"](*bounds)
class FilterContour:
@staticmethod
def MODE(cnts, fit):
sorted_list = sorted(cnts, key=fit)
return [sorted_list[len(sorted_list) // 2]]
return_modes_map = {
"MAX": lambda cnts, fit: [sorted(cnts, key=fit)[-1]],
"MIN": lambda cnts, fit: [sorted(cnts, key=fit)[0]],
"MODE": MODE,
"FILTER": lambda cnts, fit: list(filter(fit, cnts)),
}
return_modes = list(return_modes_map.keys())
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"contours": ("CV_CONTOURS",),
"fitness": ("STRING", {"multiline": True, "default":
"# Contour Fitness Function\n"}),
"select": (cls.return_modes, {"default": cls.return_modes[0]})
},
"optional": {
"image": ("IMAGE",),
"aux_contour": ("CV_CONTOUR",)
}
}
RETURN_TYPES = ("CV_CONTOUR", "CV_CONTOURS")
FUNCTION = "filter"
CATEGORY = f"{cv_category_path}/Contour"
def filter(self, contours, fitness, select, image=None, aux_contour=None):
import math
import cv2
import numpy
if len(contours) == 0:
print("Contour list is empty")
return ([[]], contours)
# region prepare inputs
if image is not None:
image = tensor2opencv(image)
fitness = prepare_text_for_eval(fitness)
# endregion
# region available functions
# cv methods, but cache them
@cache_with_ids(single=False)
def boundingRect(cnt):
return cv.boundingRect(cnt)
@cache_with_ids(single=False)
def contourArea(cnt):
return cv.contourArea(cnt)
@cache_with_ids(single=False)
def arcLength(cnt):
return cv.arcLength(cnt, True)
@cache_with_ids(single=True)
def minAreaRect(cnt):
return cv.minAreaRect(cnt)
@cache_with_ids(single=True)
def minEnclosingCircle(cnt):
return cv.minEnclosingCircle(cnt)
@cache_with_ids(single=True)
def fitEllipse(cnt):
return cv.fitEllipse(cnt)
@cache_with_ids(single=True)
def convexHull(cnt):
return cv.convexHull(cnt)
# useful properties; adapted from multiple sources, including cv documentation
@cache_with_ids(single=True)
def aspect_ratio(cnt):
_, _, w, h = boundingRect(cnt)
return float(w) / h
@cache_with_ids(single=True)
def extent(cnt):
area = contourArea(cnt)
_, _, w, h = boundingRect(cnt)
rect_area = w * h
return float(area) / rect_area
@cache_with_ids(single=True)
def solidity(cnt):
area = contourArea(cnt)
hull = convexHull(cnt)
hull_area = contourArea(hull)
return float(area) / hull_area
@cache_with_ids(single=True)
def equi_diameter(cnt):
area = contourArea(cnt)
return math.sqrt(4 * area / math.pi)
@cache_with_ids(single=True)
def center(cnt):
m = cv.moments(cnt)
c_x = int(m["m10"] / m["m00"])
c_y = int(m["m01"] / m["m00"])
return c_x, c_y
@cache_with_ids(single=False)
def contour_mask(cnt, img):
if len(img.shape) > 2:
height, width, _ = img.shape
else:
height, width = img.shape
mask = numpy.zeros((height, width, 1), numpy.uint8)
cv.drawContours(mask, [cnt], 0, 255, -1)
return mask
@cache_with_ids(single=True)
def mean_color(cnt, img):
return cv.mean(img, mask=contour_mask(cnt, img))
@cache_with_ids(single=True)
def mean_intensity(cnt, img):
gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
return mean_color(cnt, gray)[0]
@cache_with_ids(single=True)
def extreme_points(cnt):
l = tuple(cnt[cnt[:, :, 0].argmin()][0])
r = tuple(cnt[cnt[:, :, 0].argmax()][0])
t = tuple(cnt[cnt[:, :, 1].argmin()][0])
b = tuple(cnt[cnt[:, :, 1].argmax()][0])
return {"top": t, "right": r, "bottom": b, "left": l}
def intercepts_mask(cnt, img): # where img should be a binary mask
gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
intersection = cv2.bitwise_and(
gray, cv2.drawContours(np.zeros_like(gray), [cnt], 0, 255, thickness=cv2.FILLED))
return cv2.countNonZero(intersection) > 0
# endregion
available_funcs = {}
for key, value in locals().items():
if callable(value):
available_funcs[key] = value
fitness = eval(f"lambda c, i, a: {fitness}", {
"__builtins__": {},
"tuple": tuple, "list": list,
'm': math, 'cv': cv2, 'np': numpy,
**available_funcs
}, {})
ret = self.return_modes_map[select](contours, lambda c: fitness(c, image, aux_contour))
return (ret[0], ret,)
class ContourToMask:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"contour": ("CV_CONTOUR",),
"output_format": (image_output_formats_options, {
"default": image_output_formats_options[0]
})
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "draw"
CATEGORY = f"{cv_category_path}/Contour"
def draw(self, image, contour, output_format):
image = tensor2opencv(image, 1)
image = np.zeros(image.shape, dtype=np.uint8)
cv.drawContours(image, [contour], 0, (255), -1)
image = maybe_convert_img(image, 1, image_output_formats_options_map[output_format])
image = opencv2tensor(image)
return (image,)
# endregion contour nodes
# region Computational Photography
class SeamlessClone:
clone_modes_map = {
"NORMAL": cv.NORMAL_CLONE,
"MIXED": cv.MIXED_CLONE,
"MONO": cv.MONOCHROME_TRANSFER
}
clone_modes = list(clone_modes_map.keys())
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"dst": ("IMAGE",),
"src": ("IMAGE",),
"src_mask": ("IMAGE",),
"flag": (cls.clone_modes, {"default": cls.clone_modes[0]}),
"cx": ("INT", {"default": 0, "min": -999999, "step": 1}),
"cy": ("INT", {"default": 0, "min": -999999, "step": 1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "paste"
CATEGORY = f"{cv_category_path}/C.Photography"
def paste(self, src, dst, src_mask, flag, cx, cy):
src = tensor2opencv(src)
dst = tensor2opencv(dst)
src_mask = tensor2opencv(src_mask, 1)
result = cv.seamlessClone(src, dst, src_mask, (cx, cy), self.clone_modes_map[flag])
result = opencv2tensor(result)
return (result,)
class SeamlessCloneSimpler:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"dst": ("IMAGE",),
"src": ("IMAGE",),
"src_mask": ("IMAGE",),
"flag": (SeamlessClone.clone_modes, {"default": SeamlessClone.clone_modes[0]}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "paste"
CATEGORY = f"{cv_category_path}/C.Photography"
@staticmethod
def get_center(cv_mask):
br = cv.boundingRect(cv_mask)
return br[0] + br[2] // 2, br[1] + br[3] // 2
def paste(self, src, dst, src_mask, flag):
src_mask_cv = tensor2opencv(src_mask, 1)
cx, cy = SeamlessCloneSimpler.get_center(src_mask_cv)
sc = SeamlessClone()
return sc.paste(src, dst, src_mask, flag, cx, cy)
class Inpaint:
inpaint_method_map = {
"TELEA": cv.INPAINT_TELEA,
"NS": cv.INPAINT_NS,
}
inpaint_methods = list(inpaint_method_map.keys())
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"img": ("IMAGE",),
"mask": ("IMAGE",),
"radius": ("INT", {"default": 3, "min": 0, "step": 1}),
"flag": (cls.inpaint_methods, {"default": cls.inpaint_methods[0]}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "paint"
CATEGORY = f"{cv_category_path}/C.Photography"
def paint(self, img, mask, radius, flag):
img = tensor2opencv(img)
mask = tensor2opencv(mask, 1)
dst = cv.inpaint(img, mask, radius, self.inpaint_method_map[flag])
result = opencv2tensor(dst)
return (result,)
class ChameleonMask: # wtf would I name this node as?
mode_func_map = {
"GRAY": lambda i: cv.cvtColor(i, cv.COLOR_BGR2GRAY),
"VALUE": lambda i: cv.cvtColor(i, cv.COLOR_RGB2HSV)[:, :, 2],
"LIGHTNESS": lambda i: cv.cvtColor(i, cv.COLOR_RGB2HLS)[:, :, 1],
# not sure if these would be useful, but costs nothing to leave them here
"HUE": lambda i: cv.cvtColor(i, cv.COLOR_RGB2HSV)[:, :, 0],
"SATURATION (HSV)": lambda i: cv.cvtColor(i, cv.COLOR_RGB2HSV)[:, :, 1],
"SATURATION (HSL)": lambda i: cv.cvtColor(i, cv.COLOR_RGB2HLS)[:, :, 2],
}
modes = list(mode_func_map.keys())
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"dst": ("IMAGE",),
"src": ("IMAGE",),
"thresh_blur": ("INT", {"default": 30, "min": 2, "step": 2}),
"close_dist": ("INT", {"default": 32, "min": 0, "step": 1}),
"open_dist": ("INT", {"default": 32, "min": 0, "step": 1}),
"size_dist": ("INT", {"default": 8, "min": -99999, "step": 1}),
"mask_blur": ("INT", {"default": 64, "min": 0, "step": 2}),
"contrast_adjust": ("FLOAT", {"default": 2.4, "min": 0, "max": 20, "step": .5}),
"mode": (cls.modes, {"default": cls.modes[0]}),
"output_format": (image_output_formats_options, {
"default": image_output_formats_options[0]
}),
},
"optional": {
"optional_roi_mask": ("IMAGE",)
}
}
RETURN_TYPES = ("IMAGE", "IMAGE",)
FUNCTION = "create_mask"
CATEGORY = f"{cv_category_path}/C.Photography"
def create_mask(self, src, dst, thresh_blur, close_dist, open_dist, size_dist, mask_blur,
contrast_adjust, mode: str, output_format, optional_roi_mask=None):
src = tensor2opencv(src)
dst = tensor2opencv(dst)
thresh_blur += 1
if mask_blur > 0:
mask_blur += 1
# compute the difference between images based on mode
src = self.mode_func_map[mode](src) # type:ignore
dst = self.mode_func_map[mode](dst) # type:ignore
diff = cv.absdiff(src, dst)
if mode == "HUE":
diff = np.minimum(diff, 180 - diff)
# binary thresholding
# _, mask = cv.threshold(diff, threshold, 255, cv.THRESH_BINARY)
diff = cv.GaussianBlur(diff, (thresh_blur, thresh_blur), 0)
_, mask = cv.threshold(diff, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
if optional_roi_mask is not None:
optional_roi_mask = tensor2opencv(optional_roi_mask, 1)
mask[optional_roi_mask < 127] = 0
# morphological closing > closing > dilate/erode
if close_dist > 0:
close_kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (close_dist, close_dist))
mask = cv.morphologyEx(mask, cv.MORPH_CLOSE, close_kernel)
if open_dist > 0:
open_kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (open_dist, open_dist))
mask = cv.morphologyEx(mask, cv.MORPH_OPEN, open_kernel)
if size_dist > 0:
size_op = cv.MORPH_DILATE
size = size_dist
else:
size_op = cv.MORPH_ERODE
size = abs(size_dist)
if size_dist != 0:
size_kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (size, size))
mask = cv.morphologyEx(mask, size_op, size_kernel)
# gaussian blur + contrast adjust
if mask_blur > 0:
mask = cv.GaussianBlur(mask, (mask_blur, mask_blur), 0)
mask = cv.convertScaleAbs(mask, alpha=1 + contrast_adjust, beta=0) # / 100, beta=0)
# convert to target format and output as tensor
# note: diff is only meant to be used for debug purposes
mask = maybe_convert_img(mask, 1, image_output_formats_options_map[output_format])