-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathdepthmap.py
1995 lines (1706 loc) · 82.5 KB
/
depthmap.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
# Author: thygate
# https://github.com/thygate/stable-diffusion-webui-depthmap-script
import modules.scripts as scripts
import gradio as gr
from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call, wrap_gradio_call
from modules.ui import plaintext_to_html
from modules import processing, images, shared, sd_samplers, devices
from modules.processing import create_infotext, process_images, Processed
from modules.shared import opts, cmd_opts, state, Options
from modules import script_callbacks
from modules.images import get_next_sequence_number
from numba import njit, prange
from torchvision.transforms import Compose, transforms
from PIL import Image
from pathlib import Path
from operator import getitem
from tqdm import trange
from functools import reduce
from skimage.transform import resize
import sys
import torch, gc
import torch.nn as nn
import cv2
import os.path
import contextlib
import matplotlib.pyplot as plt
import numpy as np
import skimage.measure
import copy
import platform
import vispy
import imageio
sys.path.append('extensions/stable-diffusion-webui-depthmap-script/scripts')
# midas imports
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
from midas.transforms import Resize, NormalizeImage, PrepareForNet
# AdelaiDepth/LeReS imports
from lib.multi_depth_model_woauxi import RelDepthModel
from lib.net_tools import strip_prefix_if_present
# pix2pix/merge net imports
from pix2pix.options.test_options import TestOptions
from pix2pix.models.pix2pix4depth_model import Pix2Pix4DepthModel
# 3d-photo-inpainting imports
from inpaint.mesh import write_ply, read_ply, output_3d_photo
from inpaint.networks import Inpaint_Color_Net, Inpaint_Depth_Net, Inpaint_Edge_Net
from inpaint.utils import path_planning
from inpaint.bilateral_filtering import sparse_bilateral_filtering
# background removal
from rembg import new_session, remove
whole_size_threshold = 1600 # R_max from the paper
pix2pixsize = 1024
scriptname = "DepthMap v0.3.8"
class Script(scripts.Script):
def title(self):
return scriptname
def show(self, is_img2img):
return True
def ui(self, is_img2img):
with gr.Column(variant='panel'):
with gr.Row():
compute_device = gr.Radio(label="Compute on", choices=['GPU','CPU'], value='GPU', type="index")
model_type = gr.Dropdown(label="Model", choices=['res101', 'dpt_beit_large_512 (midas 3.1)', 'dpt_beit_large_384 (midas 3.1)', 'dpt_large_384 (midas 3.0)','dpt_hybrid_384 (midas 3.0)','midas_v21','midas_v21_small'], value='res101', type="index", elem_id="tabmodel_type")
with gr.Group():
with gr.Row():
net_width = gr.Slider(minimum=64, maximum=2048, step=64, label='Net width', value=512)
net_height = gr.Slider(minimum=64, maximum=2048, step=64, label='Net height', value=512)
match_size = gr.Checkbox(label="Match input size (size is ignored when using boost)",value=False)
with gr.Group():
with gr.Row():
boost = gr.Checkbox(label="BOOST (multi-resolution merging)",value=True)
invert_depth = gr.Checkbox(label="Invert DepthMap (black=near, white=far)",value=False)
with gr.Group():
with gr.Row():
clipdepth = gr.Checkbox(label="Clip and renormalize",value=False)
with gr.Row():
clipthreshold_far = gr.Slider(minimum=0, maximum=1, step=0.001, label='Far clip', value=0)
clipthreshold_near = gr.Slider(minimum=0, maximum=1, step=0.001, label='Near clip', value=1)
with gr.Group():
with gr.Row():
combine_output = gr.Checkbox(label="Combine into one image.",value=False)
combine_output_axis = gr.Radio(label="Combine axis", choices=['Vertical','Horizontal'], value='Horizontal', type="index")
with gr.Row():
save_depth = gr.Checkbox(label="Save DepthMap",value=True)
show_depth = gr.Checkbox(label="Show DepthMap",value=True)
show_heat = gr.Checkbox(label="Show HeatMap",value=False)
with gr.Group():
with gr.Row():
gen_stereo = gr.Checkbox(label="Generate Stereo side-by-side image",value=False)
gen_stereo_count = gr.Slider(minimum=2, maximum=10, step=2, label="Side-by-side image count", value=2)
gen_stereotb = gr.Checkbox(label="Generate Stereo top-bottom image",value=False)
gen_anaglyph = gr.Checkbox(label="Generate Stereo anaglyph image (red/cyan)",value=False)
with gr.Row():
stereo_divergence = gr.Slider(minimum=0.05, maximum=100.005, step=0.01, label='Divergence (3D effect)', value=2.5)
with gr.Row():
stereo_fill = gr.Dropdown(label="Gap fill technique", choices=['none', 'naive', 'naive_interpolating', 'polylines_soft', 'polylines_sharp'], value='polylines_sharp', type="index", elem_id="stereo_fill_type")
stereo_balance = gr.Slider(minimum=-1.0, maximum=1.0, step=0.05, label='Balance between eyes', value=0.0)
with gr.Group():
with gr.Row():
inpaint = gr.Checkbox(label="Generate 3D inpainted mesh. (Sloooow)",value=False, visible=False)
inpaint_vids = gr.Checkbox(label="Generate 4 demo videos with 3D inpainted mesh.",value=False)
with gr.Group():
with gr.Row():
background_removal = gr.Checkbox(label="Remove background",value=False)
save_background_removal_masks = gr.Checkbox(label="Save the foreground masks",value=False)
pre_depth_background_removal = gr.Checkbox(label="pre-depth background removal",value=False)
with gr.Row():
background_removal_model = gr.Dropdown(label="Rembg Model", choices=['u2net','u2netp','u2net_human_seg', 'silueta'], value='u2net', type="value", elem_id="backgroundmodel_type")
with gr.Box():
gr.HTML("Information, comment and share @ <a href='https://github.com/thygate/stable-diffusion-webui-depthmap-script'>https://github.com/thygate/stable-diffusion-webui-depthmap-script</a>")
gen_normal = gr.Checkbox(label="Generate Normalmap (hidden! api only)",value=False, visible=False)
clipthreshold_far.change(
fn = lambda a, b: a if b < a else b,
inputs = [clipthreshold_far, clipthreshold_near],
outputs=[clipthreshold_near]
)
clipthreshold_near.change(
fn = lambda a, b: a if b > a else b,
inputs = [clipthreshold_near, clipthreshold_far],
outputs=[clipthreshold_far]
)
return [compute_device, model_type, net_width, net_height, match_size, invert_depth, boost, save_depth, show_depth, show_heat, combine_output, combine_output_axis, gen_stereo, gen_stereotb, gen_stereo_count, gen_anaglyph, stereo_divergence, stereo_fill, stereo_balance, clipdepth, clipthreshold_far, clipthreshold_near, inpaint, inpaint_vids, background_removal_model, background_removal, pre_depth_background_removal, save_background_removal_masks, gen_normal]
# run from script in txt2img or img2img
def run(self, p, compute_device, model_type, net_width, net_height, match_size, invert_depth, boost, save_depth, show_depth, show_heat, combine_output, combine_output_axis, gen_stereo, gen_stereotb, gen_stereo_count, gen_anaglyph, stereo_divergence, stereo_fill, stereo_balance, clipdepth, clipthreshold_far, clipthreshold_near, inpaint, inpaint_vids, background_removal_model, background_removal, pre_depth_background_removal, save_background_removal_masks, gen_normal):
# sd process
processed = processing.process_images(p)
processed.sampler = p.sampler # for create_infotext
inputimages = []
for count in range(0, len(processed.images)):
# skip first grid image
if count == 0 and len(processed.images) > 1 and opts.return_grid:
continue
inputimages.append(processed.images[count])
#remove on base image before depth calculation
background_removed_images = []
if background_removal:
if pre_depth_background_removal:
inputimages = batched_background_removal(inputimages, background_removal_model)
background_removed_images = inputimages
else:
background_removed_images = batched_background_removal(inputimages, background_removal_model)
newmaps, mesh_fi = run_depthmap(processed, p.outpath_samples, inputimages, None, compute_device, model_type, net_width, net_height, match_size, invert_depth, boost, save_depth, show_depth, show_heat, combine_output, combine_output_axis, gen_stereo, gen_stereotb, gen_stereo_count, gen_anaglyph, stereo_divergence, stereo_fill, stereo_balance, clipdepth, clipthreshold_far, clipthreshold_near, inpaint, inpaint_vids, "mp4", 0, background_removal, background_removed_images, save_background_removal_masks, gen_normal)
for img in newmaps:
processed.images.append(img)
return processed
def run_depthmap(processed, outpath, inputimages, inputnames, compute_device, model_type, net_width, net_height, match_size, invert_depth, boost, save_depth, show_depth, show_heat, combine_output, combine_output_axis, gen_stereo, gen_stereotb, gen_stereo_count, gen_anaglyph, stereo_divergence, stereo_fill, stereo_balance, clipdepth, clipthreshold_far, clipthreshold_near, inpaint, inpaint_vids, fnExt, vid_ssaa, background_removal, background_removed_images, save_background_removal_masks, gen_normal):
if len(inputimages) == 0 or inputimages[0] == None:
return []
print('\n%s' % scriptname)
# unload sd model
shared.sd_model.cond_stage_model.to(devices.cpu)
shared.sd_model.first_stage_model.to(devices.cpu)
# init torch device
global device
if compute_device == 0:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
else:
device = torch.device("cpu")
print("device: %s" % device)
# model path and name
model_dir = "./models/midas"
if model_type == 0:
model_dir = "./models/leres"
# create paths to model if not present
os.makedirs(model_dir, exist_ok=True)
os.makedirs('./models/pix2pix', exist_ok=True)
outimages = []
try:
print("Loading model weights from ", end=" ")
#"res101"
if model_type == 0:
model_path = f"{model_dir}/res101.pth"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://cloudstor.aarnet.edu.au/plus/s/lTIJF4vrvHCAI31/download")
if compute_device == 0:
checkpoint = torch.load(model_path)
else:
checkpoint = torch.load(model_path,map_location=torch.device('cpu'))
model = RelDepthModel(backbone='resnext101')
model.load_state_dict(strip_prefix_if_present(checkpoint['depth_model'], "module."), strict=True)
del checkpoint
devices.torch_gc()
#"dpt_beit_large_512" midas 3.1
if model_type == 1:
model_path = f"{model_dir}/dpt_beit_large_512.pt"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_512.pt")
model = DPTDepthModel(
path=model_path,
backbone="beitl16_512",
non_negative=True,
)
net_w, net_h = 512, 512
resize_mode = "minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
#"dpt_beit_large_384" midas 3.1
if model_type == 2:
model_path = f"{model_dir}/dpt_beit_large_384.pt"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_384.pt")
model = DPTDepthModel(
path=model_path,
backbone="beitl16_384",
non_negative=True,
)
net_w, net_h = 384, 384
resize_mode = "minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
#"dpt_large_384" midas 3.0
if model_type == 3:
model_path = f"{model_dir}/dpt_large-midas-2f21e586.pt"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt")
model = DPTDepthModel(
path=model_path,
backbone="vitl16_384",
non_negative=True,
)
net_w, net_h = 384, 384
resize_mode = "minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
#"dpt_hybrid_384" midas 3.0
elif model_type == 4:
model_path = f"{model_dir}/dpt_hybrid-midas-501f0c75.pt"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt")
model = DPTDepthModel(
path=model_path,
backbone="vitb_rn50_384",
non_negative=True,
)
net_w, net_h = 384, 384
resize_mode="minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
#"midas_v21"
elif model_type == 5:
model_path = f"{model_dir}/midas_v21-f6b98070.pt"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt")
model = MidasNet(model_path, non_negative=True)
net_w, net_h = 384, 384
resize_mode="upper_bound"
normalization = NormalizeImage(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
#"midas_v21_small"
elif model_type == 6:
model_path = f"{model_dir}/midas_v21_small-70d6b9c8.pt"
print(model_path)
if not os.path.exists(model_path):
download_file(model_path,"https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt")
model = MidasNet_small(model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True})
net_w, net_h = 256, 256
resize_mode="upper_bound"
normalization = NormalizeImage(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
# load merge network if boost enabled
if boost:
pix2pixmodel_path = './models/pix2pix/latest_net_G.pth'
if not os.path.exists(pix2pixmodel_path):
download_file(pix2pixmodel_path,"https://sfu.ca/~yagiz/CVPR21/latest_net_G.pth")
opt = TestOptions().parse()
if compute_device == 1:
opt.gpu_ids = [] # cpu mode
pix2pixmodel = Pix2Pix4DepthModel(opt)
pix2pixmodel.save_dir = './models/pix2pix'
pix2pixmodel.load_networks('latest')
pix2pixmodel.eval()
devices.torch_gc()
# prepare for evaluation
model.eval()
# optimize
if device == torch.device("cuda"):
model = model.to(memory_format=torch.channels_last)
if not cmd_opts.no_half and model_type != 0 and not boost:
model = model.half()
model.to(device)
print("Computing depthmap(s) ..")
inpaint_imgs = []
inpaint_depths = []
# iterate over input (generated) images
numimages = len(inputimages)
for count in trange(0, numimages):
print('\n')
# override net size
if (match_size):
net_width, net_height = inputimages[count].width, inputimages[count].height
# input image
img = cv2.cvtColor(np.asarray(inputimages[count]), cv2.COLOR_BGR2RGB) / 255.0
# compute
if not boost:
if model_type == 0:
prediction = estimateleres(img, model, net_width, net_height)
else:
prediction = estimatemidas(img, model, net_width, net_height, resize_mode, normalization)
else:
prediction = estimateboost(img, model, model_type, pix2pixmodel)
# output
depth = prediction
numbytes=2
depth_min = depth.min()
depth_max = depth.max()
max_val = (2**(8*numbytes))-1
# check output before normalizing and mapping to 16 bit
if depth_max - depth_min > np.finfo("float").eps:
out = max_val * (depth - depth_min) / (depth_max - depth_min)
else:
out = np.zeros(depth.shape)
# single channel, 16 bit image
img_output = out.astype("uint16")
# invert depth map
if invert_depth ^ model_type == 0:
img_output = cv2.bitwise_not(img_output)
# apply depth clip and renormalize if enabled
if clipdepth:
img_output = clipdepthmap(img_output, clipthreshold_far, clipthreshold_near)
#img_output = cv2.blur(img_output, (3, 3))
# three channel, 8 bits per channel image
img_output2 = np.zeros_like(inputimages[count])
img_output2[:,:,0] = img_output / 256.0
img_output2[:,:,1] = img_output / 256.0
img_output2[:,:,2] = img_output / 256.0
# if 3dinpainting, store maps for processing in second pass
if inpaint:
inpaint_imgs.append(inputimages[count])
inpaint_depths.append(img_output)
# get generation parameters
if processed is not None and hasattr(processed, 'all_prompts') and opts.enable_pnginfo:
info = create_infotext(processed, processed.all_prompts, processed.all_seeds, processed.all_subseeds, "", 0, count)
else:
info = None
basename = 'depthmap'
if inputnames is not None:
if inputnames[count] is not None:
p = Path(inputnames[count])
basename = p.stem
rgb_image = inputimages[count]
#applying background masks after depth
if background_removal:
print('applying background masks')
background_removed_image = background_removed_images[count]
#maybe a threshold cut would be better on the line below.
background_removed_array = np.array(background_removed_image)
bg_mask = (background_removed_array[:,:,0]==0)&(background_removed_array[:,:,1]==0)&(background_removed_array[:,:,2]==0)&(background_removed_array[:,:,3]<=0.2)
far_value = 255 if invert_depth else 0
img_output[bg_mask] = far_value * far_value #255*255 or 0*0
#should this be optional
if (processed is not None):
images.save_image(background_removed_image, outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_background_removed")
else:
images.save_image(background_removed_image, path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None, suffix="_background_removed")
outimages.append(background_removed_image )
if save_background_removal_masks:
bg_array = (1 - bg_mask.astype('int8'))*255
mask_array = np.stack( (bg_array, bg_array, bg_array, bg_array), axis=2)
mask_image = Image.fromarray( mask_array.astype(np.uint8))
if (processed is not None):
images.save_image(mask_image, outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_foreground_mask")
else:
images.save_image(mask_image, path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None, suffix="_foreground_mask")
outimages.append(mask_image)
if not combine_output:
if show_depth:
outimages.append(Image.fromarray(img_output))
if save_depth and processed is not None:
# only save 16 bit single channel image when PNG format is selected
if opts.samples_format == "png":
images.save_image(Image.fromarray(img_output), outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_depth")
else:
images.save_image(Image.fromarray(img_output2), outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_depth")
elif save_depth:
# from depth tab
# only save 16 bit single channel image when PNG format is selected
if opts.samples_format == "png":
images.save_image(Image.fromarray(img_output), path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None)
else:
images.save_image(Image.fromarray(img_output2), path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None)
else:
img_concat = np.concatenate((rgb_image, img_output2), axis=combine_output_axis)
if show_depth:
outimages.append(Image.fromarray(img_concat))
if save_depth and processed is not None:
images.save_image(Image.fromarray(img_concat), outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_depth")
elif save_depth:
# from tab
images.save_image(Image.fromarray(img_concat), path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None)
if show_heat:
colormap = plt.get_cmap('inferno')
heatmap = (colormap(img_output2[:,:,0] / 256.0) * 2**16).astype(np.uint16)[:,:,:3]
outimages.append(heatmap)
if gen_stereo or gen_anaglyph or gen_stereotb:
print("Generating Stereo image with "+str(gen_stereo_count)+" images..")
#img_output = cv2.blur(img_output, (3, 3))
balance = (stereo_balance + 1) / 2
original_image = np.asarray(inputimages[count])
img_array = []
# Make the stereogram iteratively
for i in np.linspace(-1,1,gen_stereo_count):
img_array.append(apply_stereo_divergence(original_image, img_output, (i) * stereo_divergence * (1.0/gen_stereo_count), stereo_fill))
# Keep the L/R generation for anaglyph
left_image = apply_stereo_divergence(original_image, img_output, - stereo_divergence * balance, stereo_fill)
right_image = apply_stereo_divergence(original_image, img_output, stereo_divergence * 1-balance, stereo_fill)
stereo_img = np.hstack(img_array)
stereotb_img = np.vstack([left_image, right_image])
# flip sbs left/right if enabled in settings
if hasattr(opts, 'depthmap_script_sbsflip'):
if opts.depthmap_script_sbsflip:
stereo_img = np.hstack(img_array.reverse)
stereotb_img = np.vstack(img_array.reverse)
if gen_stereo:
outimages.append(stereo_img)
if gen_stereotb:
outimages.append(stereotb_img)
if gen_anaglyph:
print("Generating Anaglyph image..")
anaglyph_img = overlap(left_image, right_image)
outimages.append(anaglyph_img)
if (processed is not None):
if gen_stereo:
images.save_image(Image.fromarray(stereo_img), outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_stereo")
if gen_stereotb:
images.save_image(Image.fromarray(stereotb_img), outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_stereotb")
if gen_anaglyph:
images.save_image(Image.fromarray(anaglyph_img), outpath, "", processed.all_seeds[count], processed.all_prompts[count], opts.samples_format, info=info, p=processed, suffix="_anaglyph")
else:
# from tab
if gen_stereo:
images.save_image(Image.fromarray(stereo_img), path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None, suffix="_stereo")
if gen_stereotb:
images.save_image(Image.fromarray(stereotb_img), path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None, suffix="_stereotb")
if gen_anaglyph:
images.save_image(Image.fromarray(anaglyph_img), path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=None, forced_filename=None, suffix="_anaglyph")
if gen_normal:
# taken from @graemeniedermayer, hidden, for api use only, will remove in future
# take gradients
zx = cv2.Sobel(np.float64(img_output), cv2.CV_64F, 1, 0, ksize=3)
zy = cv2.Sobel(np.float64(img_output), cv2.CV_64F, 0, 1, ksize=3)
# combine and normalize gradients.
normal = np.dstack((zx, -zy, np.ones_like(img_output)))
n = np.linalg.norm(normal, axis=2)
normal[:, :, 0] /= n
normal[:, :, 1] /= n
normal[:, :, 2] /= n
# offset and rescale values to be in 0-255
normal += 1
normal /= 2
normal *= 255
normal = normal.astype(np.uint8)
outimages.append(Image.fromarray(normal))
print("Done.")
except RuntimeError as e:
if 'out of memory' in str(e):
print("ERROR: out of memory, could not generate depthmap !")
else:
print(e)
finally:
if 'model' in locals():
del model
if boost and 'pix2pixmodel' in locals():
del pix2pixmodel
gc.collect()
devices.torch_gc()
# reload sd model
shared.sd_model.cond_stage_model.to(devices.device)
shared.sd_model.first_stage_model.to(devices.device)
mesh_fi = ''
try:
if inpaint:
# unload sd model
shared.sd_model.cond_stage_model.to(devices.cpu)
shared.sd_model.first_stage_model.to(devices.cpu)
mesh_fi = run_3dphoto(device, inpaint_imgs, inpaint_depths, inputnames, outpath, fnExt, vid_ssaa, inpaint_vids)
finally:
# reload sd model
shared.sd_model.cond_stage_model.to(devices.device)
shared.sd_model.first_stage_model.to(devices.device)
print("All done.")
return outimages, mesh_fi
@njit(parallel=True)
def clipdepthmap(img, clipthreshold_far, clipthreshold_near):
clipped_img = img #copy.deepcopy(img)
w, h = img.shape
min = img.min()
max = img.max()
drange = max - min
clipthreshold_far = min + (clipthreshold_far * drange)
clipthreshold_near = min + (clipthreshold_near * drange)
for x in prange(w):
for y in range(h):
if clipped_img[x,y] < clipthreshold_far:
clipped_img[x,y] = 0
elif clipped_img[x,y] > clipthreshold_near:
clipped_img[x,y] = 65535
else:
clipped_img[x,y] = ((clipped_img[x,y] + min) / drange * 65535)
return clipped_img
def run_3dphoto(device, img_rgb, img_depth, inputnames, outpath, fnExt, vid_ssaa, inpaint_vids):
try:
print("Running 3D Photo Inpainting .. ")
edgemodel_path = './models/3dphoto/edge_model.pth'
depthmodel_path = './models/3dphoto/depth_model.pth'
colormodel_path = './models/3dphoto/color_model.pth'
# create paths to model if not present
os.makedirs('./models/3dphoto/', exist_ok=True)
if not os.path.exists(edgemodel_path):
download_file(edgemodel_path,"https://filebox.ece.vt.edu/~jbhuang/project/3DPhoto/model/edge-model.pth")
if not os.path.exists(depthmodel_path):
download_file(depthmodel_path,"https://filebox.ece.vt.edu/~jbhuang/project/3DPhoto/model/depth-model.pth")
if not os.path.exists(colormodel_path):
download_file(colormodel_path,"https://filebox.ece.vt.edu/~jbhuang/project/3DPhoto/model/color-model.pth")
print("Loading edge model ..")
depth_edge_model = Inpaint_Edge_Net(init_weights=True)
depth_edge_weight = torch.load(edgemodel_path, map_location=torch.device(device))
depth_edge_model.load_state_dict(depth_edge_weight)
depth_edge_model = depth_edge_model.to(device)
depth_edge_model.eval()
print("Loading depth model ..")
depth_feat_model = Inpaint_Depth_Net()
depth_feat_weight = torch.load(depthmodel_path, map_location=torch.device(device))
depth_feat_model.load_state_dict(depth_feat_weight, strict=True)
depth_feat_model = depth_feat_model.to(device)
depth_feat_model.eval()
depth_feat_model = depth_feat_model.to(device)
print("Loading rgb model ..")
rgb_model = Inpaint_Color_Net()
rgb_feat_weight = torch.load(colormodel_path, map_location=torch.device(device))
rgb_model.load_state_dict(rgb_feat_weight)
rgb_model.eval()
rgb_model = rgb_model.to(device)
config = {}
config["gpu_ids"] = 0
config['extrapolation_thickness'] = 60
config['extrapolate_border'] = True
config['depth_threshold'] = 0.04
config['redundant_number'] = 12
config['ext_edge_threshold'] = 0.002
config['background_thickness'] = 70
config['context_thickness'] = 140
config['background_thickness_2'] = 70
config['context_thickness_2'] = 70
config['log_depth'] = True
config['depth_edge_dilate'] = 10
config['depth_edge_dilate_2'] = 5
config['largest_size'] = 512
config['repeat_inpaint_edge'] = True
config['save_ply'] = True
config['ply_fmt'] = "bin"
if device == torch.device("cpu"):
config["gpu_ids"] = -1
# process all inputs
numimages = len(img_rgb)
for count in trange(0, numimages):
basename = 'depthmap'
if inputnames is not None:
if inputnames[count] is not None:
p = Path(inputnames[count])
basename = p.stem
# unique filename
basecount = get_next_sequence_number(outpath, basename)
if basecount > 0: basecount = basecount - 1
fullfn = None
for i in range(500):
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
fullfn = os.path.join(outpath, f"{fn}.ply")
if not os.path.exists(fullfn):
break
basename = Path(fullfn).stem
# mesh filename
mesh_fi = os.path.join(outpath, basename +'.ply')
print(f"\nGenerating inpainted mesh .. (go make some coffee) ..")
# from inpaint.utils.get_MiDaS_samples
W = img_rgb[count].width
H = img_rgb[count].height
int_mtx = np.array([[max(H, W), 0, W//2], [0, max(H, W), H//2], [0, 0, 1]]).astype(np.float32)
if int_mtx.max() > 1:
int_mtx[0, :] = int_mtx[0, :] / float(W)
int_mtx[1, :] = int_mtx[1, :] / float(H)
# how inpaint.utils.read_MiDaS_depth() imports depthmap
disp = img_depth[count].astype(np.float32)
disp = disp - disp.min()
disp = cv2.blur(disp / disp.max(), ksize=(3, 3)) * disp.max()
disp = (disp / disp.max()) * 3.0
depth = 1. / np.maximum(disp, 0.05)
# rgb input
img = np.asarray(img_rgb[count])
# run sparse bilateral filter
config['sparse_iter'] = 5
config['filter_size'] = [7, 7, 5, 5, 5]
config['sigma_s'] = 4.0
config['sigma_r'] = 0.5
vis_photos, vis_depths = sparse_bilateral_filtering(depth.copy(), img.copy(), config, num_iter=config['sparse_iter'], spdb=False)
depth = vis_depths[-1]
#bilat_fn = os.path.join(outpath, basename +'_bilatdepth.png')
#cv2.imwrite(bilat_fn, depth)
rt_info = write_ply(img,
depth,
int_mtx,
mesh_fi,
config,
rgb_model,
depth_edge_model,
depth_edge_model,
depth_feat_model)
if rt_info is not False and inpaint_vids:
run_3dphoto_videos(mesh_fi, basename, outpath, 300, 40,
[0.03, 0.03, 0.05, 0.03],
['double-straight-line', 'double-straight-line', 'circle', 'circle'],
[0.00, 0.00, -0.015, -0.015],
[0.00, 0.00, -0.015, -0.00],
[-0.05, -0.05, -0.05, -0.05],
['dolly-zoom-in', 'zoom-in', 'circle', 'swing'], False, fnExt, vid_ssaa)
finally:
del rgb_model
rgb_model = None
del depth_edge_model
depth_edge_model = None
del depth_feat_model
depth_feat_model = None
devices.torch_gc()
return mesh_fi
def run_3dphoto_videos(mesh_fi, basename, outpath, num_frames, fps, crop_border, traj_types, x_shift_range, y_shift_range, z_shift_range, video_postfix, vid_dolly, fnExt, vid_ssaa):
if platform.system() == 'Windows':
vispy.use(app='PyQt5')
elif platform.system() == 'Darwin':
vispy.use('PyQt6')
else:
vispy.use(app='egl')
# read ply
verts, colors, faces, Height, Width, hFov, vFov, mean_loc_depth = read_ply(mesh_fi)
original_w = output_w = W = Width
original_h = output_h = H = Height
int_mtx = np.array([[max(H, W), 0, W//2], [0, max(H, W), H//2], [0, 0, 1]]).astype(np.float32)
if int_mtx.max() > 1:
int_mtx[0, :] = int_mtx[0, :] / float(W)
int_mtx[1, :] = int_mtx[1, :] / float(H)
config = {}
config['video_folder'] = outpath
config['num_frames'] = num_frames
config['fps'] = fps
config['crop_border'] = crop_border
config['traj_types'] = traj_types
config['x_shift_range'] = x_shift_range
config['y_shift_range'] = y_shift_range
config['z_shift_range'] = z_shift_range
config['video_postfix'] = video_postfix
config['ssaa'] = vid_ssaa
# from inpaint.utils.get_MiDaS_samples
generic_pose = np.eye(4)
assert len(config['traj_types']) == len(config['x_shift_range']) ==\
len(config['y_shift_range']) == len(config['z_shift_range']) == len(config['video_postfix']), \
"The number of elements in 'traj_types', 'x_shift_range', 'y_shift_range', 'z_shift_range' and \
'video_postfix' should be equal."
tgt_pose = [[generic_pose * 1]]
tgts_poses = []
for traj_idx in range(len(config['traj_types'])):
tgt_poses = []
sx, sy, sz = path_planning(config['num_frames'], config['x_shift_range'][traj_idx], config['y_shift_range'][traj_idx],
config['z_shift_range'][traj_idx], path_type=config['traj_types'][traj_idx])
for xx, yy, zz in zip(sx, sy, sz):
tgt_poses.append(generic_pose * 1.)
tgt_poses[-1][:3, -1] = np.array([xx, yy, zz])
tgts_poses += [tgt_poses]
tgt_pose = generic_pose * 1
# seems we only need the depthmap to calc mean_loc_depth, which is only used when doing 'dolly'
# width and height are already in the ply file in the comments ..
# might try to add the mean_loc_depth to it too
# did just that
#mean_loc_depth = img_depth[img_depth.shape[0]//2, img_depth.shape[1]//2]
print("Generating videos ..")
normal_canvas, all_canvas = None, None
videos_poses, video_basename = copy.deepcopy(tgts_poses), basename
top = (original_h // 2 - int_mtx[1, 2] * output_h)
left = (original_w // 2 - int_mtx[0, 2] * output_w)
down, right = top + output_h, left + output_w
border = [int(xx) for xx in [top, down, left, right]]
normal_canvas, all_canvas, fn_saved = output_3d_photo(verts.copy(), colors.copy(), faces.copy(), copy.deepcopy(Height), copy.deepcopy(Width), copy.deepcopy(hFov), copy.deepcopy(vFov),
copy.deepcopy(tgt_pose), config['video_postfix'], copy.deepcopy(generic_pose), copy.deepcopy(config['video_folder']),
None, copy.deepcopy(int_mtx), config, None,
videos_poses, video_basename, original_h, original_w, border=border, depth=None, normal_canvas=normal_canvas, all_canvas=all_canvas,
mean_loc_depth=mean_loc_depth, dolly=vid_dolly, fnExt=fnExt)
return fn_saved
# called from gen vid tab button
def run_makevideo(fn_mesh, vid_numframes, vid_fps, vid_traj, vid_shift, vid_border, dolly, vid_format, vid_ssaa):
if len(fn_mesh) == 0 or not os.path.exists(fn_mesh):
raise Exception("Could not open mesh.")
# file type
fnExt = "mp4" if vid_format == 0 else "webm"
vid_ssaa = vid_ssaa + 1
# traj type
if vid_traj == 0:
vid_traj = ['straight-line']
elif vid_traj == 1:
vid_traj = ['double-straight-line']
elif vid_traj == 2:
vid_traj = ['circle']
num_fps = int(vid_fps)
num_frames = int(vid_numframes)
shifts = vid_shift.split(',')
if len(shifts) != 3:
raise Exception("Translate requires 3 elements.")
x_shift_range = [ float(shifts[0]) ]
y_shift_range = [ float(shifts[1]) ]
z_shift_range = [ float(shifts[2]) ]
borders = vid_border.split(',')
if len(borders) != 4:
raise Exception("Crop Border requires 4 elements.")
crop_border = [float(borders[0]), float(borders[1]), float(borders[2]), float(borders[3])]
# output path and filename mess ..
basename = Path(fn_mesh).stem
outpath = opts.outdir_samples or opts.outdir_extras_samples
# unique filename
basecount = get_next_sequence_number(outpath, basename)
if basecount > 0: basecount = basecount - 1
fullfn = None
for i in range(500):
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
fullfn = os.path.join(outpath, f"{fn}_." + fnExt)
if not os.path.exists(fullfn):
break
basename = Path(fullfn).stem
basename = basename[:-1]
print("Loading mesh ..")
fn_saved = run_3dphoto_videos(fn_mesh, basename, outpath, num_frames, num_fps, crop_border, vid_traj, x_shift_range, y_shift_range, z_shift_range, [''], dolly, fnExt, vid_ssaa)
return fn_saved[-1], fn_saved[-1], ''
def apply_stereo_divergence(original_image, depth, divergence, fill_technique):
depth_min = depth.min()
depth_max = depth.max()
depth = (depth - depth_min) / (depth_max - depth_min)
divergence_px = (divergence / 100.0) * original_image.shape[1]
if fill_technique in [0, 1, 2]:
return apply_stereo_divergence_naive(original_image, depth, divergence_px, fill_technique)
if fill_technique in [3, 4]:
return apply_stereo_divergence_polylines(original_image, depth, divergence_px, fill_technique)
@njit
def apply_stereo_divergence_naive(original_image, normalized_depth, divergence_px: float, fill_technique):
h, w, c = original_image.shape
derived_image = np.zeros_like(original_image)
filled = np.zeros(h * w, dtype=np.uint8)
for row in prange(h):
# Swipe order should ensure that pixels that are closer overwrite
# (at their destination) pixels that are less close
for col in range(w) if divergence_px < 0 else range(w - 1, -1, -1):
col_d = col + int((1 - normalized_depth[row][col] ** 2) * divergence_px)
if 0 <= col_d < w:
derived_image[row][col_d] = original_image[row][col]
filled[row * w + col_d] = 1
# Fill the gaps
if fill_technique == 2: # naive_interpolating
for row in range(h):
for l_pointer in range(w):
# This if (and the next if) performs two checks that are almost the same - for performance reasons
if sum(derived_image[row][l_pointer]) != 0 or filled[row * w + l_pointer]:
continue
l_border = derived_image[row][l_pointer - 1] if l_pointer > 0 else np.zeros(3, dtype=np.uint8)
r_border = np.zeros(3, dtype=np.uint8)
r_pointer = l_pointer + 1
while r_pointer < w:
if sum(derived_image[row][r_pointer]) != 0 and filled[row * w + r_pointer]:
r_border = derived_image[row][r_pointer]
break
r_pointer += 1
if sum(l_border) == 0:
l_border = r_border
elif sum(r_border) == 0:
r_border = l_border
# Example illustrating positions of pointers at this point in code:
# is filled? : + - - - - +
# pointers : l r
# interpolated: 0 1 2 3 4 5
# In total: 5 steps between two filled pixels
total_steps = 1 + r_pointer - l_pointer
step = (r_border.astype(np.float_) - l_border) / total_steps
for col in range(l_pointer, r_pointer):
derived_image[row][col] = l_border + (step * (col - l_pointer + 1)).astype(np.uint8)
return derived_image
elif fill_technique == 1: # naive
derived_fix = np.copy(derived_image)
for pos in np.where(filled == 0)[0]:
row = pos // w
col = pos % w
row_times_w = row * w
for offset in range(1, abs(int(divergence_px)) + 2):
r_offset = col + offset
l_offset = col - offset
if r_offset < w and filled[row_times_w + r_offset]:
derived_fix[row][col] = derived_image[row][r_offset]
break
if 0 <= l_offset and filled[row_times_w + l_offset]:
derived_fix[row][col] = derived_image[row][l_offset]
break
return derived_fix
else: # none
return derived_image
@njit(parallel=True) # fastmath=True does not reasonably improve performance
def apply_stereo_divergence_polylines(original_image, normalized_depth, divergence_px: float, fill_technique):
# This code treats rows of the image as polylines
# It generates polylines, morphs them (applies divergence) to them, and then rasterizes them
EPSILON = 1e-7
PIXEL_HALF_WIDTH = 0.45 if fill_technique == 4 else 0.0
# PERF_COUNTERS = [0, 0, 0]
h, w, c = original_image.shape
derived_image = np.zeros_like(original_image)
for row in prange(h):
# generating the vertices of the morphed polyline
# format: new coordinate of the vertex, divergence (closeness), column of pixel that contains the point's color
pt = np.zeros((5 + 2 * w, 3), dtype=np.float_)
pt_end: int = 0
pt[pt_end] = [-3.0 * abs(divergence_px), 0.0, 0.0]
pt_end += 1
for col in range(0, w):
coord_d = (1 - normalized_depth[row][col] ** 2) * divergence_px
coord_x = col + 0.5 + coord_d
if PIXEL_HALF_WIDTH < EPSILON:
pt[pt_end] = [coord_x, abs(coord_d), col]
pt_end += 1
else:
pt[pt_end] = [coord_x - PIXEL_HALF_WIDTH, abs(coord_d), col]
pt[pt_end + 1] = [coord_x + PIXEL_HALF_WIDTH, abs(coord_d), col]
pt_end += 2
pt[pt_end] = [w + 3.0 * abs(divergence_px), 0.0, w - 1]
pt_end += 1
# generating the segments of the morphed polyline
# format: coord_x, coord_d, color_i of the first point, then the same for the second point
sg_end: int = pt_end - 1
sg = np.zeros((sg_end, 6), dtype=np.float_)
for i in range(sg_end):
sg[i] += np.concatenate((pt[i], pt[i + 1]))
# Here is an informal proof that this (morphed) polyline does not self-intersect:
# Draw a plot with two axes: coord_x and coord_d. Now draw the original line - it will be positioned at the
# bottom of the graph (that is, for every point coord_d == 0). Now draw the morphed line using the vertices of
# the original polyline. Observe that for each vertex in the new polyline, its increments
# (from the corresponding vertex in the old polyline) over coord_x and coord_d are in direct proportion.
# In fact, this proportion is equal for all the vertices and it is equal either -1 or +1,
# depending on the sign of divergence_px. Now draw the lines from each old vertex to a corresponding new vertex.
# Since the proportions are equal, these lines have the same angle with an axe and are parallel.
# So, these lines do not intersect. Now rotate the plot by 45 or -45 degrees and observe that
# each dot of the polyline is further right from the last dot,
# which makes it impossible for the polyline to self-interset. QED.
# sort segments and points using insertion sort
# has a very good performance in practice, since these are almost sorted to begin with
for i in range(1, sg_end):
u = i - 1
while pt[u][0] > pt[u + 1][0] and 0 <= u:
pt[u], pt[u + 1] = np.copy(pt[u + 1]), np.copy(pt[u])
sg[u], sg[u + 1] = np.copy(sg[u + 1]), np.copy(sg[u])
u -= 1
# rasterizing
# at each point in time we keep track of segments that are "active" (or "current")
csg = np.zeros((5 * int(abs(divergence_px)) + 25, 6), dtype=np.float_)
csg_end: int = 0
sg_pointer: int = 0