-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnodes.py
More file actions
1567 lines (1314 loc) · 46.9 KB
/
nodes.py
File metadata and controls
1567 lines (1314 loc) · 46.9 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
from typing import Dict, List, Tuple
import torch
from pytorch360convert import c2e, e2c, e2e, e2p
class C2ENode:
"""
Cubemap To Equirectangular Node
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"e_img": ("IMAGE", {"default": None}),
"h": ("INT", {"default": -1}),
"w": ("INT", {"default": -1}),
"padding_mode": (
["bilinear", "bicubic", "nearest"],
{"default": "bilinear"},
),
"cube_format": (
["stack", "dice", "horizon", "list", "dict"],
{"default": "stack"},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Equirectangular Image",)
FUNCTION = "c2e"
CATEGORY = "pytorch360convert/equirectangular"
def c2e(
self,
e_img: torch.Tensor,
h=None,
w=None,
padding_mode: str = "bilinear",
cube_format: str = "stack",
) -> Tuple[torch.Tensor]:
assert e_img.shape[0] == 6, f"Input should have 6 faces, got {e_img.shape[0]}"
h = None if h < 1 else h
w = None if w < 1 else w
return (
c2e(
e_img.squeeze(0),
h=h,
w=w,
cube_format=cube_format,
mode=padding_mode,
channels_first=False,
).unsqueeze(0),
)
class E2CNode:
"""
Equirectangular to Cubemap Node
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"e_img": ("IMAGE", {"default": None}),
"face_width": ("INT", {"default": -1}),
"padding_mode": (
["bilinear", "bicubic", "nearest"],
{"default": "bilinear"},
),
"cube_format": (
["stack", "dice", "horizon", "list", "dict"],
{"default": "stack"},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Cubemap Image",)
FUNCTION = "e2c"
CATEGORY = "pytorch360convert/equirectangular"
def e2c(
self,
e_img: torch.Tensor,
face_width: int = -1,
padding_mode: str = "bilinear",
cube_format: str = "stack",
) -> Tuple[torch.Tensor]:
assert e_img.shape[0] == 1, (
"Only a batch size of 1 is currently" + f"supported, got {e_img.shape[0]}"
)
face_width = e_img.shape[1] // 2 if face_width < 1 else face_width
output = e2c(
e_img.squeeze(0),
face_w=face_width,
mode=padding_mode,
cube_format=cube_format,
channels_first=False,
)
output = output.unsqueeze(0) if output.dim() == 3 else output
return (output,)
class E2PNode:
"""
Equirectangular to Perspective Node
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"e_img": ("IMAGE", {"default": None}),
"fov_deg_h": ("FLOAT", {"default": 90.0}),
"fov_deg_v": ("FLOAT", {"default": 90.0}),
"h_deg": ("FLOAT", {"default": 0.0}),
"v_deg": ("FLOAT", {"default": 0.0}),
"out_h": ("INT", {"default": 512}),
"out_w": ("INT", {"default": 512}),
"in_rot_deg": ("FLOAT", {"default": 0.0}),
"padding_mode": (
["bilinear", "bicubic", "nearest"],
{"default": "bilinear"},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Perspective Image",)
FUNCTION = "e2p"
CATEGORY = "pytorch360convert/equirectangular"
def e2p(
self,
e_img: torch.Tensor,
fov_deg_h: float = 90.0,
fov_deg_v: float = 90.0,
h_deg: float = 0.0,
v_deg: float = 0.0,
out_h: int = 512,
out_w: int = 512,
in_rot_deg: float = 0.0,
padding_mode: str = "bilinear",
) -> Tuple[torch.Tensor]:
assert e_img.dim() == 4, f"e_img should have 4 dimensions, got {e_img.dim()}"
return (
e2p(
e_img,
fov_deg=(fov_deg_h, fov_deg_v),
h_deg=h_deg,
v_deg=v_deg,
out_hw=(out_h, out_w),
in_rot_deg=in_rot_deg,
mode=padding_mode,
channels_first=False,
),
)
class E2ENode:
"""
Equirectangular Rotation Node
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"e_img": ("IMAGE", {"default": None}),
"roll": ("FLOAT", {"default": 0.0}),
"h_deg": ("FLOAT", {"default": 0.0}),
"v_deg": ("FLOAT", {"default": 0.0}),
"padding_mode": (
["bilinear", "bicubic", "nearest"],
{"default": "bilinear"},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Rotated Image",)
FUNCTION = "e2e"
CATEGORY = "pytorch360convert/equirectangular"
def e2e(
self,
e_img: torch.Tensor,
roll: float = 0.0,
h_deg: float = 0.0,
v_deg: float = 0.0,
padding_mode: str = "bilinear",
) -> Tuple[torch.Tensor]:
assert e_img.dim() == 4, f"e_img should have 4 dimensions, got {e_img.dim()}"
return (
e2e(
e_img=e_img,
h_deg=h_deg,
v_deg=v_deg,
roll=roll,
mode=padding_mode,
channels_first=False,
),
)
class SplitFacesNode:
"""
Split a stack of cube faces for easy manipulation.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"face_stack": ("IMAGE", {"default": None}),
},
}
RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE")
RETURN_NAMES = ("Front", "Right", "Back", "Left", "Up", "Down")
FUNCTION = "split_faces"
CATEGORY = "pytorch360convert/miscellaneous"
def split_faces(self, face_stack: torch.Tensor) -> Tuple[torch.Tensor, ...]:
assert (
face_stack.dim() == 4
), f"face_stack should have 4 dimensions, got {face_stack.dim()}"
assert (
face_stack.shape[0] == 6
), f"face_stack should have 6 faces, got {face_stack.shape[0]}"
outputs = [face_stack[i].unsqueeze(0) for i in range(face_stack.shape[0])]
return tuple(outputs)
class StackFacesNode:
"""
Combine multiple cube faces into a stack.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"Front": ("IMAGE", {"default": None}),
"Right": ("IMAGE", {"default": None}),
"Back": ("IMAGE", {"default": None}),
"Left": ("IMAGE", {"default": None}),
"Up": ("IMAGE", {"default": None}),
"Down": ("IMAGE", {"default": None}),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Cubemap stack",)
FUNCTION = "stack_faces"
CATEGORY = "pytorch360convert/miscellaneous"
def stack_faces(
self,
Front: torch.Tensor,
Right: torch.Tensor,
Back: torch.Tensor,
Left: torch.Tensor,
Up: torch.Tensor,
Down: torch.Tensor,
) -> Tuple[torch.Tensor]:
assert (
Front.dim() == 4
and Right.dim() == 4
and Back.dim() == 4
and Left.dim() == 4
and Up.dim() == 4
and Down.dim() == 4
)
return (torch.cat([Front, Right, Back, Left, Up, Down], 0),)
class RollImageNode:
"""
Roll an image to make face seams easier to remove or access.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"image": ("IMAGE", {"default": None}),
"roll_x": ("INT", {"default": 0}),
"roll_y": ("INT", {"default": 0}),
"roll_x_by_50_percent": (
"BOOLEAN",
{
"default": False,
"tooltip": "Ignores roll_x and roll_y. Shifts image horizontally by 50%.",
},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Rolled Image",)
FUNCTION = "roll_image"
CATEGORY = "pytorch360convert/miscellaneous"
def roll_image(
self,
image: torch.Tensor,
roll_x: int = 0,
roll_y: int = 0,
roll_x_by_50_percent: bool = False,
) -> Tuple[torch.Tensor]:
assert image.dim() == 4, f"image should have 4 dimensions, got {image.dim()}"
if roll_x_by_50_percent:
_, H, W, _ = image.shape
px_half = W // 2
roll_y = 0
roll_x = px_half
return (torch.roll(image, shifts=(roll_y, roll_x), dims=(1, 2)),)
class C2EMaskedDiffNode:
"""
Cubemap To Equirectangular with Masked Diff Node
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"original_faces": ("IMAGE", {"default": None}),
"modified_faces": ("IMAGE", {"default": None}),
"original_equi": ("IMAGE", {"default": None}),
"padding_mode": (
["bilinear", "bicubic", "nearest"],
{"default": "bilinear"},
),
"cube_format": (
["stack", "dice", "horizon", "list", "dict"],
{"default": "stack"},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Equirectangular Image",)
FUNCTION = "c2e_masked_diff"
CATEGORY = "pytorch360convert/mask"
def c2e_masked_diff(
self,
original_faces: torch.Tensor,
modified_faces: torch.Tensor,
original_equi: torch.Tensor,
padding_mode: str = "bilinear",
cube_format: str = "stack",
) -> Tuple[torch.Tensor]:
assert original_equi.shape[0] == 1, (
"Only a batch size of 1 is currently supported"
+ f"for original_equi, got {original_equi.shape[0]}"
)
assert (
original_faces.shape[0] == 6
), f"original_faces should have 6 faces, got {original_faces.shape[0]}"
assert (
modified_faces.shape[0] == 6
), f"modified_faces should have 6 faces, got {modified_faces.shape[0]}"
new_equi = c2e(modified_faces, cube_format=cube_format, channels_first=False)
faces_mask = original_faces != modified_faces
mask_equi = c2e(
faces_mask.float(), cube_format=cube_format, channels_first=False
).bool()
return (torch.where(mask_equi, new_equi, original_equi),)
class CropImageWithCoordsNode:
"""
Crop an section of an image for manipulation
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"image": ("IMAGE", {"default": None}),
"crop_h": ("INT", {"default": 0}),
"crop_w": ("INT", {"default": 0}),
"crop_h2": ("INT", {"default": -1}),
"crop_w2": ("INT", {"default": -1}),
},
}
RETURN_TYPES = (
"IMAGE",
"LIST",
)
RETURN_NAMES = (
"Cropped Image",
"Coords",
)
FUNCTION = "crop_image"
CATEGORY = "pytorch360convert/miscellaneous"
def crop_image(
self,
image: torch.Tensor,
crop_h: int = 0,
crop_w: int = 0,
crop_h2: int = -1,
crop_w2: int = -1,
) -> Tuple[torch.Tensor, List[int]]:
assert image.dim() == 4, f"image should have 4 dimensions, got {image.dim()}"
_, H, W, _ = image.shape
# Calculate the center crop indices
if crop_h2 < 1:
start_h = (H - crop_h) // 2
end_h = start_h + crop_h
else:
start_h = crop_h
end_h = crop_h2
if crop_w2 < 1:
start_w = (W - crop_w) // 2
end_w = start_w + crop_w
else:
start_w = crop_w
end_w = crop_w2
cropped_tensor = image[:, start_h:end_h, start_w:end_w, :]
coords = [start_h, end_h, start_w, end_w]
return (
cropped_tensor,
coords,
)
class PasteImageWithCoordsNode:
"""
Add a cropped section back to the original image.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"full_image": ("IMAGE", {"default": None}),
"cropped_image": ("IMAGE", {"default": None}),
"coords": ("LIST", {"default": None}),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Pasted Image",)
FUNCTION = "paste_image"
CATEGORY = "pytorch360convert/miscellaneous"
def paste_image(
self, full_image: torch.Tensor, cropped_image: torch.Tensor, coords: List[int]
) -> Tuple[torch.Tensor]:
assert (
full_image.dim() == 4
), f"full_image should have 4 dimensions, got {full_image.dim()}"
assert (
cropped_image.dim() == 4
), f"cropped_image should have 4 dimensions, got {cropped_image.dim()}"
assert len(coords) == 4
start_h, end_h, start_w, end_w = coords
full_image[:, start_h:end_h, start_w:end_w, :] = cropped_image
return (full_image,)
class Pad180To360Node:
"""
Apply padding to a 180 degree equirectangular image, to make it 360 degrees.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"image": ("IMAGE", {"default": None}),
"fill_value": ("FLOAT", {"default": 0.0}),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Padded 360 Image",)
FUNCTION = "pad_180_to_360_image"
CATEGORY = "pytorch360convert/equirectangular"
def pad_180_to_360_image(
self, image: torch.Tensor, fill_value: float = 0.0
) -> Tuple[torch.Tensor]:
assert image.dim() == 4, f"image should have 4 dimensions, got {image.dim()}"
image = image.permute(0, 3, 1, 2)
H, W = image.shape[2:]
pad_left = W // 2
pad_right = W - pad_left
image_padded = torch.nn.functional.pad(
image, (pad_left, pad_right), mode="constant", value=fill_value
)
image_padded = image_padded.permute(0, 2, 3, 1)
return (image_padded,)
class Crop360To180Node:
"""
Crop a 360 degree equirectangular image to the central 180 degree part.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"image": ("IMAGE", {"default": None}),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Cropped 180 Image",)
FUNCTION = "crop_360_to_180_image"
CATEGORY = "pytorch360convert/equirectangular"
def crop_360_to_180_image(self, image: torch.Tensor) -> Tuple[torch.Tensor]:
"""
Crop a 360-degree equirectangular image to the central 180-degree part.
Args:
image (torch.Tensor): The 360-degree equirectangular image. Shape should
be: (B, H, W, C).
Returns:
torch.Tensor: The cropped 180-degree equirectangular image. Shape will be:
(B, H, W//2, C) where the width is halved.
Raises:
ValueError: If the input image width is less than or equal to 1.
"""
assert image.dim() == 4, f"image should have 4 dimensions, got {image.dim()}"
_, _, width, _ = image.shape
# Crop the central 180-degree part by slicing the image.
crop_start = width // 4
crop_end = 3 * width // 4
# Crop along the width dimension (left and right 180 degrees)
cropped_img = image[:, :, crop_start:crop_end, :]
return (cropped_img,)
class StereoToMonoScopicNode:
"""
Split a stereo image into 2 monoscopic images.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"image": ("IMAGE", {"default": None}),
"split_direction": (
["horizontal", "vertical"],
{"default": "horizontal"},
),
"larger_side": (["first", "second"], {"default": "first"}),
},
}
RETURN_TYPES = (
"IMAGE",
"IMAGE",
)
RETURN_NAMES = (
"First Image",
"Second Image",
)
FUNCTION = "split_stereo_image"
CATEGORY = "pytorch360convert/stereo"
def split_stereo_image(
self,
image: torch.Tensor,
split_direction: str = "horizontal",
larger_side: str = "first",
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Splits a batch of tensor images (BHWC format) into two halves either vertically
or horizontally, splitting exactly down the middle. In case of odd dimensions,
one side gets an extra pixel.
Args:
image (torch.Tensor): The tensor image batch to split. Shape should be:
(B, H, W, C).
split_direction (str, optional): The direction to split the image. Either
"horizontal" or "vertical". Default: "horizontal"
larger_side (str, optional): Specifies which side gets the extra pixel when
dimensions are odd. "first" gives the extra pixel to the first side
(top/left), "second" gives it to the second side (bottom/right).
Default: "first"
Returns:
Tuple[torch.Tensor, torch.Tensor]: A tuple containing the first and second
halves of the split images. The shape of each tensor is:
- For horizontal split: (B, H/2, W, C)
- For vertical split: (B, H, W/2, C)
Raises:
ValueError: If `split_direction` is not "horizontal" or "vertical".
"""
_, height, width, channels = image.shape
if split_direction == "vertical":
# Split horizontally (by height)
mid_point = height // 2
if height % 2 != 0: # If height is odd
if larger_side == "first":
first_half = image[:, : mid_point + 1, :, :]
second_half = image[:, mid_point + 1 :, :, :]
else: # "second"
first_half = image[:, :mid_point, :, :]
second_half = image[:, mid_point:, :]
else:
# Even height, just split in the middle
first_half = image[:, :mid_point, :, :]
second_half = image[:, mid_point:, :]
elif split_direction == "horizontal":
# Split vertically (by width)
mid_point = width // 2
if width % 2 != 0: # If width is odd
if larger_side == "first":
first_half = image[:, :, : mid_point + 1, :]
second_half = image[:, :, mid_point + 1 :, :]
else: # "second"
first_half = image[:, :, :mid_point, :]
second_half = image[:, :, mid_point:, :]
else:
# Even width, just split in the middle
first_half = image[:, :, :mid_point, :]
second_half = image[:, :, mid_point:, :]
else:
raise ValueError(
"Invalid split direction. Please choose"
+ " 'horizontal' or 'vertical'. "
+ f"Got {split_direction}"
)
return (first_half, second_half)
class MonoScopicToStereoNode:
"""
Merge two monoscopic images into a stereo image.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"first_image": ("IMAGE", {"default": None}),
"second_image": ("IMAGE", {"default": None}),
"merge_direction": (
["horizontal", "vertical"],
{"default": "horizontal"},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Stereo Image",)
FUNCTION = "merge_monoscopic_to_stereo"
CATEGORY = "pytorch360convert/stereo"
def merge_monoscopic_to_stereo(
self,
first_image: torch.Tensor,
second_image: torch.Tensor,
merge_direction: str = "horizontal",
) -> Tuple[torch.Tensor]:
"""
Merges two monoscopic images into a single stereo image by concatenating
the two images either horizontally or vertically.
Args:
first_image (torch.Tensor): The left monoscopic image. Shape should
be: (B, H, W, C).
second_image (torch.Tensor): The right monoscopic image. Shape should
be: (B, H, W, C).
merge_direction (str, optional): The direction to merge the images. Either
"horizontal" or "vertical". Default: "horizontal"
Returns:
torch.Tensor: The merged stereo image.
Raises:
ValueError: If `merge_direction` is not "horizontal" or "vertical".
"""
f_batch_size, f_height, f_width, f_channels = first_image.shape
s_batch_size, s_height, s_width, s_channels = second_image.shape
if merge_direction == "horizontal":
assert f_batch_size == s_batch_size, (
"Batch size must match: " + f"{f_batch_size} vs {s_batch_size}"
)
assert f_height == s_height, (
"Height must match: " + f"{f_height} vs {s_height}"
)
assert f_channels == s_channels, (
"Channels must match: " + f"{f_channels} vs {s_channels}"
)
# Concatenate horizontally (by width)
stereo_image = torch.cat((first_image, second_image), dim=2)
elif merge_direction == "vertical":
assert f_batch_size == s_batch_size, (
"Batch size must match: " + f"{f_batch_size} vs {s_batch_size}"
)
assert f_width == s_width, "Width must match: " + f"{f_width} vs {s_width}"
assert f_channels == s_channels, (
"Channels must match: " + f"{f_channels} vs {s_channels}"
)
# Concatenate vertically (by height)
stereo_image = torch.cat((first_image, second_image), dim=1)
else:
raise ValueError(
"Invalid split direction. Please choose"
+ " 'horizontal' or 'vertical'. "
+ f"Got {merge_direction}"
)
return (stereo_image,)
def _conv_forward(
self, x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor
) -> torch.Tensor:
x = torch.nn.functional.pad(x, self.padding_values_x, mode="circular")
x = torch.nn.functional.pad(x, self.padding_values_y, mode="constant")
return torch.nn.functional.conv2d(
x, weight, bias, self.stride, (0, 0), self.dilation, self.groups
)
def _apply_circular_conv2d_padding(
model: torch.nn.Module, is_vae: bool = False, x_axis_only: bool = True
) -> torch.nn.Module:
for layer in model.first_stage_model.modules() if is_vae else model.modules():
if isinstance(layer, torch.nn.Conv2d):
if x_axis_only:
layer.padding_values_x = (
layer._reversed_padding_repeated_twice[0],
layer._reversed_padding_repeated_twice[1],
0,
0,
)
layer.padding_values_y = (
0,
0,
layer._reversed_padding_repeated_twice[2],
layer._reversed_padding_repeated_twice[3],
)
layer._conv_forward = _conv_forward.__get__(layer, torch.nn.Conv2d)
else:
layer.padding_mode = "circular"
return model
class ApplyCircularConvPaddingModel:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": (
"MODEL",
{"tooltip": "Model to add circular x-axis conv2d padding to."},
),
"inplace": (
"BOOLEAN",
{
"default": True,
"tooltip": "Modify "
+ "the already loaded model (True) or a copy of the model (False). "
+ "If True, model will have to be reloaded to restore padding to "
+ "the original values. Modifying inplace will use less memory.",
},
),
"x_axis_only": (
"BOOLEAN",
{
"default": True,
"tooltip": "Apply"
+ " circular padding only to the x-axis or to both the x and y axes.",
},
),
},
}
CATEGORY = "pytorch360convert/models"
RETURN_TYPES = ("MODEL",)
FUNCTION = "run"
def run(
self, model: torch.nn.Module, inplace: bool = True, x_axis_only: bool = True
) -> Tuple[torch.nn.Module]:
if inplace:
use_model = model
else:
use_model = copy.deepcopy(model)
_apply_circular_conv2d_padding(use_model.model, False, x_axis_only)
return (use_model,)
class ApplyCircularConvPaddingVAE:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"vae": (
"VAE",
{"tooltip": "VAE to add circular x-axis conv2d padding to."},
),
"inplace": (
"BOOLEAN",
{
"default": True,
"tooltip": "Modify "
+ "the already loaded VAE (True) or a copy of the VAE (False). "
+ "If True, VAE will have to be reloaded to restore padding to "
+ "the original values. Modifying inplace will use less memory.",
},
),
"x_axis_only": (
"BOOLEAN",
{
"default": True,
"tooltip": "Apply"
+ " circular padding only to the x-axis or to both the x and y axes.",
},
),
}
}
RETURN_TYPES = ("VAE",)
FUNCTION = "run"
CATEGORY = "pytorch360convert/models"
def run(
self, vae: torch.nn.Module, inplace: bool = True, x_axis_only: bool = True
) -> Tuple[torch.nn.Module]:
if inplace:
use_vae = vae
else:
use_vae = copy.deepcopy(vae)
_apply_circular_conv2d_padding(use_vae, True, x_axis_only)
return (use_vae,)
def _create_center_seam_mask(
x: torch.Tensor, frac_width: float = 0.10, pixel_width: int = 0, feather: int = 0
) -> torch.Tensor:
"""
For a ComfyUI-style mask: shape [B, H, W], values 0 or 1, with optional feathering.
Args:
x (torch.Tensor): input tensor with shape [B, H, W, C].
frac_width (float, optional): fraction of input width for the vertical strip.
pixel_width (int, optional): width of the seam in pixels (if > 0).
feather (int, optional): pixel size of feathering on both sides of the mask.
Returns:
mask: torch.Tensor of shape [B, H, W] with float values 0.0 to 1.0.
"""
# Extract batch, height, and width from x
B, H, W, *_ = x.shape
# Determine strip width
if pixel_width > 0:
strip = pixel_width
else:
strip = max(1, int(W * frac_width))
x0 = (W - strip) // 2
x1 = x0 + strip
# Create the mask with zeros
mask = torch.zeros((B, H, W), dtype=x.dtype, device=x.device)
if feather <= 0:
mask[:, :, x0:x1] = 1.0
else:
# Create feathered mask
# Left feather region
left_feather_start = max(0, x0 - feather)
left_feather_end = x0
if left_feather_end > left_feather_start:
feather_steps = torch.linspace(
0.0,
1.0,
left_feather_end - left_feather_start,
dtype=x.dtype,
device=x.device,
)
mask[:, :, left_feather_start:left_feather_end] = feather_steps[
None, None, :
]
# Center region (full mask)
mask[:, :, x0:x1] = 1.0
# Right feather region
right_feather_start = x1
right_feather_end = min(W, x1 + feather)
if right_feather_end > right_feather_start:
feather_steps = torch.linspace(
1.0,
0.0,
right_feather_end - right_feather_start,
dtype=x.dtype,
device=x.device,
)
mask[:, :, right_feather_start:right_feather_end] = feather_steps[
None, None, :
]
return mask
class CreateSeamMask:
"""
Create a seam mask for inpainting on equirectangular images.
"""
@classmethod
def INPUT_TYPES(s) -> Dict:
return {
"required": {
"image": ("IMAGE", {"default": None}),
"frac_width": ("FLOAT", {"default": 0.10}),
"pixel_width": (
"INT",
{
"default": 0,
"tooltip": "Width of the seam in pixels."
+ " If > 0, frac_width is ignored in favour of width_pixel.",
},
),
"feather": (
"INT",
{"default": 0, "tooltip": "Pixel size of the feathering."},
),
"roll_x_by_50_percent": (
"BOOLEAN",
{
"default": False,
"tooltip": "Shifts the output mask horizontally by 50%."
+ " Equivalent to a 180 degree rotation on an equirectangular image.",
},
),
},