Bobby commited on
Commit
b85b7f4
·
1 Parent(s): cbe7281

inpainting test

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .aidigestignore +10 -0
  2. app.py +64 -3
  3. codebase.md +843 -0
  4. controlnet_aux_local/canny/__init__.py +0 -36
  5. controlnet_aux_local/dwpose/__init__.py +0 -91
  6. controlnet_aux_local/dwpose/util.py +0 -303
  7. controlnet_aux_local/dwpose/wholebody.py +0 -121
  8. controlnet_aux_local/hed/__init__.py +0 -129
  9. controlnet_aux_local/leres/__init__.py +0 -118
  10. controlnet_aux_local/leres/leres/Resnet.py +0 -199
  11. controlnet_aux_local/leres/leres/Resnext_torch.py +0 -237
  12. controlnet_aux_local/leres/leres/__init__.py +0 -0
  13. controlnet_aux_local/leres/leres/depthmap.py +0 -548
  14. controlnet_aux_local/leres/leres/multi_depth_model_woauxi.py +0 -35
  15. controlnet_aux_local/leres/leres/net_tools.py +0 -54
  16. controlnet_aux_local/leres/leres/network_auxi.py +0 -417
  17. controlnet_aux_local/leres/pix2pix/__init__.py +0 -0
  18. controlnet_aux_local/leres/pix2pix/models/__init__.py +0 -67
  19. controlnet_aux_local/leres/pix2pix/models/base_model.py +0 -244
  20. controlnet_aux_local/leres/pix2pix/models/base_model_hg.py +0 -58
  21. controlnet_aux_local/leres/pix2pix/models/networks.py +0 -623
  22. controlnet_aux_local/leres/pix2pix/models/pix2pix4depth_model.py +0 -155
  23. controlnet_aux_local/leres/pix2pix/options/__init__.py +0 -1
  24. controlnet_aux_local/leres/pix2pix/options/base_options.py +0 -156
  25. controlnet_aux_local/leres/pix2pix/options/test_options.py +0 -22
  26. controlnet_aux_local/leres/pix2pix/util/__init__.py +0 -1
  27. controlnet_aux_local/leres/pix2pix/util/util.py +0 -105
  28. controlnet_aux_local/lineart/__init__.py +0 -167
  29. controlnet_aux_local/lineart_anime/__init__.py +0 -189
  30. controlnet_aux_local/mediapipe_face/__init__.py +0 -53
  31. controlnet_aux_local/mediapipe_face/mediapipe_face_common.py +0 -164
  32. controlnet_aux_local/midas/__init__.py +0 -95
  33. controlnet_aux_local/midas/api.py +0 -169
  34. controlnet_aux_local/midas/midas/__init__.py +0 -0
  35. controlnet_aux_local/midas/midas/base_model.py +0 -16
  36. controlnet_aux_local/midas/midas/blocks.py +0 -342
  37. controlnet_aux_local/midas/midas/dpt_depth.py +0 -109
  38. controlnet_aux_local/midas/midas/midas_net.py +0 -76
  39. controlnet_aux_local/midas/midas/midas_net_custom.py +0 -128
  40. controlnet_aux_local/midas/midas/transforms.py +0 -234
  41. controlnet_aux_local/midas/midas/vit.py +0 -491
  42. controlnet_aux_local/midas/utils.py +0 -189
  43. controlnet_aux_local/mlsd/__init__.py +0 -79
  44. controlnet_aux_local/mlsd/models/__init__.py +0 -0
  45. controlnet_aux_local/mlsd/models/mbv2_mlsd_large.py +0 -292
  46. controlnet_aux_local/mlsd/models/mbv2_mlsd_tiny.py +0 -275
  47. controlnet_aux_local/mlsd/utils.py +0 -584
  48. controlnet_aux_local/open_pose/__init__.py +0 -234
  49. controlnet_aux_local/open_pose/body.py +0 -260
  50. controlnet_aux_local/open_pose/face.py +0 -364
.aidigestignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ controlnet_aux_local/normalbae/*
2
+ requirements.txt
3
+ win.requirements.txt
4
+ web.html
5
+ client.py
6
+ local_app.py
7
+ README.md
8
+ Dockerfile
9
+ .gitignore
10
+ .gitattributes
app.py CHANGED
@@ -15,11 +15,13 @@ import imageio
15
  from huggingface_hub import HfApi
16
  import gc
17
  import torch
 
18
  from PIL import Image
19
  from diffusers import (
20
  ControlNetModel,
21
  DPMSolverMultistepScheduler,
22
  StableDiffusionControlNetPipeline,
 
23
  # AutoencoderKL,
24
  )
25
  from controlnet_aux_local import NormalBaeDetector
@@ -98,6 +100,19 @@ if gr.NO_RELOAD:
98
  # vae=vae,
99
  torch_dtype=torch.float16,
100
  ).to("cuda")
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  print("loading preprocessor")
103
  preprocessor = Preprocessor()
@@ -119,6 +134,21 @@ if gr.NO_RELOAD:
119
  gc.collect()
120
  print(f"CUDA memory allocated: {torch.cuda.max_memory_allocated(device='cuda') / 1e9:.2f} GB")
121
  print("Model Compiled!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
124
  if randomize_seed:
@@ -422,15 +452,46 @@ def process_image(
422
  print(prompt)
423
  print(f"\n-------------------------Preprocess done in: {preprocess_time:.2f} seconds-------------------------")
424
  start = time.time()
425
- results = pipe(
 
 
 
 
 
 
 
 
 
 
426
  prompt=prompt,
427
  negative_prompt=negative_prompt,
428
  guidance_scale=guidance_scale,
429
- num_images_per_prompt=num_images,
430
  num_inference_steps=num_steps,
431
  generator=generator,
432
  image=control_image,
433
  ).images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  print(f"\n-------------------------Inference done in: {time.time() - start:.2f} seconds-------------------------")
435
  torch.cuda.empty_cache()
436
 
@@ -456,7 +517,7 @@ def process_image(
456
  token=API_KEY,
457
  run_as_future=True,
458
  )
459
- return results
460
 
461
  if prod:
462
  demo.queue(max_size=20).launch(server_name="localhost", server_port=port)
 
15
  from huggingface_hub import HfApi
16
  import gc
17
  import torch
18
+ import cv2
19
  from PIL import Image
20
  from diffusers import (
21
  ControlNetModel,
22
  DPMSolverMultistepScheduler,
23
  StableDiffusionControlNetPipeline,
24
+ StableDiffusionInpaintPipeline,
25
  # AutoencoderKL,
26
  )
27
  from controlnet_aux_local import NormalBaeDetector
 
100
  # vae=vae,
101
  torch_dtype=torch.float16,
102
  ).to("cuda")
103
+
104
+ print('loading inpainting pipe')
105
+ inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
106
+ "runwayml/stable-diffusion-inpainting",
107
+ torch_dtype=torch.float16,
108
+ ).to("cuda")
109
+
110
+ print('loading controlnet inpainting pipe')
111
+ controlnet_inpaint_pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
112
+ "runwayml/stable-diffusion-inpainting",
113
+ controlnet=controlnet,
114
+ torch_dtype=torch.float16,
115
+ ).to("cuda")
116
 
117
  print("loading preprocessor")
118
  preprocessor = Preprocessor()
 
134
  gc.collect()
135
  print(f"CUDA memory allocated: {torch.cuda.max_memory_allocated(device='cuda') / 1e9:.2f} GB")
136
  print("Model Compiled!")
137
+
138
+ def generate_furniture_mask(image, furniture_type):
139
+ image_np = np.array(image)
140
+ height, width = image_np.shape[:2]
141
+
142
+ mask = np.zeros((height, width), dtype=np.uint8)
143
+
144
+ if furniture_type == "sofa":
145
+ cv2.rectangle(mask, (width//4, int(height*0.6)), (width*3//4, height), 255, -1)
146
+ elif furniture_type == "table":
147
+ cv2.rectangle(mask, (width//3, height//3), (width*2//3, height*2//3), 255, -1)
148
+ elif furniture_type == "chair":
149
+ cv2.circle(mask, (width*3//5, height*2//3), height//6, 255, -1)
150
+
151
+ return Image.fromarray(mask)
152
 
153
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
154
  if randomize_seed:
 
452
  print(prompt)
453
  print(f"\n-------------------------Preprocess done in: {preprocess_time:.2f} seconds-------------------------")
454
  start = time.time()
455
+ # results = pipe(
456
+ # prompt=prompt,
457
+ # negative_prompt=negative_prompt,
458
+ # guidance_scale=guidance_scale,
459
+ # num_images_per_prompt=num_images,
460
+ # num_inference_steps=num_steps,
461
+ # generator=generator,
462
+ # image=control_image,
463
+ # ).images[0]
464
+
465
+ initial_result = pipe(
466
  prompt=prompt,
467
  negative_prompt=negative_prompt,
468
  guidance_scale=guidance_scale,
469
+ num_images_per_prompt=1,
470
  num_inference_steps=num_steps,
471
  generator=generator,
472
  image=control_image,
473
  ).images[0]
474
+
475
+ # Randomly choose whether to add furniture and which type
476
+ furniture_types = ["None", "sofa", "table", "chair"]
477
+ furniture_type = random.choice(furniture_types)
478
+
479
+ if furniture_type != "None":
480
+ furniture_mask = generate_furniture_mask(initial_result, furniture_type)
481
+ furniture_prompt = f"A {furniture_type} in the style of {style_selection}"
482
+ inpainted_image = controlnet_inpaint_pipe(
483
+ prompt=furniture_prompt,
484
+ image=initial_result,
485
+ mask_image=furniture_mask,
486
+ control_image=control_image,
487
+ negative_prompt=negative_prompt,
488
+ num_inference_steps=num_steps,
489
+ guidance_scale=guidance_scale,
490
+ generator=generator,
491
+ ).images[0]
492
+ else:
493
+ inpainted_image = initial_result
494
+
495
  print(f"\n-------------------------Inference done in: {time.time() - start:.2f} seconds-------------------------")
496
  torch.cuda.empty_cache()
497
 
 
517
  token=API_KEY,
518
  run_as_future=True,
519
  )
520
+ return inpainted_image
521
 
522
  if prod:
523
  demo.queue(max_size=20).launch(server_name="localhost", server_port=port)
codebase.md ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # preprocess.py
2
+
3
+ ```py
4
+ import PIL.Image
5
+ import torch, gc
6
+ from controlnet_aux_local import NormalBaeDetector#, CannyDetector
7
+
8
+ class Preprocessor:
9
+ MODEL_ID = "lllyasviel/Annotators"
10
+
11
+ def __init__(self):
12
+ self.model = None
13
+ self.name = ""
14
+
15
+ def load(self, name: str) -> None:
16
+ if name == self.name:
17
+ return
18
+ elif name == "NormalBae":
19
+ print("Loading NormalBae")
20
+ self.model = NormalBaeDetector.from_pretrained(self.MODEL_ID).to("cuda")
21
+ torch.cuda.empty_cache()
22
+ self.name = name
23
+ else:
24
+ raise ValueError
25
+ return
26
+
27
+ def __call__(self, image: PIL.Image.Image, **kwargs) -> PIL.Image.Image:
28
+ return self.model(image, **kwargs)
29
+ ```
30
+
31
+ # app.py
32
+
33
+ ```py
34
+ prod = False
35
+ port = 8080
36
+ show_options = False
37
+ if prod:
38
+ port = 8081
39
+ # show_options = False
40
+
41
+ import os
42
+ import random
43
+ import time
44
+ import gradio as gr
45
+ import numpy as np
46
+ import spaces
47
+ import imageio
48
+ from huggingface_hub import HfApi
49
+ import gc
50
+ import torch
51
+ from PIL import Image
52
+ from diffusers import (
53
+ ControlNetModel,
54
+ DPMSolverMultistepScheduler,
55
+ StableDiffusionControlNetPipeline,
56
+ # AutoencoderKL,
57
+ )
58
+ from controlnet_aux_local import NormalBaeDetector
59
+
60
+ MAX_SEED = np.iinfo(np.int32).max
61
+ API_KEY = os.environ.get("API_KEY", None)
62
+ # os.environ['HF_HOME'] = '/data/.huggingface'
63
+
64
+ print("CUDA version:", torch.version.cuda)
65
+ print("loading everything")
66
+ compiled = False
67
+ api = HfApi()
68
+
69
+ class Preprocessor:
70
+ MODEL_ID = "lllyasviel/Annotators"
71
+
72
+ def __init__(self):
73
+ self.model = None
74
+ self.name = ""
75
+
76
+ def load(self, name: str) -> None:
77
+ if name == self.name:
78
+ return
79
+ elif name == "NormalBae":
80
+ print("Loading NormalBae")
81
+ self.model = NormalBaeDetector.from_pretrained(self.MODEL_ID).to("cuda")
82
+ torch.cuda.empty_cache()
83
+ self.name = name
84
+ else:
85
+ raise ValueError
86
+ return
87
+
88
+ def __call__(self, image: Image.Image, **kwargs) -> Image.Image:
89
+ return self.model(image, **kwargs)
90
+
91
+ if gr.NO_RELOAD:
92
+ # Controlnet Normal
93
+ model_id = "lllyasviel/control_v11p_sd15_normalbae"
94
+ print("initializing controlnet")
95
+ controlnet = ControlNetModel.from_pretrained(
96
+ model_id,
97
+ torch_dtype=torch.float16,
98
+ attn_implementation="flash_attention_2",
99
+ ).to("cuda")
100
+
101
+ # Scheduler
102
+ scheduler = DPMSolverMultistepScheduler.from_pretrained(
103
+ "runwayml/stable-diffusion-v1-5",
104
+ solver_order=2,
105
+ subfolder="scheduler",
106
+ use_karras_sigmas=True,
107
+ final_sigmas_type="sigma_min",
108
+ algorithm_type="sde-dpmsolver++",
109
+ prediction_type="epsilon",
110
+ thresholding=False,
111
+ denoise_final=True,
112
+ device_map="cuda",
113
+ torch_dtype=torch.float16,
114
+ )
115
+
116
+ # Stable Diffusion Pipeline URL
117
+ # base_model_url = "https://huggingface.co/broyang/hentaidigitalart_v20/blob/main/realcartoon3d_v15.safetensors"
118
+ base_model_url = "https://huggingface.co/Lykon/AbsoluteReality/blob/main/AbsoluteReality_1.8.1_pruned.safetensors"
119
+ # vae_url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors"
120
+
121
+ # print('loading vae')
122
+ # vae = AutoencoderKL.from_single_file(vae_url, torch_dtype=torch.float16).to("cuda")
123
+ # vae.to(memory_format=torch.channels_last)
124
+
125
+ print('loading pipe')
126
+ pipe = StableDiffusionControlNetPipeline.from_single_file(
127
+ base_model_url,
128
+ safety_checker=None,
129
+ controlnet=controlnet,
130
+ scheduler=scheduler,
131
+ # vae=vae,
132
+ torch_dtype=torch.float16,
133
+ ).to("cuda")
134
+
135
+ print("loading preprocessor")
136
+ preprocessor = Preprocessor()
137
+ preprocessor.load("NormalBae")
138
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="EasyNegativeV2.safetensors", token="EasyNegativeV2",)
139
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="badhandv4.pt", token="badhandv4")
140
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="fcNeg-neg.pt", token="fcNeg-neg")
141
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_Ahegao.pt", token="HDA_Ahegao")
142
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_Bondage.pt", token="HDA_Bondage")
143
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_pet_play.pt", token="HDA_pet_play")
144
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_unconventional maid.pt", token="HDA_unconventional_maid")
145
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_NakedHoodie.pt", token="HDA_NakedHoodie")
146
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_NunDress.pt", token="HDA_NunDress")
147
+ # pipe.load_textual_inversion("broyang/hentaidigitalart_v20", weight_name="HDA_Shibari.pt", token="HDA_Shibari")
148
+ pipe.to("cuda")
149
+
150
+ print("---------------Loaded controlnet pipeline---------------")
151
+ torch.cuda.empty_cache()
152
+ gc.collect()
153
+ print(f"CUDA memory allocated: {torch.cuda.max_memory_allocated(device='cuda') / 1e9:.2f} GB")
154
+ print("Model Compiled!")
155
+
156
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
157
+ if randomize_seed:
158
+ seed = random.randint(0, MAX_SEED)
159
+ return seed
160
+
161
+ def get_additional_prompt():
162
+ prompt = "hyperrealistic photography,extremely detailed,(intricate details),unity 8k wallpaper,ultra detailed"
163
+ top = ["tank top", "blouse", "button up shirt", "sweater", "corset top"]
164
+ bottom = ["short skirt", "athletic shorts", "jean shorts", "pleated skirt", "short skirt", "leggings", "high-waisted shorts"]
165
+ accessory = ["knee-high boots", "gloves", "Thigh-high stockings", "Garter belt", "choker", "necklace", "headband", "headphones"]
166
+ return f"{prompt}, {random.choice(top)}, {random.choice(bottom)}, {random.choice(accessory)}, score_9"
167
+ # outfit = ["schoolgirl outfit", "playboy outfit", "red dress", "gala dress", "cheerleader outfit", "nurse outfit", "Kimono"]
168
+
169
+ def get_prompt(prompt, additional_prompt):
170
+ interior = "design-style interior designed (interior space),tungsten white balance,captured with a DSLR camera using f/10 aperture, 1/60 sec shutter speed, ISO 400, 20mm focal length"
171
+ default = "hyperrealistic photography,extremely detailed,(intricate details),unity 8k wallpaper,ultra detailed"
172
+ default2 = f"professional 3d model {prompt},octane render,highly detailed,volumetric,dramatic lighting,hyperrealistic photography,extremely detailed,(intricate details),unity 8k wallpaper,ultra detailed"
173
+ randomize = get_additional_prompt()
174
+ # nude = "NSFW,((nude)),medium bare breasts,hyperrealistic photography,extremely detailed,(intricate details),unity 8k wallpaper,ultra detailed"
175
+ # bodypaint = "((fully naked with no clothes)),nude naked seethroughxray,invisiblebodypaint,rating_newd,NSFW"
176
+ lab_girl = "hyperrealistic photography, extremely detailed, shy assistant wearing minidress boots and gloves, laboratory background, score_9, 1girl"
177
+ pet_play = "hyperrealistic photography, extremely detailed, playful, blush, glasses, collar, score_9, HDA_pet_play"
178
+ bondage = "hyperrealistic photography, extremely detailed, submissive, glasses, score_9, HDA_Bondage"
179
+ # ahegao = "((invisible clothing)), hyperrealistic photography,exposed vagina,sexy,nsfw,HDA_Ahegao"
180
+ ahegao2 = "(invisiblebodypaint),rating_newd,HDA_Ahegao"
181
+ athleisure = "hyperrealistic photography, extremely detailed, 1girl athlete, exhausted embarrassed sweaty,outdoors, ((athleisure clothing)), score_9"
182
+ atompunk = "((atompunk world)), hyperrealistic photography, extremely detailed, short hair, bodysuit, glasses, neon cyberpunk background, score_9"
183
+ maid = "hyperrealistic photography, extremely detailed, shy, blushing, score_9, pastel background, HDA_unconventional_maid"
184
+ nundress = "hyperrealistic photography, extremely detailed, shy, blushing, fantasy background, score_9, HDA_NunDress"
185
+ naked_hoodie = "hyperrealistic photography, extremely detailed, medium hair, cityscape, (neon lights), score_9, HDA_NakedHoodie"
186
+ abg = "(1girl, asian body covered in words, words on body, tattoos of (words) on body),(masterpiece, best quality),medium breasts,(intricate details),unity 8k wallpaper,ultra detailed,(pastel colors),beautiful and aesthetic,see-through (clothes),detailed,solo"
187
+ # shibari = "extremely detailed, hyperrealistic photography, earrings, blushing, lace choker, tattoo, medium hair, score_9, HDA_Shibari"
188
+ shibari2 = "octane render, highly detailed, volumetric, HDA_Shibari"
189
+
190
+ if prompt == "":
191
+ girls = [randomize, pet_play, bondage, lab_girl, athleisure, atompunk, maid, nundress, naked_hoodie, abg, shibari2, ahegao2]
192
+ prompts_nsfw = [abg, shibari2, ahegao2]
193
+ prompt = f"{random.choice(girls)}"
194
+ prompt = f"boho chic"
195
+ # print(f"-------------{preset}-------------")
196
+ else:
197
+ prompt = f"Photo from Pinterest of {prompt} {interior}"
198
+ # prompt = default2
199
+ return f"{prompt} f{additional_prompt}"
200
+
201
+ style_list = [
202
+ {
203
+ "name": "None",
204
+ "prompt": ""
205
+ },
206
+ {
207
+ "name": "Minimalistic",
208
+ "prompt": "Minimalist interior design,clean lines,neutral colors,uncluttered space,functional furniture,lots of natural light"
209
+ },
210
+ {
211
+ "name": "Boho",
212
+ "prompt": "Bohemian chic interior,eclectic mix of patterns and textures,vintage furniture,plants,woven textiles,warm earthy colors"
213
+ },
214
+ {
215
+ "name": "Farmhouse",
216
+ "prompt": "Modern farmhouse interior,rustic wood elements,shiplap walls,neutral color palette,industrial accents,cozy textiles"
217
+ },
218
+ {
219
+ "name": "Saudi Prince",
220
+ "prompt": "Opulent gold interior,luxurious ornate furniture,crystal chandeliers,rich fabrics,marble floors,intricate Arabic patterns"
221
+ },
222
+ {
223
+ "name": "Neoclassical",
224
+ "prompt": "Neoclassical interior design,elegant columns,ornate moldings,symmetrical layout,refined furniture,muted color palette"
225
+ },
226
+ {
227
+ "name": "Eclectic",
228
+ "prompt": "Eclectic interior design,mix of styles and eras,bold color combinations,diverse furniture pieces,unique art objects"
229
+ },
230
+ {
231
+ "name": "Parisian",
232
+ "prompt": "Parisian apartment interior,all-white color scheme,ornate moldings,herringbone wood floors,elegant furniture,large windows"
233
+ },
234
+ {
235
+ "name": "Hollywood",
236
+ "prompt": "Hollywood Regency interior,glamorous and luxurious,bold colors,mirrored surfaces,velvet upholstery,gold accents"
237
+ },
238
+ {
239
+ "name": "Scandinavian",
240
+ "prompt": "Scandinavian interior design,light wood tones,white walls,minimalist furniture,cozy textiles,hygge atmosphere"
241
+ },
242
+ {
243
+ "name": "Beach",
244
+ "prompt": "Coastal beach house interior,light blue and white color scheme,weathered wood,nautical accents,sheer curtains,ocean view"
245
+ },
246
+ {
247
+ "name": "Japanese",
248
+ "prompt": "Traditional Japanese interior,tatami mats,shoji screens,low furniture,zen garden view,minimalist decor,natural materials"
249
+ },
250
+ {
251
+ "name": "Midcentury Modern",
252
+ "prompt": "Mid-century modern interior,1950s-60s style furniture,organic shapes,warm wood tones,bold accent colors,large windows"
253
+ },
254
+ {
255
+ "name": "Retro Futurism",
256
+ "prompt": "Neon (atompunk world) retro cyberpunk background",
257
+ },
258
+ {
259
+ "name": "Texan",
260
+ "prompt": "Western cowboy interior,rustic wood beams,leather furniture,cowhide rugs,antler chandeliers,southwestern patterns"
261
+ },
262
+ {
263
+ "name": "Matrix",
264
+ "prompt": "Futuristic cyberpunk interior,neon accent lighting,holographic plants,sleek black surfaces,advanced gaming setup,transparent screens,Blade Runner inspired decor,high-tech minimalist furniture"
265
+ }
266
+ ]
267
+
268
+ styles = {k["name"]: (k["prompt"]) for k in style_list}
269
+ STYLE_NAMES = list(styles.keys())
270
+
271
+ def apply_style(style_name):
272
+ if style_name in styles:
273
+ p = styles.get(style_name, "none")
274
+ return p
275
+
276
+
277
+ css = """
278
+ h1, h2, h3 {
279
+ text-align: center;
280
+ display: block;
281
+ }
282
+ footer {
283
+ visibility: hidden;
284
+ }
285
+ .gradio-container {
286
+ max-width: 1100px !important;
287
+ }
288
+ .gr-image {
289
+ display: flex;
290
+ justify-content: center;
291
+ align-items: center;
292
+ width: 100%;
293
+ height: 512px;
294
+ overflow: hidden;
295
+ }
296
+ .gr-image img {
297
+ width: 100%;
298
+ height: 100%;
299
+ object-fit: cover;
300
+ object-position: center;
301
+ }
302
+ """
303
+ with gr.Blocks(theme="bethecloud/storj_theme", css=css) as demo:
304
+ #############################################################################
305
+ with gr.Row():
306
+ with gr.Accordion("Advanced options", open=show_options, visible=show_options):
307
+ num_images = gr.Slider(
308
+ label="Images", minimum=1, maximum=4, value=1, step=1
309
+ )
310
+ image_resolution = gr.Slider(
311
+ label="Image resolution",
312
+ minimum=256,
313
+ maximum=1024,
314
+ value=512,
315
+ step=256,
316
+ )
317
+ preprocess_resolution = gr.Slider(
318
+ label="Preprocess resolution",
319
+ minimum=128,
320
+ maximum=1024,
321
+ value=512,
322
+ step=1,
323
+ )
324
+ num_steps = gr.Slider(
325
+ label="Number of steps", minimum=1, maximum=100, value=15, step=1
326
+ ) # 20/4.5 or 12 without lora, 4 with lora
327
+ guidance_scale = gr.Slider(
328
+ label="Guidance scale", minimum=0.1, maximum=30.0, value=5.5, step=0.1
329
+ ) # 5 without lora, 2 with lora
330
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
331
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
332
+ a_prompt = gr.Textbox(
333
+ label="Additional prompt",
334
+ value = "design-style interior designed (interior space), tungsten white balance, captured with a DSLR camera using f/10 aperture, 1/60 sec shutter speed, ISO 400, 20mm focal length"
335
+ )
336
+ n_prompt = gr.Textbox(
337
+ label="Negative prompt",
338
+ value="EasyNegativeV2, fcNeg, (badhandv4:1.4), (worst quality, low quality, bad quality, normal quality:2.0), (bad hands, missing fingers, extra fingers:2.0)",
339
+ )
340
+ #############################################################################
341
+ # input text
342
+ with gr.Column():
343
+ prompt = gr.Textbox(
344
+ label="Custom Design",
345
+ placeholder="Enter a description (optional)",
346
+ )
347
+ # design options
348
+ with gr.Row(visible=True):
349
+ style_selection = gr.Radio(
350
+ show_label=True,
351
+ container=True,
352
+ interactive=True,
353
+ choices=STYLE_NAMES,
354
+ value="None",
355
+ label="Design Styles",
356
+ )
357
+ # input image
358
+ with gr.Row(equal_height=True):
359
+ with gr.Column(scale=1, min_width=300):
360
+ image = gr.Image(
361
+ label="Input",
362
+ sources=["upload"],
363
+ show_label=True,
364
+ mirror_webcam=True,
365
+ type="pil",
366
+ )
367
+ # run button
368
+ with gr.Column():
369
+ run_button = gr.Button(value="Use this one", size="lg", visible=False)
370
+ # output image
371
+ with gr.Column(scale=1, min_width=300):
372
+ result = gr.Image(
373
+ label="Output",
374
+ interactive=False,
375
+ type="pil",
376
+ show_share_button= False,
377
+ )
378
+ # Use this image button
379
+ with gr.Column():
380
+ use_ai_button = gr.Button(value="Use this one", size="lg", visible=False)
381
+ config = [
382
+ image,
383
+ style_selection,
384
+ prompt,
385
+ a_prompt,
386
+ n_prompt,
387
+ num_images,
388
+ image_resolution,
389
+ preprocess_resolution,
390
+ num_steps,
391
+ guidance_scale,
392
+ seed,
393
+ ]
394
+
395
+ with gr.Row():
396
+ helper_text = gr.Markdown("## Tap and hold (on mobile) to save the image.", visible=True)
397
+
398
+ # image processing
399
+ @gr.on(triggers=[image.upload, prompt.submit, run_button.click], inputs=config, outputs=result, show_progress="minimal")
400
+ def auto_process_image(image, style_selection, prompt, a_prompt, n_prompt, num_images, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
401
+ return process_image(image, style_selection, prompt, a_prompt, n_prompt, num_images, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed)
402
+
403
+ # AI image processing
404
+ @gr.on(triggers=[use_ai_button.click], inputs=[result] + config, outputs=[image, result], show_progress="minimal")
405
+ def submit(previous_result, image, style_selection, prompt, a_prompt, n_prompt, num_images, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
406
+ # First, yield the previous result to update the input image immediately
407
+ yield previous_result, gr.update()
408
+ # Then, process the new input image
409
+ new_result = process_image(previous_result, style_selection, prompt, a_prompt, n_prompt, num_images, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed)
410
+ # Finally, yield the new result
411
+ yield previous_result, new_result
412
+
413
+ # Turn off buttons when processing
414
+ @gr.on(triggers=[image.upload, use_ai_button.click, run_button.click], inputs=None, outputs=[run_button, use_ai_button], show_progress="hidden")
415
+ def turn_buttons_off():
416
+ return gr.update(visible=False), gr.update(visible=False)
417
+
418
+ # Turn on buttons when processing is complete
419
+ @gr.on(triggers=[result.change], inputs=None, outputs=[use_ai_button, run_button], show_progress="hidden")
420
+ def turn_buttons_on():
421
+ return gr.update(visible=True), gr.update(visible=True)
422
+
423
+ @spaces.GPU(duration=12)
424
+ @torch.inference_mode()
425
+ def process_image(
426
+ image,
427
+ style_selection,
428
+ prompt,
429
+ a_prompt,
430
+ n_prompt,
431
+ num_images,
432
+ image_resolution,
433
+ preprocess_resolution,
434
+ num_steps,
435
+ guidance_scale,
436
+ seed,
437
+ ):
438
+ preprocess_start = time.time()
439
+ print("processing image")
440
+
441
+ seed = random.randint(0, MAX_SEED)
442
+ generator = torch.cuda.manual_seed(seed)
443
+ preprocessor.load("NormalBae")
444
+ control_image = preprocessor(
445
+ image=image,
446
+ image_resolution=image_resolution,
447
+ detect_resolution=preprocess_resolution,
448
+ )
449
+ preprocess_time = time.time() - preprocess_start
450
+ if style_selection is not None or style_selection != "None":
451
+ prompt = "Photo from Pinterest of " + apply_style(style_selection) + " " + prompt + "," + a_prompt
452
+ else:
453
+ prompt=str(get_prompt(prompt, a_prompt))
454
+ negative_prompt=str(n_prompt)
455
+ print(prompt)
456
+ print(f"\n-------------------------Preprocess done in: {preprocess_time:.2f} seconds-------------------------")
457
+ start = time.time()
458
+ results = pipe(
459
+ prompt=prompt,
460
+ negative_prompt=negative_prompt,
461
+ guidance_scale=guidance_scale,
462
+ num_images_per_prompt=num_images,
463
+ num_inference_steps=num_steps,
464
+ generator=generator,
465
+ image=control_image,
466
+ ).images[0]
467
+ print(f"\n-------------------------Inference done in: {time.time() - start:.2f} seconds-------------------------")
468
+ torch.cuda.empty_cache()
469
+
470
+ # upload block
471
+ timestamp = int(time.time())
472
+ img_path = f"{timestamp}.jpg"
473
+ results_path = f"{timestamp}_out.jpg"
474
+ imageio.imsave(img_path, image)
475
+ imageio.imsave(results_path, results)
476
+ api.upload_file(
477
+ path_or_fileobj=img_path,
478
+ path_in_repo=img_path,
479
+ repo_id="broyang/interior-ai-outputs",
480
+ repo_type="dataset",
481
+ token=API_KEY,
482
+ run_as_future=True,
483
+ )
484
+ api.upload_file(
485
+ path_or_fileobj=results_path,
486
+ path_in_repo=results_path,
487
+ repo_id="broyang/interior-ai-outputs",
488
+ repo_type="dataset",
489
+ token=API_KEY,
490
+ run_as_future=True,
491
+ )
492
+ return results
493
+
494
+ if prod:
495
+ demo.queue(max_size=20).launch(server_name="localhost", server_port=port)
496
+ else:
497
+ demo.queue(api_open=False).launch(show_api=False)
498
+ ```
499
+
500
+ # .aidigestignore
501
+
502
+ ```
503
+ controlnet_aux_local/normalbae/*
504
+ requirements.txt
505
+ win.requirements.txt
506
+ web.html
507
+ client.py
508
+ local_app.py
509
+ README.md
510
+ Dockerfile
511
+ .gitignore
512
+ .gitattributes
513
+ ```
514
+
515
+ # controlnet_aux_local/util.py
516
+
517
+ ```py
518
+ import os
519
+ import random
520
+
521
+ import cv2
522
+ import numpy as np
523
+ import torch
524
+
525
+ annotator_ckpts_path = os.path.join(os.path.dirname(__file__), 'ckpts')
526
+
527
+
528
+ def HWC3(x):
529
+ assert x.dtype == np.uint8
530
+ if x.ndim == 2:
531
+ x = x[:, :, None]
532
+ assert x.ndim == 3
533
+ H, W, C = x.shape
534
+ assert C == 1 or C == 3 or C == 4
535
+ if C == 3:
536
+ return x
537
+ if C == 1:
538
+ return np.concatenate([x, x, x], axis=2)
539
+ if C == 4:
540
+ color = x[:, :, 0:3].astype(np.float32)
541
+ alpha = x[:, :, 3:4].astype(np.float32) / 255.0
542
+ y = color * alpha + 255.0 * (1.0 - alpha)
543
+ y = y.clip(0, 255).astype(np.uint8)
544
+ return y
545
+
546
+
547
+ def make_noise_disk(H, W, C, F):
548
+ noise = np.random.uniform(low=0, high=1, size=((H // F) + 2, (W // F) + 2, C))
549
+ noise = cv2.resize(noise, (W + 2 * F, H + 2 * F), interpolation=cv2.INTER_CUBIC)
550
+ noise = noise[F: F + H, F: F + W]
551
+ noise -= np.min(noise)
552
+ noise /= np.max(noise)
553
+ if C == 1:
554
+ noise = noise[:, :, None]
555
+ return noise
556
+
557
+
558
+ def nms(x, t, s):
559
+ x = cv2.GaussianBlur(x.astype(np.float32), (0, 0), s)
560
+
561
+ f1 = np.array([[0, 0, 0], [1, 1, 1], [0, 0, 0]], dtype=np.uint8)
562
+ f2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8)
563
+ f3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.uint8)
564
+ f4 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]], dtype=np.uint8)
565
+
566
+ y = np.zeros_like(x)
567
+
568
+ for f in [f1, f2, f3, f4]:
569
+ np.putmask(y, cv2.dilate(x, kernel=f) == x, x)
570
+
571
+ z = np.zeros_like(y, dtype=np.uint8)
572
+ z[y > t] = 255
573
+ return z
574
+
575
+ def min_max_norm(x):
576
+ x -= np.min(x)
577
+ x /= np.maximum(np.max(x), 1e-5)
578
+ return x
579
+
580
+
581
+ def safe_step(x, step=2):
582
+ y = x.astype(np.float32) * float(step + 1)
583
+ y = y.astype(np.int32).astype(np.float32) / float(step)
584
+ return y
585
+
586
+
587
+ def img2mask(img, H, W, low=10, high=90):
588
+ assert img.ndim == 3 or img.ndim == 2
589
+ assert img.dtype == np.uint8
590
+
591
+ if img.ndim == 3:
592
+ y = img[:, :, random.randrange(0, img.shape[2])]
593
+ else:
594
+ y = img
595
+
596
+ y = cv2.resize(y, (W, H), interpolation=cv2.INTER_CUBIC)
597
+
598
+ if random.uniform(0, 1) < 0.5:
599
+ y = 255 - y
600
+
601
+ return y < np.percentile(y, random.randrange(low, high))
602
+
603
+
604
+ def resize_image(input_image, resolution):
605
+ H, W, C = input_image.shape
606
+ H = float(H)
607
+ W = float(W)
608
+ k = float(resolution) / min(H, W)
609
+ H *= k
610
+ W *= k
611
+ H = int(np.round(H / 64.0)) * 64
612
+ W = int(np.round(W / 64.0)) * 64
613
+ img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
614
+ return img
615
+
616
+
617
+ def torch_gc():
618
+ if torch.cuda.is_available():
619
+ torch.cuda.empty_cache()
620
+ torch.cuda.ipc_collect()
621
+
622
+
623
+ def ade_palette():
624
+ """ADE20K palette that maps each class to RGB values."""
625
+ return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
626
+ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
627
+ [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
628
+ [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
629
+ [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
630
+ [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
631
+ [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
632
+ [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
633
+ [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
634
+ [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
635
+ [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
636
+ [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
637
+ [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
638
+ [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
639
+ [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
640
+ [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
641
+ [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
642
+ [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
643
+ [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
644
+ [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
645
+ [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
646
+ [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
647
+ [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
648
+ [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
649
+ [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
650
+ [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
651
+ [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
652
+ [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
653
+ [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
654
+ [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
655
+ [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
656
+ [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
657
+ [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
658
+ [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
659
+ [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
660
+ [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
661
+ [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
662
+ [102, 255, 0], [92, 0, 255]]
663
+
664
+
665
+ ```
666
+
667
+ # controlnet_aux_local/processor.py
668
+
669
+ ```py
670
+ """
671
+ This file contains a Processor that can be used to process images with controlnet aux processors
672
+ """
673
+ import io
674
+ import logging
675
+ from typing import Dict, Optional, Union
676
+
677
+ from PIL import Image
678
+
679
+ from controlnet_aux_local import (CannyDetector, ContentShuffleDetector, HEDdetector,
680
+ LeresDetector, LineartAnimeDetector,
681
+ LineartDetector, MediapipeFaceDetector,
682
+ MidasDetector, MLSDdetector, NormalBaeDetector,
683
+ OpenposeDetector, PidiNetDetector, ZoeDetector,
684
+ DWposeDetector)
685
+
686
+ LOGGER = logging.getLogger(__name__)
687
+
688
+
689
+ MODELS = {
690
+ # checkpoint models
691
+ 'scribble_hed': {'class': HEDdetector, 'checkpoint': True},
692
+ 'softedge_hed': {'class': HEDdetector, 'checkpoint': True},
693
+ 'scribble_hedsafe': {'class': HEDdetector, 'checkpoint': True},
694
+ 'softedge_hedsafe': {'class': HEDdetector, 'checkpoint': True},
695
+ 'depth_midas': {'class': MidasDetector, 'checkpoint': True},
696
+ 'mlsd': {'class': MLSDdetector, 'checkpoint': True},
697
+ 'openpose': {'class': OpenposeDetector, 'checkpoint': True},
698
+ 'openpose_face': {'class': OpenposeDetector, 'checkpoint': True},
699
+ 'openpose_faceonly': {'class': OpenposeDetector, 'checkpoint': True},
700
+ 'openpose_full': {'class': OpenposeDetector, 'checkpoint': True},
701
+ 'openpose_hand': {'class': OpenposeDetector, 'checkpoint': True},
702
+ 'dwpose': {'class': DWposeDetector, 'checkpoint': True},
703
+ 'scribble_pidinet': {'class': PidiNetDetector, 'checkpoint': True},
704
+ 'softedge_pidinet': {'class': PidiNetDetector, 'checkpoint': True},
705
+ 'scribble_pidsafe': {'class': PidiNetDetector, 'checkpoint': True},
706
+ 'softedge_pidsafe': {'class': PidiNetDetector, 'checkpoint': True},
707
+ 'normal_bae': {'class': NormalBaeDetector, 'checkpoint': True},
708
+ 'lineart_coarse': {'class': LineartDetector, 'checkpoint': True},
709
+ 'lineart_realistic': {'class': LineartDetector, 'checkpoint': True},
710
+ 'lineart_anime': {'class': LineartAnimeDetector, 'checkpoint': True},
711
+ 'depth_zoe': {'class': ZoeDetector, 'checkpoint': True},
712
+ 'depth_leres': {'class': LeresDetector, 'checkpoint': True},
713
+ 'depth_leres++': {'class': LeresDetector, 'checkpoint': True},
714
+ # instantiate
715
+ 'shuffle': {'class': ContentShuffleDetector, 'checkpoint': False},
716
+ 'mediapipe_face': {'class': MediapipeFaceDetector, 'checkpoint': False},
717
+ 'canny': {'class': CannyDetector, 'checkpoint': False},
718
+ }
719
+
720
+
721
+ MODEL_PARAMS = {
722
+ 'scribble_hed': {'scribble': True},
723
+ 'softedge_hed': {'scribble': False},
724
+ 'scribble_hedsafe': {'scribble': True, 'safe': True},
725
+ 'softedge_hedsafe': {'scribble': False, 'safe': True},
726
+ 'depth_midas': {},
727
+ 'mlsd': {},
728
+ 'openpose': {'include_body': True, 'include_hand': False, 'include_face': False},
729
+ 'openpose_face': {'include_body': True, 'include_hand': False, 'include_face': True},
730
+ 'openpose_faceonly': {'include_body': False, 'include_hand': False, 'include_face': True},
731
+ 'openpose_full': {'include_body': True, 'include_hand': True, 'include_face': True},
732
+ 'openpose_hand': {'include_body': False, 'include_hand': True, 'include_face': False},
733
+ 'dwpose': {},
734
+ 'scribble_pidinet': {'safe': False, 'scribble': True},
735
+ 'softedge_pidinet': {'safe': False, 'scribble': False},
736
+ 'scribble_pidsafe': {'safe': True, 'scribble': True},
737
+ 'softedge_pidsafe': {'safe': True, 'scribble': False},
738
+ 'normal_bae': {},
739
+ 'lineart_realistic': {'coarse': False},
740
+ 'lineart_coarse': {'coarse': True},
741
+ 'lineart_anime': {},
742
+ 'canny': {},
743
+ 'shuffle': {},
744
+ 'depth_zoe': {},
745
+ 'depth_leres': {'boost': False},
746
+ 'depth_leres++': {'boost': True},
747
+ 'mediapipe_face': {},
748
+ }
749
+
750
+ CHOICES = f"Choices for the processor are {list(MODELS.keys())}"
751
+
752
+
753
+ class Processor:
754
+ def __init__(self, processor_id: str, params: Optional[Dict] = None) -> None:
755
+ """Processor that can be used to process images with controlnet aux processors
756
+
757
+ Args:
758
+ processor_id (str): processor name, options are 'hed, midas, mlsd, openpose,
759
+ pidinet, normalbae, lineart, lineart_coarse, lineart_anime,
760
+ canny, content_shuffle, zoe, mediapipe_face
761
+ params (Optional[Dict]): parameters for the processor
762
+ """
763
+ LOGGER.info(f"Loading {processor_id}")
764
+
765
+ if processor_id not in MODELS:
766
+ raise ValueError(f"{processor_id} is not a valid processor id. Please make sure to choose one of {', '.join(MODELS.keys())}")
767
+
768
+ self.processor_id = processor_id
769
+ self.processor = self.load_processor(self.processor_id)
770
+
771
+ # load default params
772
+ self.params = MODEL_PARAMS[self.processor_id]
773
+ # update with user params
774
+ if params:
775
+ self.params.update(params)
776
+
777
+ def load_processor(self, processor_id: str) -> 'Processor':
778
+ """Load controlnet aux processors
779
+
780
+ Args:
781
+ processor_id (str): processor name
782
+
783
+ Returns:
784
+ Processor: controlnet aux processor
785
+ """
786
+ processor = MODELS[processor_id]['class']
787
+
788
+ # check if the proecssor is a checkpoint model
789
+ if MODELS[processor_id]['checkpoint']:
790
+ processor = processor.from_pretrained("lllyasviel/Annotators")
791
+ else:
792
+ processor = processor()
793
+ return processor
794
+
795
+ def __call__(self, image: Union[Image.Image, bytes],
796
+ to_pil: bool = True) -> Union[Image.Image, bytes]:
797
+ """processes an image with a controlnet aux processor
798
+
799
+ Args:
800
+ image (Union[Image.Image, bytes]): input image in bytes or PIL Image
801
+ to_pil (bool): whether to return bytes or PIL Image
802
+
803
+ Returns:
804
+ Union[Image.Image, bytes]: processed image in bytes or PIL Image
805
+ """
806
+ # check if bytes or PIL Image
807
+ if isinstance(image, bytes):
808
+ image = Image.open(io.BytesIO(image)).convert("RGB")
809
+
810
+ processed_image = self.processor(image, **self.params)
811
+
812
+ if to_pil:
813
+ return processed_image
814
+ else:
815
+ output_bytes = io.BytesIO()
816
+ processed_image.save(output_bytes, format='JPEG')
817
+ return output_bytes.getvalue()
818
+
819
+ ```
820
+
821
+ # controlnet_aux_local/__init__.py
822
+
823
+ ```py
824
+ __version__ = "0.0.8"
825
+
826
+ # from .hed import HEDdetector
827
+ # from .leres import LeresDetector
828
+ # from .lineart import LineartDetector
829
+ # from .lineart_anime import LineartAnimeDetector
830
+ # from .midas import MidasDetector
831
+ # from .mlsd import MLSDdetector
832
+ from .normalbae import NormalBaeDetector
833
+ # from .open_pose import OpenposeDetector
834
+ # from .pidi import PidiNetDetector
835
+ # from .zoe import ZoeDetector
836
+
837
+ # from .canny import CannyDetector
838
+ # from .mediapipe_face import MediapipeFaceDetector
839
+ # from .segment_anything import SamDetector
840
+ # from .shuffle import ContentShuffleDetector
841
+ # from .dwpose import DWposeDetector
842
+ ```
843
+
controlnet_aux_local/canny/__init__.py DELETED
@@ -1,36 +0,0 @@
1
- import warnings
2
- import cv2
3
- import numpy as np
4
- from PIL import Image
5
- from ..util import HWC3, resize_image
6
-
7
- class CannyDetector:
8
- def __call__(self, input_image=None, low_threshold=100, high_threshold=200, detect_resolution=512, image_resolution=512, output_type=None, **kwargs):
9
- if "img" in kwargs:
10
- warnings.warn("img is deprecated, please use `input_image=...` instead.", DeprecationWarning)
11
- input_image = kwargs.pop("img")
12
-
13
- if input_image is None:
14
- raise ValueError("input_image must be defined.")
15
-
16
- if not isinstance(input_image, np.ndarray):
17
- input_image = np.array(input_image, dtype=np.uint8)
18
- output_type = output_type or "pil"
19
- else:
20
- output_type = output_type or "np"
21
-
22
- input_image = HWC3(input_image)
23
- input_image = resize_image(input_image, detect_resolution)
24
-
25
- detected_map = cv2.Canny(input_image, low_threshold, high_threshold)
26
- detected_map = HWC3(detected_map)
27
-
28
- img = resize_image(input_image, image_resolution)
29
- H, W, C = img.shape
30
-
31
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
32
-
33
- if output_type == "pil":
34
- detected_map = Image.fromarray(detected_map)
35
-
36
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/dwpose/__init__.py DELETED
@@ -1,91 +0,0 @@
1
- # Openpose
2
- # Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose
3
- # 2nd Edited by https://github.com/Hzzone/pytorch-openpose
4
- # 3rd Edited by ControlNet
5
- # 4th Edited by ControlNet (added face and correct hands)
6
-
7
- import os
8
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
9
-
10
- import cv2
11
- import torch
12
- import numpy as np
13
- from PIL import Image
14
-
15
- from ..util import HWC3, resize_image
16
- from . import util
17
-
18
-
19
- def draw_pose(pose, H, W):
20
- bodies = pose['bodies']
21
- faces = pose['faces']
22
- hands = pose['hands']
23
- candidate = bodies['candidate']
24
- subset = bodies['subset']
25
-
26
- canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)
27
- canvas = util.draw_bodypose(canvas, candidate, subset)
28
- canvas = util.draw_handpose(canvas, hands)
29
- canvas = util.draw_facepose(canvas, faces)
30
-
31
- return canvas
32
-
33
- class DWposeDetector:
34
- def __init__(self, det_config=None, det_ckpt=None, pose_config=None, pose_ckpt=None, device="cpu"):
35
- from .wholebody import Wholebody
36
-
37
- self.pose_estimation = Wholebody(det_config, det_ckpt, pose_config, pose_ckpt, device)
38
-
39
- def to(self, device):
40
- self.pose_estimation.to(device)
41
- return self
42
-
43
- def __call__(self, input_image, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
44
-
45
- input_image = cv2.cvtColor(np.array(input_image, dtype=np.uint8), cv2.COLOR_RGB2BGR)
46
-
47
- input_image = HWC3(input_image)
48
- input_image = resize_image(input_image, detect_resolution)
49
- H, W, C = input_image.shape
50
-
51
- with torch.no_grad():
52
- candidate, subset = self.pose_estimation(input_image)
53
- nums, keys, locs = candidate.shape
54
- candidate[..., 0] /= float(W)
55
- candidate[..., 1] /= float(H)
56
- body = candidate[:,:18].copy()
57
- body = body.reshape(nums*18, locs)
58
- score = subset[:,:18]
59
-
60
- for i in range(len(score)):
61
- for j in range(len(score[i])):
62
- if score[i][j] > 0.3:
63
- score[i][j] = int(18*i+j)
64
- else:
65
- score[i][j] = -1
66
-
67
- un_visible = subset<0.3
68
- candidate[un_visible] = -1
69
-
70
- foot = candidate[:,18:24]
71
-
72
- faces = candidate[:,24:92]
73
-
74
- hands = candidate[:,92:113]
75
- hands = np.vstack([hands, candidate[:,113:]])
76
-
77
- bodies = dict(candidate=body, subset=score)
78
- pose = dict(bodies=bodies, hands=hands, faces=faces)
79
-
80
- detected_map = draw_pose(pose, H, W)
81
- detected_map = HWC3(detected_map)
82
-
83
- img = resize_image(input_image, image_resolution)
84
- H, W, C = img.shape
85
-
86
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
87
-
88
- if output_type == "pil":
89
- detected_map = Image.fromarray(detected_map)
90
-
91
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/dwpose/util.py DELETED
@@ -1,303 +0,0 @@
1
- import math
2
- import numpy as np
3
- import cv2
4
-
5
-
6
- eps = 0.01
7
-
8
-
9
- def smart_resize(x, s):
10
- Ht, Wt = s
11
- if x.ndim == 2:
12
- Ho, Wo = x.shape
13
- Co = 1
14
- else:
15
- Ho, Wo, Co = x.shape
16
- if Co == 3 or Co == 1:
17
- k = float(Ht + Wt) / float(Ho + Wo)
18
- return cv2.resize(x, (int(Wt), int(Ht)), interpolation=cv2.INTER_AREA if k < 1 else cv2.INTER_LANCZOS4)
19
- else:
20
- return np.stack([smart_resize(x[:, :, i], s) for i in range(Co)], axis=2)
21
-
22
-
23
- def smart_resize_k(x, fx, fy):
24
- if x.ndim == 2:
25
- Ho, Wo = x.shape
26
- Co = 1
27
- else:
28
- Ho, Wo, Co = x.shape
29
- Ht, Wt = Ho * fy, Wo * fx
30
- if Co == 3 or Co == 1:
31
- k = float(Ht + Wt) / float(Ho + Wo)
32
- return cv2.resize(x, (int(Wt), int(Ht)), interpolation=cv2.INTER_AREA if k < 1 else cv2.INTER_LANCZOS4)
33
- else:
34
- return np.stack([smart_resize_k(x[:, :, i], fx, fy) for i in range(Co)], axis=2)
35
-
36
-
37
- def padRightDownCorner(img, stride, padValue):
38
- h = img.shape[0]
39
- w = img.shape[1]
40
-
41
- pad = 4 * [None]
42
- pad[0] = 0 # up
43
- pad[1] = 0 # left
44
- pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
45
- pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
46
-
47
- img_padded = img
48
- pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1))
49
- img_padded = np.concatenate((pad_up, img_padded), axis=0)
50
- pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1))
51
- img_padded = np.concatenate((pad_left, img_padded), axis=1)
52
- pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1))
53
- img_padded = np.concatenate((img_padded, pad_down), axis=0)
54
- pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1))
55
- img_padded = np.concatenate((img_padded, pad_right), axis=1)
56
-
57
- return img_padded, pad
58
-
59
-
60
- def transfer(model, model_weights):
61
- transfered_model_weights = {}
62
- for weights_name in model.state_dict().keys():
63
- transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])]
64
- return transfered_model_weights
65
-
66
-
67
- def draw_bodypose(canvas, candidate, subset):
68
- H, W, C = canvas.shape
69
- candidate = np.array(candidate)
70
- subset = np.array(subset)
71
-
72
- stickwidth = 4
73
-
74
- limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
75
- [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
76
- [1, 16], [16, 18], [3, 17], [6, 18]]
77
-
78
- colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
79
- [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
80
- [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
81
-
82
- for i in range(17):
83
- for n in range(len(subset)):
84
- index = subset[n][np.array(limbSeq[i]) - 1]
85
- if -1 in index:
86
- continue
87
- Y = candidate[index.astype(int), 0] * float(W)
88
- X = candidate[index.astype(int), 1] * float(H)
89
- mX = np.mean(X)
90
- mY = np.mean(Y)
91
- length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
92
- angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
93
- polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
94
- cv2.fillConvexPoly(canvas, polygon, colors[i])
95
-
96
- canvas = (canvas * 0.6).astype(np.uint8)
97
-
98
- for i in range(18):
99
- for n in range(len(subset)):
100
- index = int(subset[n][i])
101
- if index == -1:
102
- continue
103
- x, y = candidate[index][0:2]
104
- x = int(x * W)
105
- y = int(y * H)
106
- cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)
107
-
108
- return canvas
109
-
110
-
111
- def draw_handpose(canvas, all_hand_peaks):
112
- import matplotlib
113
-
114
- H, W, C = canvas.shape
115
-
116
- edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
117
- [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
118
-
119
- # (person_number*2, 21, 2)
120
- for i in range(len(all_hand_peaks)):
121
- peaks = all_hand_peaks[i]
122
- peaks = np.array(peaks)
123
-
124
- for ie, e in enumerate(edges):
125
-
126
- x1, y1 = peaks[e[0]]
127
- x2, y2 = peaks[e[1]]
128
-
129
- x1 = int(x1 * W)
130
- y1 = int(y1 * H)
131
- x2 = int(x2 * W)
132
- y2 = int(y2 * H)
133
- if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
134
- cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255, thickness=2)
135
-
136
- for _, keyponit in enumerate(peaks):
137
- x, y = keyponit
138
-
139
- x = int(x * W)
140
- y = int(y * H)
141
- if x > eps and y > eps:
142
- cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1)
143
- return canvas
144
-
145
-
146
- def draw_facepose(canvas, all_lmks):
147
- H, W, C = canvas.shape
148
- for lmks in all_lmks:
149
- lmks = np.array(lmks)
150
- for lmk in lmks:
151
- x, y = lmk
152
- x = int(x * W)
153
- y = int(y * H)
154
- if x > eps and y > eps:
155
- cv2.circle(canvas, (x, y), 3, (255, 255, 255), thickness=-1)
156
- return canvas
157
-
158
-
159
- # detect hand according to body pose keypoints
160
- # please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cpp
161
- def handDetect(candidate, subset, oriImg):
162
- # right hand: wrist 4, elbow 3, shoulder 2
163
- # left hand: wrist 7, elbow 6, shoulder 5
164
- ratioWristElbow = 0.33
165
- detect_result = []
166
- image_height, image_width = oriImg.shape[0:2]
167
- for person in subset.astype(int):
168
- # if any of three not detected
169
- has_left = np.sum(person[[5, 6, 7]] == -1) == 0
170
- has_right = np.sum(person[[2, 3, 4]] == -1) == 0
171
- if not (has_left or has_right):
172
- continue
173
- hands = []
174
- #left hand
175
- if has_left:
176
- left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]]
177
- x1, y1 = candidate[left_shoulder_index][:2]
178
- x2, y2 = candidate[left_elbow_index][:2]
179
- x3, y3 = candidate[left_wrist_index][:2]
180
- hands.append([x1, y1, x2, y2, x3, y3, True])
181
- # right hand
182
- if has_right:
183
- right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]]
184
- x1, y1 = candidate[right_shoulder_index][:2]
185
- x2, y2 = candidate[right_elbow_index][:2]
186
- x3, y3 = candidate[right_wrist_index][:2]
187
- hands.append([x1, y1, x2, y2, x3, y3, False])
188
-
189
- for x1, y1, x2, y2, x3, y3, is_left in hands:
190
- # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox
191
- # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]);
192
- # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]);
193
- # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow);
194
- # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder);
195
- # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder);
196
- x = x3 + ratioWristElbow * (x3 - x2)
197
- y = y3 + ratioWristElbow * (y3 - y2)
198
- distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)
199
- distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
200
- width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder)
201
- # x-y refers to the center --> offset to topLeft point
202
- # handRectangle.x -= handRectangle.width / 2.f;
203
- # handRectangle.y -= handRectangle.height / 2.f;
204
- x -= width / 2
205
- y -= width / 2 # width = height
206
- # overflow the image
207
- if x < 0: x = 0
208
- if y < 0: y = 0
209
- width1 = width
210
- width2 = width
211
- if x + width > image_width: width1 = image_width - x
212
- if y + width > image_height: width2 = image_height - y
213
- width = min(width1, width2)
214
- # the max hand box value is 20 pixels
215
- if width >= 20:
216
- detect_result.append([int(x), int(y), int(width), is_left])
217
-
218
- '''
219
- return value: [[x, y, w, True if left hand else False]].
220
- width=height since the network require squared input.
221
- x, y is the coordinate of top left
222
- '''
223
- return detect_result
224
-
225
-
226
- # Written by Lvmin
227
- def faceDetect(candidate, subset, oriImg):
228
- # left right eye ear 14 15 16 17
229
- detect_result = []
230
- image_height, image_width = oriImg.shape[0:2]
231
- for person in subset.astype(int):
232
- has_head = person[0] > -1
233
- if not has_head:
234
- continue
235
-
236
- has_left_eye = person[14] > -1
237
- has_right_eye = person[15] > -1
238
- has_left_ear = person[16] > -1
239
- has_right_ear = person[17] > -1
240
-
241
- if not (has_left_eye or has_right_eye or has_left_ear or has_right_ear):
242
- continue
243
-
244
- head, left_eye, right_eye, left_ear, right_ear = person[[0, 14, 15, 16, 17]]
245
-
246
- width = 0.0
247
- x0, y0 = candidate[head][:2]
248
-
249
- if has_left_eye:
250
- x1, y1 = candidate[left_eye][:2]
251
- d = max(abs(x0 - x1), abs(y0 - y1))
252
- width = max(width, d * 3.0)
253
-
254
- if has_right_eye:
255
- x1, y1 = candidate[right_eye][:2]
256
- d = max(abs(x0 - x1), abs(y0 - y1))
257
- width = max(width, d * 3.0)
258
-
259
- if has_left_ear:
260
- x1, y1 = candidate[left_ear][:2]
261
- d = max(abs(x0 - x1), abs(y0 - y1))
262
- width = max(width, d * 1.5)
263
-
264
- if has_right_ear:
265
- x1, y1 = candidate[right_ear][:2]
266
- d = max(abs(x0 - x1), abs(y0 - y1))
267
- width = max(width, d * 1.5)
268
-
269
- x, y = x0, y0
270
-
271
- x -= width
272
- y -= width
273
-
274
- if x < 0:
275
- x = 0
276
-
277
- if y < 0:
278
- y = 0
279
-
280
- width1 = width * 2
281
- width2 = width * 2
282
-
283
- if x + width > image_width:
284
- width1 = image_width - x
285
-
286
- if y + width > image_height:
287
- width2 = image_height - y
288
-
289
- width = min(width1, width2)
290
-
291
- if width >= 20:
292
- detect_result.append([int(x), int(y), int(width)])
293
-
294
- return detect_result
295
-
296
-
297
- # get max index of 2d array
298
- def npmax(array):
299
- arrayindex = array.argmax(1)
300
- arrayvalue = array.max(1)
301
- i = arrayvalue.argmax()
302
- j = arrayindex[i]
303
- return i, j
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/dwpose/wholebody.py DELETED
@@ -1,121 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- import os
3
- import numpy as np
4
- import warnings
5
-
6
- try:
7
- import mmcv
8
- except ImportError:
9
- warnings.warn(
10
- "The module 'mmcv' is not installed. The package will have limited functionality. Please install it using the command: mim install 'mmcv>=2.0.1'"
11
- )
12
-
13
- try:
14
- from mmpose.apis import inference_topdown
15
- from mmpose.apis import init_model as init_pose_estimator
16
- from mmpose.evaluation.functional import nms
17
- from mmpose.utils import adapt_mmdet_pipeline
18
- from mmpose.structures import merge_data_samples
19
- except ImportError:
20
- warnings.warn(
21
- "The module 'mmpose' is not installed. The package will have limited functionality. Please install it using the command: mim install 'mmpose>=1.1.0'"
22
- )
23
-
24
- try:
25
- from mmdet.apis import inference_detector, init_detector
26
- except ImportError:
27
- warnings.warn(
28
- "The module 'mmdet' is not installed. The package will have limited functionality. Please install it using the command: mim install 'mmdet>=3.1.0'"
29
- )
30
-
31
-
32
- class Wholebody:
33
- def __init__(self,
34
- det_config=None, det_ckpt=None,
35
- pose_config=None, pose_ckpt=None,
36
- device="cpu"):
37
-
38
- if det_config is None:
39
- det_config = os.path.join(os.path.dirname(__file__), "yolox_config/yolox_l_8xb8-300e_coco.py")
40
-
41
- if pose_config is None:
42
- pose_config = os.path.join(os.path.dirname(__file__), "dwpose_config/dwpose-l_384x288.py")
43
-
44
- if det_ckpt is None:
45
- det_ckpt = 'https://download.openmmlab.com/mmdetection/v2.0/yolox/yolox_l_8x8_300e_coco/yolox_l_8x8_300e_coco_20211126_140236-d3bd2b23.pth'
46
-
47
- if pose_ckpt is None:
48
- pose_ckpt = "https://huggingface.co/wanghaofan/dw-ll_ucoco_384/resolve/main/dw-ll_ucoco_384.pth"
49
-
50
- # build detector
51
- self.detector = init_detector(det_config, det_ckpt, device=device)
52
- self.detector.cfg = adapt_mmdet_pipeline(self.detector.cfg)
53
-
54
- # build pose estimator
55
- self.pose_estimator = init_pose_estimator(
56
- pose_config,
57
- pose_ckpt,
58
- device=device)
59
-
60
- def to(self, device):
61
- self.detector.to(device)
62
- self.pose_estimator.to(device)
63
- return self
64
-
65
- def __call__(self, oriImg):
66
- # predict bbox
67
- det_result = inference_detector(self.detector, oriImg)
68
- pred_instance = det_result.pred_instances.cpu().numpy()
69
- bboxes = np.concatenate(
70
- (pred_instance.bboxes, pred_instance.scores[:, None]), axis=1)
71
- bboxes = bboxes[np.logical_and(pred_instance.labels == 0,
72
- pred_instance.scores > 0.5)]
73
-
74
- # set NMS threshold
75
- bboxes = bboxes[nms(bboxes, 0.7), :4]
76
-
77
- # predict keypoints
78
- if len(bboxes) == 0:
79
- pose_results = inference_topdown(self.pose_estimator, oriImg)
80
- else:
81
- pose_results = inference_topdown(self.pose_estimator, oriImg, bboxes)
82
- preds = merge_data_samples(pose_results)
83
- preds = preds.pred_instances
84
-
85
- # preds = pose_results[0].pred_instances
86
- keypoints = preds.get('transformed_keypoints',
87
- preds.keypoints)
88
- if 'keypoint_scores' in preds:
89
- scores = preds.keypoint_scores
90
- else:
91
- scores = np.ones(keypoints.shape[:-1])
92
-
93
- if 'keypoints_visible' in preds:
94
- visible = preds.keypoints_visible
95
- else:
96
- visible = np.ones(keypoints.shape[:-1])
97
- keypoints_info = np.concatenate(
98
- (keypoints, scores[..., None], visible[..., None]),
99
- axis=-1)
100
- # compute neck joint
101
- neck = np.mean(keypoints_info[:, [5, 6]], axis=1)
102
- # neck score when visualizing pred
103
- neck[:, 2:4] = np.logical_and(
104
- keypoints_info[:, 5, 2:4] > 0.3,
105
- keypoints_info[:, 6, 2:4] > 0.3).astype(int)
106
- new_keypoints_info = np.insert(
107
- keypoints_info, 17, neck, axis=1)
108
- mmpose_idx = [
109
- 17, 6, 8, 10, 7, 9, 12, 14, 16, 13, 15, 2, 1, 4, 3
110
- ]
111
- openpose_idx = [
112
- 1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17
113
- ]
114
- new_keypoints_info[:, openpose_idx] = \
115
- new_keypoints_info[:, mmpose_idx]
116
- keypoints_info = new_keypoints_info
117
-
118
- keypoints, scores, visible = keypoints_info[
119
- ..., :2], keypoints_info[..., 2], keypoints_info[..., 3]
120
-
121
- return keypoints, scores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/hed/__init__.py DELETED
@@ -1,129 +0,0 @@
1
- # This is an improved version and model of HED edge detection with Apache License, Version 2.0.
2
- # Please use this implementation in your products
3
- # This implementation may produce slightly different results from Saining Xie's official implementations,
4
- # but it generates smoother edges and is more suitable for ControlNet as well as other image-to-image translations.
5
- # Different from official models and other implementations, this is an RGB-input model (rather than BGR)
6
- # and in this way it works better for gradio's RGB protocol
7
-
8
- import os
9
- import warnings
10
-
11
- import cv2
12
- import numpy as np
13
- import torch
14
- from einops import rearrange
15
- from huggingface_hub import hf_hub_download
16
- from PIL import Image
17
-
18
- from ..util import HWC3, nms, resize_image, safe_step
19
-
20
-
21
- class DoubleConvBlock(torch.nn.Module):
22
- def __init__(self, input_channel, output_channel, layer_number):
23
- super().__init__()
24
- self.convs = torch.nn.Sequential()
25
- self.convs.append(torch.nn.Conv2d(in_channels=input_channel, out_channels=output_channel, kernel_size=(3, 3), stride=(1, 1), padding=1))
26
- for i in range(1, layer_number):
27
- self.convs.append(torch.nn.Conv2d(in_channels=output_channel, out_channels=output_channel, kernel_size=(3, 3), stride=(1, 1), padding=1))
28
- self.projection = torch.nn.Conv2d(in_channels=output_channel, out_channels=1, kernel_size=(1, 1), stride=(1, 1), padding=0)
29
-
30
- def __call__(self, x, down_sampling=False):
31
- h = x
32
- if down_sampling:
33
- h = torch.nn.functional.max_pool2d(h, kernel_size=(2, 2), stride=(2, 2))
34
- for conv in self.convs:
35
- h = conv(h)
36
- h = torch.nn.functional.relu(h)
37
- return h, self.projection(h)
38
-
39
-
40
- class ControlNetHED_Apache2(torch.nn.Module):
41
- def __init__(self):
42
- super().__init__()
43
- self.norm = torch.nn.Parameter(torch.zeros(size=(1, 3, 1, 1)))
44
- self.block1 = DoubleConvBlock(input_channel=3, output_channel=64, layer_number=2)
45
- self.block2 = DoubleConvBlock(input_channel=64, output_channel=128, layer_number=2)
46
- self.block3 = DoubleConvBlock(input_channel=128, output_channel=256, layer_number=3)
47
- self.block4 = DoubleConvBlock(input_channel=256, output_channel=512, layer_number=3)
48
- self.block5 = DoubleConvBlock(input_channel=512, output_channel=512, layer_number=3)
49
-
50
- def __call__(self, x):
51
- h = x - self.norm
52
- h, projection1 = self.block1(h)
53
- h, projection2 = self.block2(h, down_sampling=True)
54
- h, projection3 = self.block3(h, down_sampling=True)
55
- h, projection4 = self.block4(h, down_sampling=True)
56
- h, projection5 = self.block5(h, down_sampling=True)
57
- return projection1, projection2, projection3, projection4, projection5
58
-
59
- class HEDdetector:
60
- def __init__(self, netNetwork):
61
- self.netNetwork = netNetwork
62
-
63
- @classmethod
64
- def from_pretrained(cls, pretrained_model_or_path, filename=None, cache_dir=None, local_files_only=False):
65
- filename = filename or "ControlNetHED.pth"
66
-
67
- if os.path.isdir(pretrained_model_or_path):
68
- model_path = os.path.join(pretrained_model_or_path, filename)
69
- else:
70
- model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
71
-
72
- netNetwork = ControlNetHED_Apache2()
73
- netNetwork.load_state_dict(torch.load(model_path, map_location='cpu'))
74
- netNetwork.float().eval()
75
-
76
- return cls(netNetwork)
77
-
78
- def to(self, device):
79
- self.netNetwork.to(device)
80
- return self
81
-
82
- def __call__(self, input_image, detect_resolution=512, image_resolution=512, safe=False, output_type="pil", scribble=False, **kwargs):
83
- if "return_pil" in kwargs:
84
- warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
85
- output_type = "pil" if kwargs["return_pil"] else "np"
86
- if type(output_type) is bool:
87
- warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
88
- if output_type:
89
- output_type = "pil"
90
-
91
- device = next(iter(self.netNetwork.parameters())).device
92
- if not isinstance(input_image, np.ndarray):
93
- input_image = np.array(input_image, dtype=np.uint8)
94
-
95
- input_image = HWC3(input_image)
96
- input_image = resize_image(input_image, detect_resolution)
97
-
98
- assert input_image.ndim == 3
99
- H, W, C = input_image.shape
100
- with torch.no_grad():
101
- image_hed = torch.from_numpy(input_image.copy()).float().to(device)
102
- image_hed = rearrange(image_hed, 'h w c -> 1 c h w')
103
- edges = self.netNetwork(image_hed)
104
- edges = [e.detach().cpu().numpy().astype(np.float32)[0, 0] for e in edges]
105
- edges = [cv2.resize(e, (W, H), interpolation=cv2.INTER_LINEAR) for e in edges]
106
- edges = np.stack(edges, axis=2)
107
- edge = 1 / (1 + np.exp(-np.mean(edges, axis=2).astype(np.float64)))
108
- if safe:
109
- edge = safe_step(edge)
110
- edge = (edge * 255.0).clip(0, 255).astype(np.uint8)
111
-
112
- detected_map = edge
113
- detected_map = HWC3(detected_map)
114
-
115
- img = resize_image(input_image, image_resolution)
116
- H, W, C = img.shape
117
-
118
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
119
-
120
- if scribble:
121
- detected_map = nms(detected_map, 127, 3.0)
122
- detected_map = cv2.GaussianBlur(detected_map, (0, 0), 3.0)
123
- detected_map[detected_map > 4] = 255
124
- detected_map[detected_map < 255] = 0
125
-
126
- if output_type == "pil":
127
- detected_map = Image.fromarray(detected_map)
128
-
129
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/__init__.py DELETED
@@ -1,118 +0,0 @@
1
- import os
2
-
3
- import cv2
4
- import numpy as np
5
- import torch
6
- from huggingface_hub import hf_hub_download
7
- from PIL import Image
8
-
9
- from ..util import HWC3, resize_image
10
- from .leres.depthmap import estimateboost, estimateleres
11
- from .leres.multi_depth_model_woauxi import RelDepthModel
12
- from .leres.net_tools import strip_prefix_if_present
13
- from .pix2pix.models.pix2pix4depth_model import Pix2Pix4DepthModel
14
- from .pix2pix.options.test_options import TestOptions
15
-
16
-
17
- class LeresDetector:
18
- def __init__(self, model, pix2pixmodel):
19
- self.model = model
20
- self.pix2pixmodel = pix2pixmodel
21
-
22
- @classmethod
23
- def from_pretrained(cls, pretrained_model_or_path, filename=None, pix2pix_filename=None, cache_dir=None, local_files_only=False):
24
- filename = filename or "res101.pth"
25
- pix2pix_filename = pix2pix_filename or "latest_net_G.pth"
26
-
27
- if os.path.isdir(pretrained_model_or_path):
28
- model_path = os.path.join(pretrained_model_or_path, filename)
29
- else:
30
- model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
31
-
32
- checkpoint = torch.load(model_path, map_location=torch.device('cpu'))
33
-
34
- model = RelDepthModel(backbone='resnext101')
35
- model.load_state_dict(strip_prefix_if_present(checkpoint['depth_model'], "module."), strict=True)
36
- del checkpoint
37
-
38
- if os.path.isdir(pretrained_model_or_path):
39
- model_path = os.path.join(pretrained_model_or_path, pix2pix_filename)
40
- else:
41
- model_path = hf_hub_download(pretrained_model_or_path, pix2pix_filename, cache_dir=cache_dir, local_files_only=local_files_only)
42
-
43
- opt = TestOptions().parse()
44
- if not torch.cuda.is_available():
45
- opt.gpu_ids = [] # cpu mode
46
- pix2pixmodel = Pix2Pix4DepthModel(opt)
47
- pix2pixmodel.save_dir = os.path.dirname(model_path)
48
- pix2pixmodel.load_networks('latest')
49
- pix2pixmodel.eval()
50
-
51
- return cls(model, pix2pixmodel)
52
-
53
- def to(self, device):
54
- self.model.to(device)
55
- # TODO - refactor pix2pix implementation to support device migration
56
- # self.pix2pixmodel.to(device)
57
- return self
58
-
59
- def __call__(self, input_image, thr_a=0, thr_b=0, boost=False, detect_resolution=512, image_resolution=512, output_type="pil"):
60
- device = next(iter(self.model.parameters())).device
61
- if not isinstance(input_image, np.ndarray):
62
- input_image = np.array(input_image, dtype=np.uint8)
63
-
64
- input_image = HWC3(input_image)
65
- input_image = resize_image(input_image, detect_resolution)
66
-
67
- assert input_image.ndim == 3
68
- height, width, dim = input_image.shape
69
-
70
- with torch.no_grad():
71
-
72
- if boost:
73
- depth = estimateboost(input_image, self.model, 0, self.pix2pixmodel, max(width, height))
74
- else:
75
- depth = estimateleres(input_image, self.model, width, height)
76
-
77
- numbytes=2
78
- depth_min = depth.min()
79
- depth_max = depth.max()
80
- max_val = (2**(8*numbytes))-1
81
-
82
- # check output before normalizing and mapping to 16 bit
83
- if depth_max - depth_min > np.finfo("float").eps:
84
- out = max_val * (depth - depth_min) / (depth_max - depth_min)
85
- else:
86
- out = np.zeros(depth.shape)
87
-
88
- # single channel, 16 bit image
89
- depth_image = out.astype("uint16")
90
-
91
- # convert to uint8
92
- depth_image = cv2.convertScaleAbs(depth_image, alpha=(255.0/65535.0))
93
-
94
- # remove near
95
- if thr_a != 0:
96
- thr_a = ((thr_a/100)*255)
97
- depth_image = cv2.threshold(depth_image, thr_a, 255, cv2.THRESH_TOZERO)[1]
98
-
99
- # invert image
100
- depth_image = cv2.bitwise_not(depth_image)
101
-
102
- # remove bg
103
- if thr_b != 0:
104
- thr_b = ((thr_b/100)*255)
105
- depth_image = cv2.threshold(depth_image, thr_b, 255, cv2.THRESH_TOZERO)[1]
106
-
107
- detected_map = depth_image
108
- detected_map = HWC3(detected_map)
109
-
110
- img = resize_image(input_image, image_resolution)
111
- H, W, C = img.shape
112
-
113
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
114
-
115
- if output_type == "pil":
116
- detected_map = Image.fromarray(detected_map)
117
-
118
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/leres/Resnet.py DELETED
@@ -1,199 +0,0 @@
1
- import torch.nn as nn
2
- import torch.nn as NN
3
-
4
- __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
5
- 'resnet152']
6
-
7
-
8
- model_urls = {
9
- 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
10
- 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
11
- 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
12
- 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
13
- 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
14
- }
15
-
16
-
17
- def conv3x3(in_planes, out_planes, stride=1):
18
- """3x3 convolution with padding"""
19
- return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
20
- padding=1, bias=False)
21
-
22
-
23
- class BasicBlock(nn.Module):
24
- expansion = 1
25
-
26
- def __init__(self, inplanes, planes, stride=1, downsample=None):
27
- super(BasicBlock, self).__init__()
28
- self.conv1 = conv3x3(inplanes, planes, stride)
29
- self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d
30
- self.relu = nn.ReLU(inplace=True)
31
- self.conv2 = conv3x3(planes, planes)
32
- self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d
33
- self.downsample = downsample
34
- self.stride = stride
35
-
36
- def forward(self, x):
37
- residual = x
38
-
39
- out = self.conv1(x)
40
- out = self.bn1(out)
41
- out = self.relu(out)
42
-
43
- out = self.conv2(out)
44
- out = self.bn2(out)
45
-
46
- if self.downsample is not None:
47
- residual = self.downsample(x)
48
-
49
- out += residual
50
- out = self.relu(out)
51
-
52
- return out
53
-
54
-
55
- class Bottleneck(nn.Module):
56
- expansion = 4
57
-
58
- def __init__(self, inplanes, planes, stride=1, downsample=None):
59
- super(Bottleneck, self).__init__()
60
- self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
61
- self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d
62
- self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
63
- padding=1, bias=False)
64
- self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d
65
- self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
66
- self.bn3 = NN.BatchNorm2d(planes * self.expansion) #NN.BatchNorm2d
67
- self.relu = nn.ReLU(inplace=True)
68
- self.downsample = downsample
69
- self.stride = stride
70
-
71
- def forward(self, x):
72
- residual = x
73
-
74
- out = self.conv1(x)
75
- out = self.bn1(out)
76
- out = self.relu(out)
77
-
78
- out = self.conv2(out)
79
- out = self.bn2(out)
80
- out = self.relu(out)
81
-
82
- out = self.conv3(out)
83
- out = self.bn3(out)
84
-
85
- if self.downsample is not None:
86
- residual = self.downsample(x)
87
-
88
- out += residual
89
- out = self.relu(out)
90
-
91
- return out
92
-
93
-
94
- class ResNet(nn.Module):
95
-
96
- def __init__(self, block, layers, num_classes=1000):
97
- self.inplanes = 64
98
- super(ResNet, self).__init__()
99
- self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
100
- bias=False)
101
- self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d
102
- self.relu = nn.ReLU(inplace=True)
103
- self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
104
- self.layer1 = self._make_layer(block, 64, layers[0])
105
- self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
106
- self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
107
- self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
108
- #self.avgpool = nn.AvgPool2d(7, stride=1)
109
- #self.fc = nn.Linear(512 * block.expansion, num_classes)
110
-
111
- for m in self.modules():
112
- if isinstance(m, nn.Conv2d):
113
- nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
114
- elif isinstance(m, nn.BatchNorm2d):
115
- nn.init.constant_(m.weight, 1)
116
- nn.init.constant_(m.bias, 0)
117
-
118
- def _make_layer(self, block, planes, blocks, stride=1):
119
- downsample = None
120
- if stride != 1 or self.inplanes != planes * block.expansion:
121
- downsample = nn.Sequential(
122
- nn.Conv2d(self.inplanes, planes * block.expansion,
123
- kernel_size=1, stride=stride, bias=False),
124
- NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d
125
- )
126
-
127
- layers = []
128
- layers.append(block(self.inplanes, planes, stride, downsample))
129
- self.inplanes = planes * block.expansion
130
- for i in range(1, blocks):
131
- layers.append(block(self.inplanes, planes))
132
-
133
- return nn.Sequential(*layers)
134
-
135
- def forward(self, x):
136
- features = []
137
-
138
- x = self.conv1(x)
139
- x = self.bn1(x)
140
- x = self.relu(x)
141
- x = self.maxpool(x)
142
-
143
- x = self.layer1(x)
144
- features.append(x)
145
- x = self.layer2(x)
146
- features.append(x)
147
- x = self.layer3(x)
148
- features.append(x)
149
- x = self.layer4(x)
150
- features.append(x)
151
-
152
- return features
153
-
154
-
155
- def resnet18(pretrained=True, **kwargs):
156
- """Constructs a ResNet-18 model.
157
- Args:
158
- pretrained (bool): If True, returns a model pre-trained on ImageNet
159
- """
160
- model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
161
- return model
162
-
163
-
164
- def resnet34(pretrained=True, **kwargs):
165
- """Constructs a ResNet-34 model.
166
- Args:
167
- pretrained (bool): If True, returns a model pre-trained on ImageNet
168
- """
169
- model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
170
- return model
171
-
172
-
173
- def resnet50(pretrained=True, **kwargs):
174
- """Constructs a ResNet-50 model.
175
- Args:
176
- pretrained (bool): If True, returns a model pre-trained on ImageNet
177
- """
178
- model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
179
-
180
- return model
181
-
182
-
183
- def resnet101(pretrained=True, **kwargs):
184
- """Constructs a ResNet-101 model.
185
- Args:
186
- pretrained (bool): If True, returns a model pre-trained on ImageNet
187
- """
188
- model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
189
-
190
- return model
191
-
192
-
193
- def resnet152(pretrained=True, **kwargs):
194
- """Constructs a ResNet-152 model.
195
- Args:
196
- pretrained (bool): If True, returns a model pre-trained on ImageNet
197
- """
198
- model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
199
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/leres/Resnext_torch.py DELETED
@@ -1,237 +0,0 @@
1
- #!/usr/bin/env python
2
- # coding: utf-8
3
- import torch.nn as nn
4
-
5
- try:
6
- from urllib import urlretrieve
7
- except ImportError:
8
- from urllib.request import urlretrieve
9
-
10
- __all__ = ['resnext101_32x8d']
11
-
12
-
13
- model_urls = {
14
- 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
15
- 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
16
- }
17
-
18
-
19
- def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
20
- """3x3 convolution with padding"""
21
- return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
22
- padding=dilation, groups=groups, bias=False, dilation=dilation)
23
-
24
-
25
- def conv1x1(in_planes, out_planes, stride=1):
26
- """1x1 convolution"""
27
- return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
28
-
29
-
30
- class BasicBlock(nn.Module):
31
- expansion = 1
32
-
33
- def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
34
- base_width=64, dilation=1, norm_layer=None):
35
- super(BasicBlock, self).__init__()
36
- if norm_layer is None:
37
- norm_layer = nn.BatchNorm2d
38
- if groups != 1 or base_width != 64:
39
- raise ValueError('BasicBlock only supports groups=1 and base_width=64')
40
- if dilation > 1:
41
- raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
42
- # Both self.conv1 and self.downsample layers downsample the input when stride != 1
43
- self.conv1 = conv3x3(inplanes, planes, stride)
44
- self.bn1 = norm_layer(planes)
45
- self.relu = nn.ReLU(inplace=True)
46
- self.conv2 = conv3x3(planes, planes)
47
- self.bn2 = norm_layer(planes)
48
- self.downsample = downsample
49
- self.stride = stride
50
-
51
- def forward(self, x):
52
- identity = x
53
-
54
- out = self.conv1(x)
55
- out = self.bn1(out)
56
- out = self.relu(out)
57
-
58
- out = self.conv2(out)
59
- out = self.bn2(out)
60
-
61
- if self.downsample is not None:
62
- identity = self.downsample(x)
63
-
64
- out += identity
65
- out = self.relu(out)
66
-
67
- return out
68
-
69
-
70
- class Bottleneck(nn.Module):
71
- # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
72
- # while original implementation places the stride at the first 1x1 convolution(self.conv1)
73
- # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
74
- # This variant is also known as ResNet V1.5 and improves accuracy according to
75
- # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
76
-
77
- expansion = 4
78
-
79
- def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
80
- base_width=64, dilation=1, norm_layer=None):
81
- super(Bottleneck, self).__init__()
82
- if norm_layer is None:
83
- norm_layer = nn.BatchNorm2d
84
- width = int(planes * (base_width / 64.)) * groups
85
- # Both self.conv2 and self.downsample layers downsample the input when stride != 1
86
- self.conv1 = conv1x1(inplanes, width)
87
- self.bn1 = norm_layer(width)
88
- self.conv2 = conv3x3(width, width, stride, groups, dilation)
89
- self.bn2 = norm_layer(width)
90
- self.conv3 = conv1x1(width, planes * self.expansion)
91
- self.bn3 = norm_layer(planes * self.expansion)
92
- self.relu = nn.ReLU(inplace=True)
93
- self.downsample = downsample
94
- self.stride = stride
95
-
96
- def forward(self, x):
97
- identity = x
98
-
99
- out = self.conv1(x)
100
- out = self.bn1(out)
101
- out = self.relu(out)
102
-
103
- out = self.conv2(out)
104
- out = self.bn2(out)
105
- out = self.relu(out)
106
-
107
- out = self.conv3(out)
108
- out = self.bn3(out)
109
-
110
- if self.downsample is not None:
111
- identity = self.downsample(x)
112
-
113
- out += identity
114
- out = self.relu(out)
115
-
116
- return out
117
-
118
-
119
- class ResNet(nn.Module):
120
-
121
- def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
122
- groups=1, width_per_group=64, replace_stride_with_dilation=None,
123
- norm_layer=None):
124
- super(ResNet, self).__init__()
125
- if norm_layer is None:
126
- norm_layer = nn.BatchNorm2d
127
- self._norm_layer = norm_layer
128
-
129
- self.inplanes = 64
130
- self.dilation = 1
131
- if replace_stride_with_dilation is None:
132
- # each element in the tuple indicates if we should replace
133
- # the 2x2 stride with a dilated convolution instead
134
- replace_stride_with_dilation = [False, False, False]
135
- if len(replace_stride_with_dilation) != 3:
136
- raise ValueError("replace_stride_with_dilation should be None "
137
- "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
138
- self.groups = groups
139
- self.base_width = width_per_group
140
- self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
141
- bias=False)
142
- self.bn1 = norm_layer(self.inplanes)
143
- self.relu = nn.ReLU(inplace=True)
144
- self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
145
- self.layer1 = self._make_layer(block, 64, layers[0])
146
- self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
147
- dilate=replace_stride_with_dilation[0])
148
- self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
149
- dilate=replace_stride_with_dilation[1])
150
- self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
151
- dilate=replace_stride_with_dilation[2])
152
- #self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
153
- #self.fc = nn.Linear(512 * block.expansion, num_classes)
154
-
155
- for m in self.modules():
156
- if isinstance(m, nn.Conv2d):
157
- nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
158
- elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
159
- nn.init.constant_(m.weight, 1)
160
- nn.init.constant_(m.bias, 0)
161
-
162
- # Zero-initialize the last BN in each residual branch,
163
- # so that the residual branch starts with zeros, and each residual block behaves like an identity.
164
- # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
165
- if zero_init_residual:
166
- for m in self.modules():
167
- if isinstance(m, Bottleneck):
168
- nn.init.constant_(m.bn3.weight, 0)
169
- elif isinstance(m, BasicBlock):
170
- nn.init.constant_(m.bn2.weight, 0)
171
-
172
- def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
173
- norm_layer = self._norm_layer
174
- downsample = None
175
- previous_dilation = self.dilation
176
- if dilate:
177
- self.dilation *= stride
178
- stride = 1
179
- if stride != 1 or self.inplanes != planes * block.expansion:
180
- downsample = nn.Sequential(
181
- conv1x1(self.inplanes, planes * block.expansion, stride),
182
- norm_layer(planes * block.expansion),
183
- )
184
-
185
- layers = []
186
- layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
187
- self.base_width, previous_dilation, norm_layer))
188
- self.inplanes = planes * block.expansion
189
- for _ in range(1, blocks):
190
- layers.append(block(self.inplanes, planes, groups=self.groups,
191
- base_width=self.base_width, dilation=self.dilation,
192
- norm_layer=norm_layer))
193
-
194
- return nn.Sequential(*layers)
195
-
196
- def _forward_impl(self, x):
197
- # See note [TorchScript super()]
198
- features = []
199
- x = self.conv1(x)
200
- x = self.bn1(x)
201
- x = self.relu(x)
202
- x = self.maxpool(x)
203
-
204
- x = self.layer1(x)
205
- features.append(x)
206
-
207
- x = self.layer2(x)
208
- features.append(x)
209
-
210
- x = self.layer3(x)
211
- features.append(x)
212
-
213
- x = self.layer4(x)
214
- features.append(x)
215
-
216
- #x = self.avgpool(x)
217
- #x = torch.flatten(x, 1)
218
- #x = self.fc(x)
219
-
220
- return features
221
-
222
- def forward(self, x):
223
- return self._forward_impl(x)
224
-
225
-
226
-
227
- def resnext101_32x8d(pretrained=True, **kwargs):
228
- """Constructs a ResNet-152 model.
229
- Args:
230
- pretrained (bool): If True, returns a model pre-trained on ImageNet
231
- """
232
- kwargs['groups'] = 32
233
- kwargs['width_per_group'] = 8
234
-
235
- model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
236
- return model
237
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/leres/__init__.py DELETED
File without changes
controlnet_aux_local/leres/leres/depthmap.py DELETED
@@ -1,548 +0,0 @@
1
- # Author: thygate
2
- # https://github.com/thygate/stable-diffusion-webui-depthmap-script
3
-
4
- import gc
5
- from operator import getitem
6
-
7
- import cv2
8
- import numpy as np
9
- import skimage.measure
10
- import torch
11
- from torchvision.transforms import transforms
12
-
13
- from ...util import torch_gc
14
-
15
- whole_size_threshold = 1600 # R_max from the paper
16
- pix2pixsize = 1024
17
-
18
- def scale_torch(img):
19
- """
20
- Scale the image and output it in torch.tensor.
21
- :param img: input rgb is in shape [H, W, C], input depth/disp is in shape [H, W]
22
- :param scale: the scale factor. float
23
- :return: img. [C, H, W]
24
- """
25
- if len(img.shape) == 2:
26
- img = img[np.newaxis, :, :]
27
- if img.shape[2] == 3:
28
- transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406) , (0.229, 0.224, 0.225) )])
29
- img = transform(img.astype(np.float32))
30
- else:
31
- img = img.astype(np.float32)
32
- img = torch.from_numpy(img)
33
- return img
34
-
35
- def estimateleres(img, model, w, h):
36
- device = next(iter(model.parameters())).device
37
- # leres transform input
38
- rgb_c = img[:, :, ::-1].copy()
39
- A_resize = cv2.resize(rgb_c, (w, h))
40
- img_torch = scale_torch(A_resize)[None, :, :, :]
41
-
42
- # compute
43
- with torch.no_grad():
44
- img_torch = img_torch.to(device)
45
- prediction = model.depth_model(img_torch)
46
-
47
- prediction = prediction.squeeze().cpu().numpy()
48
- prediction = cv2.resize(prediction, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_CUBIC)
49
-
50
- return prediction
51
-
52
- def generatemask(size):
53
- # Generates a Guassian mask
54
- mask = np.zeros(size, dtype=np.float32)
55
- sigma = int(size[0]/16)
56
- k_size = int(2 * np.ceil(2 * int(size[0]/16)) + 1)
57
- mask[int(0.15*size[0]):size[0] - int(0.15*size[0]), int(0.15*size[1]): size[1] - int(0.15*size[1])] = 1
58
- mask = cv2.GaussianBlur(mask, (int(k_size), int(k_size)), sigma)
59
- mask = (mask - mask.min()) / (mask.max() - mask.min())
60
- mask = mask.astype(np.float32)
61
- return mask
62
-
63
- def resizewithpool(img, size):
64
- i_size = img.shape[0]
65
- n = int(np.floor(i_size/size))
66
-
67
- out = skimage.measure.block_reduce(img, (n, n), np.max)
68
- return out
69
-
70
- def rgb2gray(rgb):
71
- # Converts rgb to gray
72
- return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140])
73
-
74
- def calculateprocessingres(img, basesize, confidence=0.1, scale_threshold=3, whole_size_threshold=3000):
75
- # Returns the R_x resolution described in section 5 of the main paper.
76
-
77
- # Parameters:
78
- # img :input rgb image
79
- # basesize : size the dilation kernel which is equal to receptive field of the network.
80
- # confidence: value of x in R_x; allowed percentage of pixels that are not getting any contextual cue.
81
- # scale_threshold: maximum allowed upscaling on the input image ; it has been set to 3.
82
- # whole_size_threshold: maximum allowed resolution. (R_max from section 6 of the main paper)
83
-
84
- # Returns:
85
- # outputsize_scale*speed_scale :The computed R_x resolution
86
- # patch_scale: K parameter from section 6 of the paper
87
-
88
- # speed scale parameter is to process every image in a smaller size to accelerate the R_x resolution search
89
- speed_scale = 32
90
- image_dim = int(min(img.shape[0:2]))
91
-
92
- gray = rgb2gray(img)
93
- grad = np.abs(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)) + np.abs(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3))
94
- grad = cv2.resize(grad, (image_dim, image_dim), cv2.INTER_AREA)
95
-
96
- # thresholding the gradient map to generate the edge-map as a proxy of the contextual cues
97
- m = grad.min()
98
- M = grad.max()
99
- middle = m + (0.4 * (M - m))
100
- grad[grad < middle] = 0
101
- grad[grad >= middle] = 1
102
-
103
- # dilation kernel with size of the receptive field
104
- kernel = np.ones((int(basesize/speed_scale), int(basesize/speed_scale)), float)
105
- # dilation kernel with size of the a quarter of receptive field used to compute k
106
- # as described in section 6 of main paper
107
- kernel2 = np.ones((int(basesize / (4*speed_scale)), int(basesize / (4*speed_scale))), float)
108
-
109
- # Output resolution limit set by the whole_size_threshold and scale_threshold.
110
- threshold = min(whole_size_threshold, scale_threshold * max(img.shape[:2]))
111
-
112
- outputsize_scale = basesize / speed_scale
113
- for p_size in range(int(basesize/speed_scale), int(threshold/speed_scale), int(basesize / (2*speed_scale))):
114
- grad_resized = resizewithpool(grad, p_size)
115
- grad_resized = cv2.resize(grad_resized, (p_size, p_size), cv2.INTER_NEAREST)
116
- grad_resized[grad_resized >= 0.5] = 1
117
- grad_resized[grad_resized < 0.5] = 0
118
-
119
- dilated = cv2.dilate(grad_resized, kernel, iterations=1)
120
- meanvalue = (1-dilated).mean()
121
- if meanvalue > confidence:
122
- break
123
- else:
124
- outputsize_scale = p_size
125
-
126
- grad_region = cv2.dilate(grad_resized, kernel2, iterations=1)
127
- patch_scale = grad_region.mean()
128
-
129
- return int(outputsize_scale*speed_scale), patch_scale
130
-
131
- # Generate a double-input depth estimation
132
- def doubleestimate(img, size1, size2, pix2pixsize, model, net_type, pix2pixmodel):
133
- # Generate the low resolution estimation
134
- estimate1 = singleestimate(img, size1, model, net_type)
135
- # Resize to the inference size of merge network.
136
- estimate1 = cv2.resize(estimate1, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC)
137
-
138
- # Generate the high resolution estimation
139
- estimate2 = singleestimate(img, size2, model, net_type)
140
- # Resize to the inference size of merge network.
141
- estimate2 = cv2.resize(estimate2, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC)
142
-
143
- # Inference on the merge model
144
- pix2pixmodel.set_input(estimate1, estimate2)
145
- pix2pixmodel.test()
146
- visuals = pix2pixmodel.get_current_visuals()
147
- prediction_mapped = visuals['fake_B']
148
- prediction_mapped = (prediction_mapped+1)/2
149
- prediction_mapped = (prediction_mapped - torch.min(prediction_mapped)) / (
150
- torch.max(prediction_mapped) - torch.min(prediction_mapped))
151
- prediction_mapped = prediction_mapped.squeeze().cpu().numpy()
152
-
153
- return prediction_mapped
154
-
155
- # Generate a single-input depth estimation
156
- def singleestimate(img, msize, model, net_type):
157
- # if net_type == 0:
158
- return estimateleres(img, model, msize, msize)
159
- # else:
160
- # return estimatemidasBoost(img, model, msize, msize)
161
-
162
- def applyGridpatch(blsize, stride, img, box):
163
- # Extract a simple grid patch.
164
- counter1 = 0
165
- patch_bound_list = {}
166
- for k in range(blsize, img.shape[1] - blsize, stride):
167
- for j in range(blsize, img.shape[0] - blsize, stride):
168
- patch_bound_list[str(counter1)] = {}
169
- patchbounds = [j - blsize, k - blsize, j - blsize + 2 * blsize, k - blsize + 2 * blsize]
170
- patch_bound = [box[0] + patchbounds[1], box[1] + patchbounds[0], patchbounds[3] - patchbounds[1],
171
- patchbounds[2] - patchbounds[0]]
172
- patch_bound_list[str(counter1)]['rect'] = patch_bound
173
- patch_bound_list[str(counter1)]['size'] = patch_bound[2]
174
- counter1 = counter1 + 1
175
- return patch_bound_list
176
-
177
- # Generating local patches to perform the local refinement described in section 6 of the main paper.
178
- def generatepatchs(img, base_size):
179
-
180
- # Compute the gradients as a proxy of the contextual cues.
181
- img_gray = rgb2gray(img)
182
- whole_grad = np.abs(cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=3)) +\
183
- np.abs(cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=3))
184
-
185
- threshold = whole_grad[whole_grad > 0].mean()
186
- whole_grad[whole_grad < threshold] = 0
187
-
188
- # We use the integral image to speed-up the evaluation of the amount of gradients for each patch.
189
- gf = whole_grad.sum()/len(whole_grad.reshape(-1))
190
- grad_integral_image = cv2.integral(whole_grad)
191
-
192
- # Variables are selected such that the initial patch size would be the receptive field size
193
- # and the stride is set to 1/3 of the receptive field size.
194
- blsize = int(round(base_size/2))
195
- stride = int(round(blsize*0.75))
196
-
197
- # Get initial Grid
198
- patch_bound_list = applyGridpatch(blsize, stride, img, [0, 0, 0, 0])
199
-
200
- # Refine initial Grid of patches by discarding the flat (in terms of gradients of the rgb image) ones. Refine
201
- # each patch size to ensure that there will be enough depth cues for the network to generate a consistent depth map.
202
- print("Selecting patches ...")
203
- patch_bound_list = adaptiveselection(grad_integral_image, patch_bound_list, gf)
204
-
205
- # Sort the patch list to make sure the merging operation will be done with the correct order: starting from biggest
206
- # patch
207
- patchset = sorted(patch_bound_list.items(), key=lambda x: getitem(x[1], 'size'), reverse=True)
208
- return patchset
209
-
210
- def getGF_fromintegral(integralimage, rect):
211
- # Computes the gradient density of a given patch from the gradient integral image.
212
- x1 = rect[1]
213
- x2 = rect[1]+rect[3]
214
- y1 = rect[0]
215
- y2 = rect[0]+rect[2]
216
- value = integralimage[x2, y2]-integralimage[x1, y2]-integralimage[x2, y1]+integralimage[x1, y1]
217
- return value
218
-
219
- # Adaptively select patches
220
- def adaptiveselection(integral_grad, patch_bound_list, gf):
221
- patchlist = {}
222
- count = 0
223
- height, width = integral_grad.shape
224
-
225
- search_step = int(32/factor)
226
-
227
- # Go through all patches
228
- for c in range(len(patch_bound_list)):
229
- # Get patch
230
- bbox = patch_bound_list[str(c)]['rect']
231
-
232
- # Compute the amount of gradients present in the patch from the integral image.
233
- cgf = getGF_fromintegral(integral_grad, bbox)/(bbox[2]*bbox[3])
234
-
235
- # Check if patching is beneficial by comparing the gradient density of the patch to
236
- # the gradient density of the whole image
237
- if cgf >= gf:
238
- bbox_test = bbox.copy()
239
- patchlist[str(count)] = {}
240
-
241
- # Enlarge each patch until the gradient density of the patch is equal
242
- # to the whole image gradient density
243
- while True:
244
-
245
- bbox_test[0] = bbox_test[0] - int(search_step/2)
246
- bbox_test[1] = bbox_test[1] - int(search_step/2)
247
-
248
- bbox_test[2] = bbox_test[2] + search_step
249
- bbox_test[3] = bbox_test[3] + search_step
250
-
251
- # Check if we are still within the image
252
- if bbox_test[0] < 0 or bbox_test[1] < 0 or bbox_test[1] + bbox_test[3] >= height \
253
- or bbox_test[0] + bbox_test[2] >= width:
254
- break
255
-
256
- # Compare gradient density
257
- cgf = getGF_fromintegral(integral_grad, bbox_test)/(bbox_test[2]*bbox_test[3])
258
- if cgf < gf:
259
- break
260
- bbox = bbox_test.copy()
261
-
262
- # Add patch to selected patches
263
- patchlist[str(count)]['rect'] = bbox
264
- patchlist[str(count)]['size'] = bbox[2]
265
- count = count + 1
266
-
267
- # Return selected patches
268
- return patchlist
269
-
270
- def impatch(image, rect):
271
- # Extract the given patch pixels from a given image.
272
- w1 = rect[0]
273
- h1 = rect[1]
274
- w2 = w1 + rect[2]
275
- h2 = h1 + rect[3]
276
- image_patch = image[h1:h2, w1:w2]
277
- return image_patch
278
-
279
- class ImageandPatchs:
280
- def __init__(self, root_dir, name, patchsinfo, rgb_image, scale=1):
281
- self.root_dir = root_dir
282
- self.patchsinfo = patchsinfo
283
- self.name = name
284
- self.patchs = patchsinfo
285
- self.scale = scale
286
-
287
- self.rgb_image = cv2.resize(rgb_image, (round(rgb_image.shape[1]*scale), round(rgb_image.shape[0]*scale)),
288
- interpolation=cv2.INTER_CUBIC)
289
-
290
- self.do_have_estimate = False
291
- self.estimation_updated_image = None
292
- self.estimation_base_image = None
293
-
294
- def __len__(self):
295
- return len(self.patchs)
296
-
297
- def set_base_estimate(self, est):
298
- self.estimation_base_image = est
299
- if self.estimation_updated_image is not None:
300
- self.do_have_estimate = True
301
-
302
- def set_updated_estimate(self, est):
303
- self.estimation_updated_image = est
304
- if self.estimation_base_image is not None:
305
- self.do_have_estimate = True
306
-
307
- def __getitem__(self, index):
308
- patch_id = int(self.patchs[index][0])
309
- rect = np.array(self.patchs[index][1]['rect'])
310
- msize = self.patchs[index][1]['size']
311
-
312
- ## applying scale to rect:
313
- rect = np.round(rect * self.scale)
314
- rect = rect.astype('int')
315
- msize = round(msize * self.scale)
316
-
317
- patch_rgb = impatch(self.rgb_image, rect)
318
- if self.do_have_estimate:
319
- patch_whole_estimate_base = impatch(self.estimation_base_image, rect)
320
- patch_whole_estimate_updated = impatch(self.estimation_updated_image, rect)
321
- return {'patch_rgb': patch_rgb, 'patch_whole_estimate_base': patch_whole_estimate_base,
322
- 'patch_whole_estimate_updated': patch_whole_estimate_updated, 'rect': rect,
323
- 'size': msize, 'id': patch_id}
324
- else:
325
- return {'patch_rgb': patch_rgb, 'rect': rect, 'size': msize, 'id': patch_id}
326
-
327
- def print_options(self, opt):
328
- """Print and save options
329
-
330
- It will print both current options and default values(if different).
331
- It will save options into a text file / [checkpoints_dir] / opt.txt
332
- """
333
- message = ''
334
- message += '----------------- Options ---------------\n'
335
- for k, v in sorted(vars(opt).items()):
336
- comment = ''
337
- default = self.parser.get_default(k)
338
- if v != default:
339
- comment = '\t[default: %s]' % str(default)
340
- message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment)
341
- message += '----------------- End -------------------'
342
- print(message)
343
-
344
- # save to the disk
345
- """
346
- expr_dir = os.path.join(opt.checkpoints_dir, opt.name)
347
- util.mkdirs(expr_dir)
348
- file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase))
349
- with open(file_name, 'wt') as opt_file:
350
- opt_file.write(message)
351
- opt_file.write('\n')
352
- """
353
-
354
- def parse(self):
355
- """Parse our options, create checkpoints directory suffix, and set up gpu device."""
356
- opt = self.gather_options()
357
- opt.isTrain = self.isTrain # train or test
358
-
359
- # process opt.suffix
360
- if opt.suffix:
361
- suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''
362
- opt.name = opt.name + suffix
363
-
364
- #self.print_options(opt)
365
-
366
- # set gpu ids
367
- str_ids = opt.gpu_ids.split(',')
368
- opt.gpu_ids = []
369
- for str_id in str_ids:
370
- id = int(str_id)
371
- if id >= 0:
372
- opt.gpu_ids.append(id)
373
- #if len(opt.gpu_ids) > 0:
374
- # torch.cuda.set_device(opt.gpu_ids[0])
375
-
376
- self.opt = opt
377
- return self.opt
378
-
379
-
380
- def estimateboost(img, model, model_type, pix2pixmodel, max_res=512, depthmap_script_boost_rmax=None):
381
- global whole_size_threshold
382
-
383
- # get settings
384
- if depthmap_script_boost_rmax:
385
- whole_size_threshold = depthmap_script_boost_rmax
386
-
387
- if model_type == 0: #leres
388
- net_receptive_field_size = 448
389
- patch_netsize = 2 * net_receptive_field_size
390
- elif model_type == 1: #dpt_beit_large_512
391
- net_receptive_field_size = 512
392
- patch_netsize = 2 * net_receptive_field_size
393
- else: #other midas
394
- net_receptive_field_size = 384
395
- patch_netsize = 2 * net_receptive_field_size
396
-
397
- gc.collect()
398
- torch_gc()
399
-
400
- # Generate mask used to smoothly blend the local pathc estimations to the base estimate.
401
- # It is arbitrarily large to avoid artifacts during rescaling for each crop.
402
- mask_org = generatemask((3000, 3000))
403
- mask = mask_org.copy()
404
-
405
- # Value x of R_x defined in the section 5 of the main paper.
406
- r_threshold_value = 0.2
407
- #if R0:
408
- # r_threshold_value = 0
409
-
410
- input_resolution = img.shape
411
- scale_threshold = 3 # Allows up-scaling with a scale up to 3
412
-
413
- # Find the best input resolution R-x. The resolution search described in section 5-double estimation of the main paper and section B of the
414
- # supplementary material.
415
- whole_image_optimal_size, patch_scale = calculateprocessingres(img, net_receptive_field_size, r_threshold_value, scale_threshold, whole_size_threshold)
416
-
417
- # print('wholeImage being processed in :', whole_image_optimal_size)
418
-
419
- # Generate the base estimate using the double estimation.
420
- whole_estimate = doubleestimate(img, net_receptive_field_size, whole_image_optimal_size, pix2pixsize, model, model_type, pix2pixmodel)
421
-
422
- # Compute the multiplier described in section 6 of the main paper to make sure our initial patch can select
423
- # small high-density regions of the image.
424
- global factor
425
- factor = max(min(1, 4 * patch_scale * whole_image_optimal_size / whole_size_threshold), 0.2)
426
- # print('Adjust factor is:', 1/factor)
427
-
428
- # Check if Local boosting is beneficial.
429
- if max_res < whole_image_optimal_size:
430
- # print("No Local boosting. Specified Max Res is smaller than R20, Returning doubleestimate result")
431
- return cv2.resize(whole_estimate, (input_resolution[1], input_resolution[0]), interpolation=cv2.INTER_CUBIC)
432
-
433
- # Compute the default target resolution.
434
- if img.shape[0] > img.shape[1]:
435
- a = 2 * whole_image_optimal_size
436
- b = round(2 * whole_image_optimal_size * img.shape[1] / img.shape[0])
437
- else:
438
- a = round(2 * whole_image_optimal_size * img.shape[0] / img.shape[1])
439
- b = 2 * whole_image_optimal_size
440
- b = int(round(b / factor))
441
- a = int(round(a / factor))
442
-
443
- """
444
- # recompute a, b and saturate to max res.
445
- if max(a,b) > max_res:
446
- print('Default Res is higher than max-res: Reducing final resolution')
447
- if img.shape[0] > img.shape[1]:
448
- a = max_res
449
- b = round(max_res * img.shape[1] / img.shape[0])
450
- else:
451
- a = round(max_res * img.shape[0] / img.shape[1])
452
- b = max_res
453
- b = int(b)
454
- a = int(a)
455
- """
456
-
457
- img = cv2.resize(img, (b, a), interpolation=cv2.INTER_CUBIC)
458
-
459
- # Extract selected patches for local refinement
460
- base_size = net_receptive_field_size * 2
461
- patchset = generatepatchs(img, base_size)
462
-
463
- # print('Target resolution: ', img.shape)
464
-
465
- # Computing a scale in case user prompted to generate the results as the same resolution of the input.
466
- # Notice that our method output resolution is independent of the input resolution and this parameter will only
467
- # enable a scaling operation during the local patch merge implementation to generate results with the same resolution
468
- # as the input.
469
- """
470
- if output_resolution == 1:
471
- mergein_scale = input_resolution[0] / img.shape[0]
472
- print('Dynamicly change merged-in resolution; scale:', mergein_scale)
473
- else:
474
- mergein_scale = 1
475
- """
476
- # always rescale to input res for now
477
- mergein_scale = input_resolution[0] / img.shape[0]
478
-
479
- imageandpatchs = ImageandPatchs('', '', patchset, img, mergein_scale)
480
- whole_estimate_resized = cv2.resize(whole_estimate, (round(img.shape[1]*mergein_scale),
481
- round(img.shape[0]*mergein_scale)), interpolation=cv2.INTER_CUBIC)
482
- imageandpatchs.set_base_estimate(whole_estimate_resized.copy())
483
- imageandpatchs.set_updated_estimate(whole_estimate_resized.copy())
484
-
485
- print('Resulting depthmap resolution will be :', whole_estimate_resized.shape[:2])
486
- print('Patches to process: '+str(len(imageandpatchs)))
487
-
488
- # Enumerate through all patches, generate their estimations and refining the base estimate.
489
- for patch_ind in range(len(imageandpatchs)):
490
-
491
- # Get patch information
492
- patch = imageandpatchs[patch_ind] # patch object
493
- patch_rgb = patch['patch_rgb'] # rgb patch
494
- patch_whole_estimate_base = patch['patch_whole_estimate_base'] # corresponding patch from base
495
- rect = patch['rect'] # patch size and location
496
- patch_id = patch['id'] # patch ID
497
- org_size = patch_whole_estimate_base.shape # the original size from the unscaled input
498
- print('\t Processing patch', patch_ind, '/', len(imageandpatchs)-1, '|', rect)
499
-
500
- # We apply double estimation for patches. The high resolution value is fixed to twice the receptive
501
- # field size of the network for patches to accelerate the process.
502
- patch_estimation = doubleestimate(patch_rgb, net_receptive_field_size, patch_netsize, pix2pixsize, model, model_type, pix2pixmodel)
503
- patch_estimation = cv2.resize(patch_estimation, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC)
504
- patch_whole_estimate_base = cv2.resize(patch_whole_estimate_base, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC)
505
-
506
- # Merging the patch estimation into the base estimate using our merge network:
507
- # We feed the patch estimation and the same region from the updated base estimate to the merge network
508
- # to generate the target estimate for the corresponding region.
509
- pix2pixmodel.set_input(patch_whole_estimate_base, patch_estimation)
510
-
511
- # Run merging network
512
- pix2pixmodel.test()
513
- visuals = pix2pixmodel.get_current_visuals()
514
-
515
- prediction_mapped = visuals['fake_B']
516
- prediction_mapped = (prediction_mapped+1)/2
517
- prediction_mapped = prediction_mapped.squeeze().cpu().numpy()
518
-
519
- mapped = prediction_mapped
520
-
521
- # We use a simple linear polynomial to make sure the result of the merge network would match the values of
522
- # base estimate
523
- p_coef = np.polyfit(mapped.reshape(-1), patch_whole_estimate_base.reshape(-1), deg=1)
524
- merged = np.polyval(p_coef, mapped.reshape(-1)).reshape(mapped.shape)
525
-
526
- merged = cv2.resize(merged, (org_size[1],org_size[0]), interpolation=cv2.INTER_CUBIC)
527
-
528
- # Get patch size and location
529
- w1 = rect[0]
530
- h1 = rect[1]
531
- w2 = w1 + rect[2]
532
- h2 = h1 + rect[3]
533
-
534
- # To speed up the implementation, we only generate the Gaussian mask once with a sufficiently large size
535
- # and resize it to our needed size while merging the patches.
536
- if mask.shape != org_size:
537
- mask = cv2.resize(mask_org, (org_size[1],org_size[0]), interpolation=cv2.INTER_LINEAR)
538
-
539
- tobemergedto = imageandpatchs.estimation_updated_image
540
-
541
- # Update the whole estimation:
542
- # We use a simple Gaussian mask to blend the merged patch region with the base estimate to ensure seamless
543
- # blending at the boundaries of the patch region.
544
- tobemergedto[h1:h2, w1:w2] = np.multiply(tobemergedto[h1:h2, w1:w2], 1 - mask) + np.multiply(merged, mask)
545
- imageandpatchs.set_updated_estimate(tobemergedto)
546
-
547
- # output
548
- return cv2.resize(imageandpatchs.estimation_updated_image, (input_resolution[1], input_resolution[0]), interpolation=cv2.INTER_CUBIC)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/leres/multi_depth_model_woauxi.py DELETED
@@ -1,35 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
-
4
- from . import network_auxi as network
5
- from .net_tools import get_func
6
-
7
-
8
- class RelDepthModel(nn.Module):
9
- def __init__(self, backbone='resnet50'):
10
- super(RelDepthModel, self).__init__()
11
- if backbone == 'resnet50':
12
- encoder = 'resnet50_stride32'
13
- elif backbone == 'resnext101':
14
- encoder = 'resnext101_stride32x8d'
15
- self.depth_model = DepthModel(encoder)
16
-
17
- def inference(self, rgb):
18
- with torch.no_grad():
19
- input = rgb.to(self.depth_model.device)
20
- depth = self.depth_model(input)
21
- #pred_depth_out = depth - depth.min() + 0.01
22
- return depth #pred_depth_out
23
-
24
-
25
- class DepthModel(nn.Module):
26
- def __init__(self, encoder):
27
- super(DepthModel, self).__init__()
28
- backbone = network.__name__.split('.')[-1] + '.' + encoder
29
- self.encoder_modules = get_func(backbone)()
30
- self.decoder_modules = network.Decoder()
31
-
32
- def forward(self, x):
33
- lateral_out = self.encoder_modules(x)
34
- out_logit = self.decoder_modules(lateral_out)
35
- return out_logit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/leres/net_tools.py DELETED
@@ -1,54 +0,0 @@
1
- import importlib
2
- import torch
3
- import os
4
- from collections import OrderedDict
5
-
6
-
7
- def get_func(func_name):
8
- """Helper to return a function object by name. func_name must identify a
9
- function in this module or the path to a function relative to the base
10
- 'modeling' module.
11
- """
12
- if func_name == '':
13
- return None
14
- try:
15
- parts = func_name.split('.')
16
- # Refers to a function in this module
17
- if len(parts) == 1:
18
- return globals()[parts[0]]
19
- # Otherwise, assume we're referencing a module under modeling
20
- module_name = 'controlnet_aux.leres.leres.' + '.'.join(parts[:-1])
21
- module = importlib.import_module(module_name)
22
- return getattr(module, parts[-1])
23
- except Exception:
24
- print('Failed to f1ind function: %s', func_name)
25
- raise
26
-
27
- def load_ckpt(args, depth_model, shift_model, focal_model):
28
- """
29
- Load checkpoint.
30
- """
31
- if os.path.isfile(args.load_ckpt):
32
- print("loading checkpoint %s" % args.load_ckpt)
33
- checkpoint = torch.load(args.load_ckpt)
34
- if shift_model is not None:
35
- shift_model.load_state_dict(strip_prefix_if_present(checkpoint['shift_model'], 'module.'),
36
- strict=True)
37
- if focal_model is not None:
38
- focal_model.load_state_dict(strip_prefix_if_present(checkpoint['focal_model'], 'module.'),
39
- strict=True)
40
- depth_model.load_state_dict(strip_prefix_if_present(checkpoint['depth_model'], "module."),
41
- strict=True)
42
- del checkpoint
43
- if torch.cuda.is_available():
44
- torch.cuda.empty_cache()
45
-
46
-
47
- def strip_prefix_if_present(state_dict, prefix):
48
- keys = sorted(state_dict.keys())
49
- if not all(key.startswith(prefix) for key in keys):
50
- return state_dict
51
- stripped_state_dict = OrderedDict()
52
- for key, value in state_dict.items():
53
- stripped_state_dict[key.replace(prefix, "")] = value
54
- return stripped_state_dict
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/leres/network_auxi.py DELETED
@@ -1,417 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.nn.init as init
4
-
5
- from . import Resnet, Resnext_torch
6
-
7
-
8
- def resnet50_stride32():
9
- return DepthNet(backbone='resnet', depth=50, upfactors=[2, 2, 2, 2])
10
-
11
- def resnext101_stride32x8d():
12
- return DepthNet(backbone='resnext101_32x8d', depth=101, upfactors=[2, 2, 2, 2])
13
-
14
-
15
- class Decoder(nn.Module):
16
- def __init__(self):
17
- super(Decoder, self).__init__()
18
- self.inchannels = [256, 512, 1024, 2048]
19
- self.midchannels = [256, 256, 256, 512]
20
- self.upfactors = [2,2,2,2]
21
- self.outchannels = 1
22
-
23
- self.conv = FTB(inchannels=self.inchannels[3], midchannels=self.midchannels[3])
24
- self.conv1 = nn.Conv2d(in_channels=self.midchannels[3], out_channels=self.midchannels[2], kernel_size=3, padding=1, stride=1, bias=True)
25
- self.upsample = nn.Upsample(scale_factor=self.upfactors[3], mode='bilinear', align_corners=True)
26
-
27
- self.ffm2 = FFM(inchannels=self.inchannels[2], midchannels=self.midchannels[2], outchannels = self.midchannels[2], upfactor=self.upfactors[2])
28
- self.ffm1 = FFM(inchannels=self.inchannels[1], midchannels=self.midchannels[1], outchannels = self.midchannels[1], upfactor=self.upfactors[1])
29
- self.ffm0 = FFM(inchannels=self.inchannels[0], midchannels=self.midchannels[0], outchannels = self.midchannels[0], upfactor=self.upfactors[0])
30
-
31
- self.outconv = AO(inchannels=self.midchannels[0], outchannels=self.outchannels, upfactor=2)
32
- self._init_params()
33
-
34
- def _init_params(self):
35
- for m in self.modules():
36
- if isinstance(m, nn.Conv2d):
37
- init.normal_(m.weight, std=0.01)
38
- if m.bias is not None:
39
- init.constant_(m.bias, 0)
40
- elif isinstance(m, nn.ConvTranspose2d):
41
- init.normal_(m.weight, std=0.01)
42
- if m.bias is not None:
43
- init.constant_(m.bias, 0)
44
- elif isinstance(m, nn.BatchNorm2d): #NN.BatchNorm2d
45
- init.constant_(m.weight, 1)
46
- init.constant_(m.bias, 0)
47
- elif isinstance(m, nn.Linear):
48
- init.normal_(m.weight, std=0.01)
49
- if m.bias is not None:
50
- init.constant_(m.bias, 0)
51
-
52
- def forward(self, features):
53
- x_32x = self.conv(features[3]) # 1/32
54
- x_32 = self.conv1(x_32x)
55
- x_16 = self.upsample(x_32) # 1/16
56
-
57
- x_8 = self.ffm2(features[2], x_16) # 1/8
58
- x_4 = self.ffm1(features[1], x_8) # 1/4
59
- x_2 = self.ffm0(features[0], x_4) # 1/2
60
- #-----------------------------------------
61
- x = self.outconv(x_2) # original size
62
- return x
63
-
64
- class DepthNet(nn.Module):
65
- __factory = {
66
- 18: Resnet.resnet18,
67
- 34: Resnet.resnet34,
68
- 50: Resnet.resnet50,
69
- 101: Resnet.resnet101,
70
- 152: Resnet.resnet152
71
- }
72
- def __init__(self,
73
- backbone='resnet',
74
- depth=50,
75
- upfactors=[2, 2, 2, 2]):
76
- super(DepthNet, self).__init__()
77
- self.backbone = backbone
78
- self.depth = depth
79
- self.pretrained = False
80
- self.inchannels = [256, 512, 1024, 2048]
81
- self.midchannels = [256, 256, 256, 512]
82
- self.upfactors = upfactors
83
- self.outchannels = 1
84
-
85
- # Build model
86
- if self.backbone == 'resnet':
87
- if self.depth not in DepthNet.__factory:
88
- raise KeyError("Unsupported depth:", self.depth)
89
- self.encoder = DepthNet.__factory[depth](pretrained=self.pretrained)
90
- elif self.backbone == 'resnext101_32x8d':
91
- self.encoder = Resnext_torch.resnext101_32x8d(pretrained=self.pretrained)
92
- else:
93
- self.encoder = Resnext_torch.resnext101(pretrained=self.pretrained)
94
-
95
- def forward(self, x):
96
- x = self.encoder(x) # 1/32, 1/16, 1/8, 1/4
97
- return x
98
-
99
-
100
- class FTB(nn.Module):
101
- def __init__(self, inchannels, midchannels=512):
102
- super(FTB, self).__init__()
103
- self.in1 = inchannels
104
- self.mid = midchannels
105
- self.conv1 = nn.Conv2d(in_channels=self.in1, out_channels=self.mid, kernel_size=3, padding=1, stride=1,
106
- bias=True)
107
- # NN.BatchNorm2d
108
- self.conv_branch = nn.Sequential(nn.ReLU(inplace=True), \
109
- nn.Conv2d(in_channels=self.mid, out_channels=self.mid, kernel_size=3,
110
- padding=1, stride=1, bias=True), \
111
- nn.BatchNorm2d(num_features=self.mid), \
112
- nn.ReLU(inplace=True), \
113
- nn.Conv2d(in_channels=self.mid, out_channels=self.mid, kernel_size=3,
114
- padding=1, stride=1, bias=True))
115
- self.relu = nn.ReLU(inplace=True)
116
-
117
- self.init_params()
118
-
119
- def forward(self, x):
120
- x = self.conv1(x)
121
- x = x + self.conv_branch(x)
122
- x = self.relu(x)
123
-
124
- return x
125
-
126
- def init_params(self):
127
- for m in self.modules():
128
- if isinstance(m, nn.Conv2d):
129
- init.normal_(m.weight, std=0.01)
130
- if m.bias is not None:
131
- init.constant_(m.bias, 0)
132
- elif isinstance(m, nn.ConvTranspose2d):
133
- # init.kaiming_normal_(m.weight, mode='fan_out')
134
- init.normal_(m.weight, std=0.01)
135
- # init.xavier_normal_(m.weight)
136
- if m.bias is not None:
137
- init.constant_(m.bias, 0)
138
- elif isinstance(m, nn.BatchNorm2d): # NN.BatchNorm2d
139
- init.constant_(m.weight, 1)
140
- init.constant_(m.bias, 0)
141
- elif isinstance(m, nn.Linear):
142
- init.normal_(m.weight, std=0.01)
143
- if m.bias is not None:
144
- init.constant_(m.bias, 0)
145
-
146
-
147
- class ATA(nn.Module):
148
- def __init__(self, inchannels, reduction=8):
149
- super(ATA, self).__init__()
150
- self.inchannels = inchannels
151
- self.avg_pool = nn.AdaptiveAvgPool2d(1)
152
- self.fc = nn.Sequential(nn.Linear(self.inchannels * 2, self.inchannels // reduction),
153
- nn.ReLU(inplace=True),
154
- nn.Linear(self.inchannels // reduction, self.inchannels),
155
- nn.Sigmoid())
156
- self.init_params()
157
-
158
- def forward(self, low_x, high_x):
159
- n, c, _, _ = low_x.size()
160
- x = torch.cat([low_x, high_x], 1)
161
- x = self.avg_pool(x)
162
- x = x.view(n, -1)
163
- x = self.fc(x).view(n, c, 1, 1)
164
- x = low_x * x + high_x
165
-
166
- return x
167
-
168
- def init_params(self):
169
- for m in self.modules():
170
- if isinstance(m, nn.Conv2d):
171
- # init.kaiming_normal_(m.weight, mode='fan_out')
172
- # init.normal(m.weight, std=0.01)
173
- init.xavier_normal_(m.weight)
174
- if m.bias is not None:
175
- init.constant_(m.bias, 0)
176
- elif isinstance(m, nn.ConvTranspose2d):
177
- # init.kaiming_normal_(m.weight, mode='fan_out')
178
- # init.normal_(m.weight, std=0.01)
179
- init.xavier_normal_(m.weight)
180
- if m.bias is not None:
181
- init.constant_(m.bias, 0)
182
- elif isinstance(m, nn.BatchNorm2d): # NN.BatchNorm2d
183
- init.constant_(m.weight, 1)
184
- init.constant_(m.bias, 0)
185
- elif isinstance(m, nn.Linear):
186
- init.normal_(m.weight, std=0.01)
187
- if m.bias is not None:
188
- init.constant_(m.bias, 0)
189
-
190
-
191
- class FFM(nn.Module):
192
- def __init__(self, inchannels, midchannels, outchannels, upfactor=2):
193
- super(FFM, self).__init__()
194
- self.inchannels = inchannels
195
- self.midchannels = midchannels
196
- self.outchannels = outchannels
197
- self.upfactor = upfactor
198
-
199
- self.ftb1 = FTB(inchannels=self.inchannels, midchannels=self.midchannels)
200
- # self.ata = ATA(inchannels = self.midchannels)
201
- self.ftb2 = FTB(inchannels=self.midchannels, midchannels=self.outchannels)
202
-
203
- self.upsample = nn.Upsample(scale_factor=self.upfactor, mode='bilinear', align_corners=True)
204
-
205
- self.init_params()
206
-
207
- def forward(self, low_x, high_x):
208
- x = self.ftb1(low_x)
209
- x = x + high_x
210
- x = self.ftb2(x)
211
- x = self.upsample(x)
212
-
213
- return x
214
-
215
- def init_params(self):
216
- for m in self.modules():
217
- if isinstance(m, nn.Conv2d):
218
- # init.kaiming_normal_(m.weight, mode='fan_out')
219
- init.normal_(m.weight, std=0.01)
220
- # init.xavier_normal_(m.weight)
221
- if m.bias is not None:
222
- init.constant_(m.bias, 0)
223
- elif isinstance(m, nn.ConvTranspose2d):
224
- # init.kaiming_normal_(m.weight, mode='fan_out')
225
- init.normal_(m.weight, std=0.01)
226
- # init.xavier_normal_(m.weight)
227
- if m.bias is not None:
228
- init.constant_(m.bias, 0)
229
- elif isinstance(m, nn.BatchNorm2d): # NN.Batchnorm2d
230
- init.constant_(m.weight, 1)
231
- init.constant_(m.bias, 0)
232
- elif isinstance(m, nn.Linear):
233
- init.normal_(m.weight, std=0.01)
234
- if m.bias is not None:
235
- init.constant_(m.bias, 0)
236
-
237
-
238
- class AO(nn.Module):
239
- # Adaptive output module
240
- def __init__(self, inchannels, outchannels, upfactor=2):
241
- super(AO, self).__init__()
242
- self.inchannels = inchannels
243
- self.outchannels = outchannels
244
- self.upfactor = upfactor
245
-
246
- self.adapt_conv = nn.Sequential(
247
- nn.Conv2d(in_channels=self.inchannels, out_channels=self.inchannels // 2, kernel_size=3, padding=1,
248
- stride=1, bias=True), \
249
- nn.BatchNorm2d(num_features=self.inchannels // 2), \
250
- nn.ReLU(inplace=True), \
251
- nn.Conv2d(in_channels=self.inchannels // 2, out_channels=self.outchannels, kernel_size=3, padding=1,
252
- stride=1, bias=True), \
253
- nn.Upsample(scale_factor=self.upfactor, mode='bilinear', align_corners=True))
254
-
255
- self.init_params()
256
-
257
- def forward(self, x):
258
- x = self.adapt_conv(x)
259
- return x
260
-
261
- def init_params(self):
262
- for m in self.modules():
263
- if isinstance(m, nn.Conv2d):
264
- # init.kaiming_normal_(m.weight, mode='fan_out')
265
- init.normal_(m.weight, std=0.01)
266
- # init.xavier_normal_(m.weight)
267
- if m.bias is not None:
268
- init.constant_(m.bias, 0)
269
- elif isinstance(m, nn.ConvTranspose2d):
270
- # init.kaiming_normal_(m.weight, mode='fan_out')
271
- init.normal_(m.weight, std=0.01)
272
- # init.xavier_normal_(m.weight)
273
- if m.bias is not None:
274
- init.constant_(m.bias, 0)
275
- elif isinstance(m, nn.BatchNorm2d): # NN.Batchnorm2d
276
- init.constant_(m.weight, 1)
277
- init.constant_(m.bias, 0)
278
- elif isinstance(m, nn.Linear):
279
- init.normal_(m.weight, std=0.01)
280
- if m.bias is not None:
281
- init.constant_(m.bias, 0)
282
-
283
-
284
-
285
- # ==============================================================================================================
286
-
287
-
288
- class ResidualConv(nn.Module):
289
- def __init__(self, inchannels):
290
- super(ResidualConv, self).__init__()
291
- # NN.BatchNorm2d
292
- self.conv = nn.Sequential(
293
- # nn.BatchNorm2d(num_features=inchannels),
294
- nn.ReLU(inplace=False),
295
- # nn.Conv2d(in_channels=inchannels, out_channels=inchannels, kernel_size=3, padding=1, stride=1, groups=inchannels,bias=True),
296
- # nn.Conv2d(in_channels=inchannels, out_channels=inchannels, kernel_size=1, padding=0, stride=1, groups=1,bias=True)
297
- nn.Conv2d(in_channels=inchannels, out_channels=inchannels / 2, kernel_size=3, padding=1, stride=1,
298
- bias=False),
299
- nn.BatchNorm2d(num_features=inchannels / 2),
300
- nn.ReLU(inplace=False),
301
- nn.Conv2d(in_channels=inchannels / 2, out_channels=inchannels, kernel_size=3, padding=1, stride=1,
302
- bias=False)
303
- )
304
- self.init_params()
305
-
306
- def forward(self, x):
307
- x = self.conv(x) + x
308
- return x
309
-
310
- def init_params(self):
311
- for m in self.modules():
312
- if isinstance(m, nn.Conv2d):
313
- # init.kaiming_normal_(m.weight, mode='fan_out')
314
- init.normal_(m.weight, std=0.01)
315
- # init.xavier_normal_(m.weight)
316
- if m.bias is not None:
317
- init.constant_(m.bias, 0)
318
- elif isinstance(m, nn.ConvTranspose2d):
319
- # init.kaiming_normal_(m.weight, mode='fan_out')
320
- init.normal_(m.weight, std=0.01)
321
- # init.xavier_normal_(m.weight)
322
- if m.bias is not None:
323
- init.constant_(m.bias, 0)
324
- elif isinstance(m, nn.BatchNorm2d): # NN.BatchNorm2d
325
- init.constant_(m.weight, 1)
326
- init.constant_(m.bias, 0)
327
- elif isinstance(m, nn.Linear):
328
- init.normal_(m.weight, std=0.01)
329
- if m.bias is not None:
330
- init.constant_(m.bias, 0)
331
-
332
-
333
- class FeatureFusion(nn.Module):
334
- def __init__(self, inchannels, outchannels):
335
- super(FeatureFusion, self).__init__()
336
- self.conv = ResidualConv(inchannels=inchannels)
337
- # NN.BatchNorm2d
338
- self.up = nn.Sequential(ResidualConv(inchannels=inchannels),
339
- nn.ConvTranspose2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3,
340
- stride=2, padding=1, output_padding=1),
341
- nn.BatchNorm2d(num_features=outchannels),
342
- nn.ReLU(inplace=True))
343
-
344
- def forward(self, lowfeat, highfeat):
345
- return self.up(highfeat + self.conv(lowfeat))
346
-
347
- def init_params(self):
348
- for m in self.modules():
349
- if isinstance(m, nn.Conv2d):
350
- # init.kaiming_normal_(m.weight, mode='fan_out')
351
- init.normal_(m.weight, std=0.01)
352
- # init.xavier_normal_(m.weight)
353
- if m.bias is not None:
354
- init.constant_(m.bias, 0)
355
- elif isinstance(m, nn.ConvTranspose2d):
356
- # init.kaiming_normal_(m.weight, mode='fan_out')
357
- init.normal_(m.weight, std=0.01)
358
- # init.xavier_normal_(m.weight)
359
- if m.bias is not None:
360
- init.constant_(m.bias, 0)
361
- elif isinstance(m, nn.BatchNorm2d): # NN.BatchNorm2d
362
- init.constant_(m.weight, 1)
363
- init.constant_(m.bias, 0)
364
- elif isinstance(m, nn.Linear):
365
- init.normal_(m.weight, std=0.01)
366
- if m.bias is not None:
367
- init.constant_(m.bias, 0)
368
-
369
-
370
- class SenceUnderstand(nn.Module):
371
- def __init__(self, channels):
372
- super(SenceUnderstand, self).__init__()
373
- self.channels = channels
374
- self.conv1 = nn.Sequential(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
375
- nn.ReLU(inplace=True))
376
- self.pool = nn.AdaptiveAvgPool2d(8)
377
- self.fc = nn.Sequential(nn.Linear(512 * 8 * 8, self.channels),
378
- nn.ReLU(inplace=True))
379
- self.conv2 = nn.Sequential(
380
- nn.Conv2d(in_channels=self.channels, out_channels=self.channels, kernel_size=1, padding=0),
381
- nn.ReLU(inplace=True))
382
- self.initial_params()
383
-
384
- def forward(self, x):
385
- n, c, h, w = x.size()
386
- x = self.conv1(x)
387
- x = self.pool(x)
388
- x = x.view(n, -1)
389
- x = self.fc(x)
390
- x = x.view(n, self.channels, 1, 1)
391
- x = self.conv2(x)
392
- x = x.repeat(1, 1, h, w)
393
- return x
394
-
395
- def initial_params(self, dev=0.01):
396
- for m in self.modules():
397
- if isinstance(m, nn.Conv2d):
398
- # print torch.sum(m.weight)
399
- m.weight.data.normal_(0, dev)
400
- if m.bias is not None:
401
- m.bias.data.fill_(0)
402
- elif isinstance(m, nn.ConvTranspose2d):
403
- # print torch.sum(m.weight)
404
- m.weight.data.normal_(0, dev)
405
- if m.bias is not None:
406
- m.bias.data.fill_(0)
407
- elif isinstance(m, nn.Linear):
408
- m.weight.data.normal_(0, dev)
409
-
410
-
411
- if __name__ == '__main__':
412
- net = DepthNet(depth=50, pretrained=True)
413
- print(net)
414
- inputs = torch.ones(4,3,128,128)
415
- out = net(inputs)
416
- print(out.size())
417
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/__init__.py DELETED
File without changes
controlnet_aux_local/leres/pix2pix/models/__init__.py DELETED
@@ -1,67 +0,0 @@
1
- """This package contains modules related to objective functions, optimizations, and network architectures.
2
-
3
- To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel.
4
- You need to implement the following five functions:
5
- -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).
6
- -- <set_input>: unpack data from dataset and apply preprocessing.
7
- -- <forward>: produce intermediate results.
8
- -- <optimize_parameters>: calculate loss, gradients, and update network weights.
9
- -- <modify_commandline_options>: (optionally) add model-specific options and set default options.
10
-
11
- In the function <__init__>, you need to define four lists:
12
- -- self.loss_names (str list): specify the training losses that you want to plot and save.
13
- -- self.model_names (str list): define networks used in our training.
14
- -- self.visual_names (str list): specify the images that you want to display and save.
15
- -- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an usage.
16
-
17
- Now you can use the model class by specifying flag '--model dummy'.
18
- See our template model class 'template_model.py' for more details.
19
- """
20
-
21
- import importlib
22
- from .base_model import BaseModel
23
-
24
-
25
- def find_model_using_name(model_name):
26
- """Import the module "models/[model_name]_model.py".
27
-
28
- In the file, the class called DatasetNameModel() will
29
- be instantiated. It has to be a subclass of BaseModel,
30
- and it is case-insensitive.
31
- """
32
- model_filename = "controlnet_aux.leres.pix2pix.models." + model_name + "_model"
33
- modellib = importlib.import_module(model_filename)
34
- model = None
35
- target_model_name = model_name.replace('_', '') + 'model'
36
- for name, cls in modellib.__dict__.items():
37
- if name.lower() == target_model_name.lower() \
38
- and issubclass(cls, BaseModel):
39
- model = cls
40
-
41
- if model is None:
42
- print("In %s.py, there should be a subclass of BaseModel with class name that matches %s in lowercase." % (model_filename, target_model_name))
43
- exit(0)
44
-
45
- return model
46
-
47
-
48
- def get_option_setter(model_name):
49
- """Return the static method <modify_commandline_options> of the model class."""
50
- model_class = find_model_using_name(model_name)
51
- return model_class.modify_commandline_options
52
-
53
-
54
- def create_model(opt):
55
- """Create a model given the option.
56
-
57
- This function warps the class CustomDatasetDataLoader.
58
- This is the main interface between this package and 'train.py'/'test.py'
59
-
60
- Example:
61
- >>> from models import create_model
62
- >>> model = create_model(opt)
63
- """
64
- model = find_model_using_name(opt.model)
65
- instance = model(opt)
66
- print("model [%s] was created" % type(instance).__name__)
67
- return instance
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/models/base_model.py DELETED
@@ -1,244 +0,0 @@
1
- import gc
2
- import os
3
- from abc import ABC, abstractmethod
4
- from collections import OrderedDict
5
-
6
- import torch
7
-
8
- from ....util import torch_gc
9
- from . import networks
10
-
11
-
12
- class BaseModel(ABC):
13
- """This class is an abstract base class (ABC) for models.
14
- To create a subclass, you need to implement the following five functions:
15
- -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).
16
- -- <set_input>: unpack data from dataset and apply preprocessing.
17
- -- <forward>: produce intermediate results.
18
- -- <optimize_parameters>: calculate losses, gradients, and update network weights.
19
- -- <modify_commandline_options>: (optionally) add model-specific options and set default options.
20
- """
21
-
22
- def __init__(self, opt):
23
- """Initialize the BaseModel class.
24
-
25
- Parameters:
26
- opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
27
-
28
- When creating your custom class, you need to implement your own initialization.
29
- In this function, you should first call <BaseModel.__init__(self, opt)>
30
- Then, you need to define four lists:
31
- -- self.loss_names (str list): specify the training losses that you want to plot and save.
32
- -- self.model_names (str list): define networks used in our training.
33
- -- self.visual_names (str list): specify the images that you want to display and save.
34
- -- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.
35
- """
36
- self.opt = opt
37
- self.gpu_ids = opt.gpu_ids
38
- self.isTrain = opt.isTrain
39
- self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU
40
- self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) # save all the checkpoints to save_dir
41
- if opt.preprocess != 'scale_width': # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark.
42
- torch.backends.cudnn.benchmark = True
43
- self.loss_names = []
44
- self.model_names = []
45
- self.visual_names = []
46
- self.optimizers = []
47
- self.image_paths = []
48
- self.metric = 0 # used for learning rate policy 'plateau'
49
-
50
- @staticmethod
51
- def modify_commandline_options(parser, is_train):
52
- """Add new model-specific options, and rewrite default values for existing options.
53
-
54
- Parameters:
55
- parser -- original option parser
56
- is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
57
-
58
- Returns:
59
- the modified parser.
60
- """
61
- return parser
62
-
63
- @abstractmethod
64
- def set_input(self, input):
65
- """Unpack input data from the dataloader and perform necessary pre-processing steps.
66
-
67
- Parameters:
68
- input (dict): includes the data itself and its metadata information.
69
- """
70
- pass
71
-
72
- @abstractmethod
73
- def forward(self):
74
- """Run forward pass; called by both functions <optimize_parameters> and <test>."""
75
- pass
76
-
77
- @abstractmethod
78
- def optimize_parameters(self):
79
- """Calculate losses, gradients, and update network weights; called in every training iteration"""
80
- pass
81
-
82
- def setup(self, opt):
83
- """Load and print networks; create schedulers
84
-
85
- Parameters:
86
- opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
87
- """
88
- if self.isTrain:
89
- self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers]
90
- if not self.isTrain or opt.continue_train:
91
- load_suffix = 'iter_%d' % opt.load_iter if opt.load_iter > 0 else opt.epoch
92
- self.load_networks(load_suffix)
93
- self.print_networks(opt.verbose)
94
-
95
- def eval(self):
96
- """Make models eval mode during test time"""
97
- for name in self.model_names:
98
- if isinstance(name, str):
99
- net = getattr(self, 'net' + name)
100
- net.eval()
101
-
102
- def test(self):
103
- """Forward function used in test time.
104
-
105
- This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop
106
- It also calls <compute_visuals> to produce additional visualization results
107
- """
108
- with torch.no_grad():
109
- self.forward()
110
- self.compute_visuals()
111
-
112
- def compute_visuals(self):
113
- """Calculate additional output images for visdom and HTML visualization"""
114
- pass
115
-
116
- def get_image_paths(self):
117
- """ Return image paths that are used to load current data"""
118
- return self.image_paths
119
-
120
- def update_learning_rate(self):
121
- """Update learning rates for all the networks; called at the end of every epoch"""
122
- old_lr = self.optimizers[0].param_groups[0]['lr']
123
- for scheduler in self.schedulers:
124
- if self.opt.lr_policy == 'plateau':
125
- scheduler.step(self.metric)
126
- else:
127
- scheduler.step()
128
-
129
- lr = self.optimizers[0].param_groups[0]['lr']
130
- print('learning rate %.7f -> %.7f' % (old_lr, lr))
131
-
132
- def get_current_visuals(self):
133
- """Return visualization images. train.py will display these images with visdom, and save the images to a HTML"""
134
- visual_ret = OrderedDict()
135
- for name in self.visual_names:
136
- if isinstance(name, str):
137
- visual_ret[name] = getattr(self, name)
138
- return visual_ret
139
-
140
- def get_current_losses(self):
141
- """Return traning losses / errors. train.py will print out these errors on console, and save them to a file"""
142
- errors_ret = OrderedDict()
143
- for name in self.loss_names:
144
- if isinstance(name, str):
145
- errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number
146
- return errors_ret
147
-
148
- def save_networks(self, epoch):
149
- """Save all the networks to the disk.
150
-
151
- Parameters:
152
- epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
153
- """
154
- for name in self.model_names:
155
- if isinstance(name, str):
156
- save_filename = '%s_net_%s.pth' % (epoch, name)
157
- save_path = os.path.join(self.save_dir, save_filename)
158
- net = getattr(self, 'net' + name)
159
-
160
- if len(self.gpu_ids) > 0 and torch.cuda.is_available():
161
- torch.save(net.module.cpu().state_dict(), save_path)
162
- net.cuda(self.gpu_ids[0])
163
- else:
164
- torch.save(net.cpu().state_dict(), save_path)
165
-
166
- def unload_network(self, name):
167
- """Unload network and gc.
168
- """
169
- if isinstance(name, str):
170
- net = getattr(self, 'net' + name)
171
- del net
172
- gc.collect()
173
- torch_gc()
174
- return None
175
-
176
- def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):
177
- """Fix InstanceNorm checkpoints incompatibility (prior to 0.4)"""
178
- key = keys[i]
179
- if i + 1 == len(keys): # at the end, pointing to a parameter/buffer
180
- if module.__class__.__name__.startswith('InstanceNorm') and \
181
- (key == 'running_mean' or key == 'running_var'):
182
- if getattr(module, key) is None:
183
- state_dict.pop('.'.join(keys))
184
- if module.__class__.__name__.startswith('InstanceNorm') and \
185
- (key == 'num_batches_tracked'):
186
- state_dict.pop('.'.join(keys))
187
- else:
188
- self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)
189
-
190
- def load_networks(self, epoch):
191
- """Load all the networks from the disk.
192
-
193
- Parameters:
194
- epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
195
- """
196
- for name in self.model_names:
197
- if isinstance(name, str):
198
- load_filename = '%s_net_%s.pth' % (epoch, name)
199
- load_path = os.path.join(self.save_dir, load_filename)
200
- net = getattr(self, 'net' + name)
201
- if isinstance(net, torch.nn.DataParallel):
202
- net = net.module
203
- # print('Loading depth boost model from %s' % load_path)
204
- # if you are using PyTorch newer than 0.4 (e.g., built from
205
- # GitHub source), you can remove str() on self.device
206
- state_dict = torch.load(load_path, map_location=str(self.device))
207
- if hasattr(state_dict, '_metadata'):
208
- del state_dict._metadata
209
-
210
- # patch InstanceNorm checkpoints prior to 0.4
211
- for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop
212
- self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))
213
- net.load_state_dict(state_dict)
214
-
215
- def print_networks(self, verbose):
216
- """Print the total number of parameters in the network and (if verbose) network architecture
217
-
218
- Parameters:
219
- verbose (bool) -- if verbose: print the network architecture
220
- """
221
- print('---------- Networks initialized -------------')
222
- for name in self.model_names:
223
- if isinstance(name, str):
224
- net = getattr(self, 'net' + name)
225
- num_params = 0
226
- for param in net.parameters():
227
- num_params += param.numel()
228
- if verbose:
229
- print(net)
230
- print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))
231
- print('-----------------------------------------------')
232
-
233
- def set_requires_grad(self, nets, requires_grad=False):
234
- """Set requies_grad=Fasle for all the networks to avoid unnecessary computations
235
- Parameters:
236
- nets (network list) -- a list of networks
237
- requires_grad (bool) -- whether the networks require gradients or not
238
- """
239
- if not isinstance(nets, list):
240
- nets = [nets]
241
- for net in nets:
242
- if net is not None:
243
- for param in net.parameters():
244
- param.requires_grad = requires_grad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/models/base_model_hg.py DELETED
@@ -1,58 +0,0 @@
1
- import os
2
- import torch
3
-
4
- class BaseModelHG():
5
- def name(self):
6
- return 'BaseModel'
7
-
8
- def initialize(self, opt):
9
- self.opt = opt
10
- self.gpu_ids = opt.gpu_ids
11
- self.isTrain = opt.isTrain
12
- self.Tensor = torch.cuda.FloatTensor if self.gpu_ids else torch.Tensor
13
- self.save_dir = os.path.join(opt.checkpoints_dir, opt.name)
14
-
15
- def set_input(self, input):
16
- self.input = input
17
-
18
- def forward(self):
19
- pass
20
-
21
- # used in test time, no backprop
22
- def test(self):
23
- pass
24
-
25
- def get_image_paths(self):
26
- pass
27
-
28
- def optimize_parameters(self):
29
- pass
30
-
31
- def get_current_visuals(self):
32
- return self.input
33
-
34
- def get_current_errors(self):
35
- return {}
36
-
37
- def save(self, label):
38
- pass
39
-
40
- # helper saving function that can be used by subclasses
41
- def save_network(self, network, network_label, epoch_label, gpu_ids):
42
- save_filename = '_%s_net_%s.pth' % (epoch_label, network_label)
43
- save_path = os.path.join(self.save_dir, save_filename)
44
- torch.save(network.cpu().state_dict(), save_path)
45
- if len(gpu_ids) and torch.cuda.is_available():
46
- network.cuda(device_id=gpu_ids[0])
47
-
48
- # helper loading function that can be used by subclasses
49
- def load_network(self, network, network_label, epoch_label):
50
- save_filename = '%s_net_%s.pth' % (epoch_label, network_label)
51
- save_path = os.path.join(self.save_dir, save_filename)
52
- print(save_path)
53
- model = torch.load(save_path)
54
- return model
55
- # network.load_state_dict(torch.load(save_path))
56
-
57
- def update_learning_rate():
58
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/models/networks.py DELETED
@@ -1,623 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from torch.nn import init
4
- import functools
5
- from torch.optim import lr_scheduler
6
-
7
-
8
- ###############################################################################
9
- # Helper Functions
10
- ###############################################################################
11
-
12
-
13
- class Identity(nn.Module):
14
- def forward(self, x):
15
- return x
16
-
17
-
18
- def get_norm_layer(norm_type='instance'):
19
- """Return a normalization layer
20
-
21
- Parameters:
22
- norm_type (str) -- the name of the normalization layer: batch | instance | none
23
-
24
- For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
25
- For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.
26
- """
27
- if norm_type == 'batch':
28
- norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
29
- elif norm_type == 'instance':
30
- norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)
31
- elif norm_type == 'none':
32
- def norm_layer(x): return Identity()
33
- else:
34
- raise NotImplementedError('normalization layer [%s] is not found' % norm_type)
35
- return norm_layer
36
-
37
-
38
- def get_scheduler(optimizer, opt):
39
- """Return a learning rate scheduler
40
-
41
- Parameters:
42
- optimizer -- the optimizer of the network
43
- opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions. 
44
- opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine
45
-
46
- For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs
47
- and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs.
48
- For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.
49
- See https://pytorch.org/docs/stable/optim.html for more details.
50
- """
51
- if opt.lr_policy == 'linear':
52
- def lambda_rule(epoch):
53
- lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.n_epochs) / float(opt.n_epochs_decay + 1)
54
- return lr_l
55
- scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
56
- elif opt.lr_policy == 'step':
57
- scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)
58
- elif opt.lr_policy == 'plateau':
59
- scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)
60
- elif opt.lr_policy == 'cosine':
61
- scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.n_epochs, eta_min=0)
62
- else:
63
- return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)
64
- return scheduler
65
-
66
-
67
- def init_weights(net, init_type='normal', init_gain=0.02):
68
- """Initialize network weights.
69
-
70
- Parameters:
71
- net (network) -- network to be initialized
72
- init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
73
- init_gain (float) -- scaling factor for normal, xavier and orthogonal.
74
-
75
- We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might
76
- work better for some applications. Feel free to try yourself.
77
- """
78
- def init_func(m): # define the initialization function
79
- classname = m.__class__.__name__
80
- if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
81
- if init_type == 'normal':
82
- init.normal_(m.weight.data, 0.0, init_gain)
83
- elif init_type == 'xavier':
84
- init.xavier_normal_(m.weight.data, gain=init_gain)
85
- elif init_type == 'kaiming':
86
- init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
87
- elif init_type == 'orthogonal':
88
- init.orthogonal_(m.weight.data, gain=init_gain)
89
- else:
90
- raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
91
- if hasattr(m, 'bias') and m.bias is not None:
92
- init.constant_(m.bias.data, 0.0)
93
- elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
94
- init.normal_(m.weight.data, 1.0, init_gain)
95
- init.constant_(m.bias.data, 0.0)
96
-
97
- # print('initialize network with %s' % init_type)
98
- net.apply(init_func) # apply the initialization function <init_func>
99
-
100
-
101
- def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
102
- """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights
103
- Parameters:
104
- net (network) -- the network to be initialized
105
- init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
106
- gain (float) -- scaling factor for normal, xavier and orthogonal.
107
- gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
108
-
109
- Return an initialized network.
110
- """
111
- if len(gpu_ids) > 0:
112
- assert(torch.cuda.is_available())
113
- net.to(gpu_ids[0])
114
- net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs
115
- init_weights(net, init_type, init_gain=init_gain)
116
- return net
117
-
118
-
119
- def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
120
- """Create a generator
121
-
122
- Parameters:
123
- input_nc (int) -- the number of channels in input images
124
- output_nc (int) -- the number of channels in output images
125
- ngf (int) -- the number of filters in the last conv layer
126
- netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128
127
- norm (str) -- the name of normalization layers used in the network: batch | instance | none
128
- use_dropout (bool) -- if use dropout layers.
129
- init_type (str) -- the name of our initialization method.
130
- init_gain (float) -- scaling factor for normal, xavier and orthogonal.
131
- gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
132
-
133
- Returns a generator
134
-
135
- Our current implementation provides two types of generators:
136
- U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)
137
- The original U-Net paper: https://arxiv.org/abs/1505.04597
138
-
139
- Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)
140
- Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.
141
- We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).
142
-
143
-
144
- The generator has been initialized by <init_net>. It uses RELU for non-linearity.
145
- """
146
- net = None
147
- norm_layer = get_norm_layer(norm_type=norm)
148
-
149
- if netG == 'resnet_9blocks':
150
- net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)
151
- elif netG == 'resnet_6blocks':
152
- net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)
153
- elif netG == 'resnet_12blocks':
154
- net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=12)
155
- elif netG == 'unet_128':
156
- net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
157
- elif netG == 'unet_256':
158
- net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
159
- elif netG == 'unet_672':
160
- net = UnetGenerator(input_nc, output_nc, 5, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
161
- elif netG == 'unet_960':
162
- net = UnetGenerator(input_nc, output_nc, 6, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
163
- elif netG == 'unet_1024':
164
- net = UnetGenerator(input_nc, output_nc, 10, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
165
- else:
166
- raise NotImplementedError('Generator model name [%s] is not recognized' % netG)
167
- return init_net(net, init_type, init_gain, gpu_ids)
168
-
169
-
170
- def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):
171
- """Create a discriminator
172
-
173
- Parameters:
174
- input_nc (int) -- the number of channels in input images
175
- ndf (int) -- the number of filters in the first conv layer
176
- netD (str) -- the architecture's name: basic | n_layers | pixel
177
- n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'
178
- norm (str) -- the type of normalization layers used in the network.
179
- init_type (str) -- the name of the initialization method.
180
- init_gain (float) -- scaling factor for normal, xavier and orthogonal.
181
- gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
182
-
183
- Returns a discriminator
184
-
185
- Our current implementation provides three types of discriminators:
186
- [basic]: 'PatchGAN' classifier described in the original pix2pix paper.
187
- It can classify whether 70×70 overlapping patches are real or fake.
188
- Such a patch-level discriminator architecture has fewer parameters
189
- than a full-image discriminator and can work on arbitrarily-sized images
190
- in a fully convolutional fashion.
191
-
192
- [n_layers]: With this mode, you can specify the number of conv layers in the discriminator
193
- with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)
194
-
195
- [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.
196
- It encourages greater color diversity but has no effect on spatial statistics.
197
-
198
- The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.
199
- """
200
- net = None
201
- norm_layer = get_norm_layer(norm_type=norm)
202
-
203
- if netD == 'basic': # default PatchGAN classifier
204
- net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)
205
- elif netD == 'n_layers': # more options
206
- net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)
207
- elif netD == 'pixel': # classify if each pixel is real or fake
208
- net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)
209
- else:
210
- raise NotImplementedError('Discriminator model name [%s] is not recognized' % netD)
211
- return init_net(net, init_type, init_gain, gpu_ids)
212
-
213
-
214
- ##############################################################################
215
- # Classes
216
- ##############################################################################
217
- class GANLoss(nn.Module):
218
- """Define different GAN objectives.
219
-
220
- The GANLoss class abstracts away the need to create the target label tensor
221
- that has the same size as the input.
222
- """
223
-
224
- def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
225
- """ Initialize the GANLoss class.
226
-
227
- Parameters:
228
- gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.
229
- target_real_label (bool) - - label for a real image
230
- target_fake_label (bool) - - label of a fake image
231
-
232
- Note: Do not use sigmoid as the last layer of Discriminator.
233
- LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.
234
- """
235
- super(GANLoss, self).__init__()
236
- self.register_buffer('real_label', torch.tensor(target_real_label))
237
- self.register_buffer('fake_label', torch.tensor(target_fake_label))
238
- self.gan_mode = gan_mode
239
- if gan_mode == 'lsgan':
240
- self.loss = nn.MSELoss()
241
- elif gan_mode == 'vanilla':
242
- self.loss = nn.BCEWithLogitsLoss()
243
- elif gan_mode in ['wgangp']:
244
- self.loss = None
245
- else:
246
- raise NotImplementedError('gan mode %s not implemented' % gan_mode)
247
-
248
- def get_target_tensor(self, prediction, target_is_real):
249
- """Create label tensors with the same size as the input.
250
-
251
- Parameters:
252
- prediction (tensor) - - tpyically the prediction from a discriminator
253
- target_is_real (bool) - - if the ground truth label is for real images or fake images
254
-
255
- Returns:
256
- A label tensor filled with ground truth label, and with the size of the input
257
- """
258
-
259
- if target_is_real:
260
- target_tensor = self.real_label
261
- else:
262
- target_tensor = self.fake_label
263
- return target_tensor.expand_as(prediction)
264
-
265
- def __call__(self, prediction, target_is_real):
266
- """Calculate loss given Discriminator's output and grount truth labels.
267
-
268
- Parameters:
269
- prediction (tensor) - - tpyically the prediction output from a discriminator
270
- target_is_real (bool) - - if the ground truth label is for real images or fake images
271
-
272
- Returns:
273
- the calculated loss.
274
- """
275
- if self.gan_mode in ['lsgan', 'vanilla']:
276
- target_tensor = self.get_target_tensor(prediction, target_is_real)
277
- loss = self.loss(prediction, target_tensor)
278
- elif self.gan_mode == 'wgangp':
279
- if target_is_real:
280
- loss = -prediction.mean()
281
- else:
282
- loss = prediction.mean()
283
- return loss
284
-
285
-
286
- def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
287
- """Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028
288
-
289
- Arguments:
290
- netD (network) -- discriminator network
291
- real_data (tensor array) -- real images
292
- fake_data (tensor array) -- generated images from the generator
293
- device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')
294
- type (str) -- if we mix real and fake data or not [real | fake | mixed].
295
- constant (float) -- the constant used in formula ( ||gradient||_2 - constant)^2
296
- lambda_gp (float) -- weight for this loss
297
-
298
- Returns the gradient penalty loss
299
- """
300
- if lambda_gp > 0.0:
301
- if type == 'real': # either use real images, fake images, or a linear interpolation of two.
302
- interpolatesv = real_data
303
- elif type == 'fake':
304
- interpolatesv = fake_data
305
- elif type == 'mixed':
306
- alpha = torch.rand(real_data.shape[0], 1, device=device)
307
- alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)
308
- interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)
309
- else:
310
- raise NotImplementedError('{} not implemented'.format(type))
311
- interpolatesv.requires_grad_(True)
312
- disc_interpolates = netD(interpolatesv)
313
- gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv,
314
- grad_outputs=torch.ones(disc_interpolates.size()).to(device),
315
- create_graph=True, retain_graph=True, only_inputs=True)
316
- gradients = gradients[0].view(real_data.size(0), -1) # flat the data
317
- gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps
318
- return gradient_penalty, gradients
319
- else:
320
- return 0.0, None
321
-
322
-
323
- class ResnetGenerator(nn.Module):
324
- """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.
325
-
326
- We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)
327
- """
328
-
329
- def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):
330
- """Construct a Resnet-based generator
331
-
332
- Parameters:
333
- input_nc (int) -- the number of channels in input images
334
- output_nc (int) -- the number of channels in output images
335
- ngf (int) -- the number of filters in the last conv layer
336
- norm_layer -- normalization layer
337
- use_dropout (bool) -- if use dropout layers
338
- n_blocks (int) -- the number of ResNet blocks
339
- padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero
340
- """
341
- assert(n_blocks >= 0)
342
- super(ResnetGenerator, self).__init__()
343
- if type(norm_layer) == functools.partial:
344
- use_bias = norm_layer.func == nn.InstanceNorm2d
345
- else:
346
- use_bias = norm_layer == nn.InstanceNorm2d
347
-
348
- model = [nn.ReflectionPad2d(3),
349
- nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),
350
- norm_layer(ngf),
351
- nn.ReLU(True)]
352
-
353
- n_downsampling = 2
354
- for i in range(n_downsampling): # add downsampling layers
355
- mult = 2 ** i
356
- model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),
357
- norm_layer(ngf * mult * 2),
358
- nn.ReLU(True)]
359
-
360
- mult = 2 ** n_downsampling
361
- for i in range(n_blocks): # add ResNet blocks
362
-
363
- model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]
364
-
365
- for i in range(n_downsampling): # add upsampling layers
366
- mult = 2 ** (n_downsampling - i)
367
- model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
368
- kernel_size=3, stride=2,
369
- padding=1, output_padding=1,
370
- bias=use_bias),
371
- norm_layer(int(ngf * mult / 2)),
372
- nn.ReLU(True)]
373
- model += [nn.ReflectionPad2d(3)]
374
- model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]
375
- model += [nn.Tanh()]
376
-
377
- self.model = nn.Sequential(*model)
378
-
379
- def forward(self, input):
380
- """Standard forward"""
381
- return self.model(input)
382
-
383
-
384
- class ResnetBlock(nn.Module):
385
- """Define a Resnet block"""
386
-
387
- def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
388
- """Initialize the Resnet block
389
-
390
- A resnet block is a conv block with skip connections
391
- We construct a conv block with build_conv_block function,
392
- and implement skip connections in <forward> function.
393
- Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf
394
- """
395
- super(ResnetBlock, self).__init__()
396
- self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)
397
-
398
- def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):
399
- """Construct a convolutional block.
400
-
401
- Parameters:
402
- dim (int) -- the number of channels in the conv layer.
403
- padding_type (str) -- the name of padding layer: reflect | replicate | zero
404
- norm_layer -- normalization layer
405
- use_dropout (bool) -- if use dropout layers.
406
- use_bias (bool) -- if the conv layer uses bias or not
407
-
408
- Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))
409
- """
410
- conv_block = []
411
- p = 0
412
- if padding_type == 'reflect':
413
- conv_block += [nn.ReflectionPad2d(1)]
414
- elif padding_type == 'replicate':
415
- conv_block += [nn.ReplicationPad2d(1)]
416
- elif padding_type == 'zero':
417
- p = 1
418
- else:
419
- raise NotImplementedError('padding [%s] is not implemented' % padding_type)
420
-
421
- conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]
422
- if use_dropout:
423
- conv_block += [nn.Dropout(0.5)]
424
-
425
- p = 0
426
- if padding_type == 'reflect':
427
- conv_block += [nn.ReflectionPad2d(1)]
428
- elif padding_type == 'replicate':
429
- conv_block += [nn.ReplicationPad2d(1)]
430
- elif padding_type == 'zero':
431
- p = 1
432
- else:
433
- raise NotImplementedError('padding [%s] is not implemented' % padding_type)
434
- conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]
435
-
436
- return nn.Sequential(*conv_block)
437
-
438
- def forward(self, x):
439
- """Forward function (with skip connections)"""
440
- out = x + self.conv_block(x) # add skip connections
441
- return out
442
-
443
-
444
- class UnetGenerator(nn.Module):
445
- """Create a Unet-based generator"""
446
-
447
- def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):
448
- """Construct a Unet generator
449
- Parameters:
450
- input_nc (int) -- the number of channels in input images
451
- output_nc (int) -- the number of channels in output images
452
- num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,
453
- image of size 128x128 will become of size 1x1 # at the bottleneck
454
- ngf (int) -- the number of filters in the last conv layer
455
- norm_layer -- normalization layer
456
-
457
- We construct the U-Net from the innermost layer to the outermost layer.
458
- It is a recursive process.
459
- """
460
- super(UnetGenerator, self).__init__()
461
- # construct unet structure
462
- unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer
463
- for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters
464
- unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)
465
- # gradually reduce the number of filters from ngf * 8 to ngf
466
- unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
467
- unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
468
- unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
469
- self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer
470
-
471
- def forward(self, input):
472
- """Standard forward"""
473
- return self.model(input)
474
-
475
-
476
- class UnetSkipConnectionBlock(nn.Module):
477
- """Defines the Unet submodule with skip connection.
478
- X -------------------identity----------------------
479
- |-- downsampling -- |submodule| -- upsampling --|
480
- """
481
-
482
- def __init__(self, outer_nc, inner_nc, input_nc=None,
483
- submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):
484
- """Construct a Unet submodule with skip connections.
485
-
486
- Parameters:
487
- outer_nc (int) -- the number of filters in the outer conv layer
488
- inner_nc (int) -- the number of filters in the inner conv layer
489
- input_nc (int) -- the number of channels in input images/features
490
- submodule (UnetSkipConnectionBlock) -- previously defined submodules
491
- outermost (bool) -- if this module is the outermost module
492
- innermost (bool) -- if this module is the innermost module
493
- norm_layer -- normalization layer
494
- use_dropout (bool) -- if use dropout layers.
495
- """
496
- super(UnetSkipConnectionBlock, self).__init__()
497
- self.outermost = outermost
498
- if type(norm_layer) == functools.partial:
499
- use_bias = norm_layer.func == nn.InstanceNorm2d
500
- else:
501
- use_bias = norm_layer == nn.InstanceNorm2d
502
- if input_nc is None:
503
- input_nc = outer_nc
504
- downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,
505
- stride=2, padding=1, bias=use_bias)
506
- downrelu = nn.LeakyReLU(0.2, True)
507
- downnorm = norm_layer(inner_nc)
508
- uprelu = nn.ReLU(True)
509
- upnorm = norm_layer(outer_nc)
510
-
511
- if outermost:
512
- upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
513
- kernel_size=4, stride=2,
514
- padding=1)
515
- down = [downconv]
516
- up = [uprelu, upconv, nn.Tanh()]
517
- model = down + [submodule] + up
518
- elif innermost:
519
- upconv = nn.ConvTranspose2d(inner_nc, outer_nc,
520
- kernel_size=4, stride=2,
521
- padding=1, bias=use_bias)
522
- down = [downrelu, downconv]
523
- up = [uprelu, upconv, upnorm]
524
- model = down + up
525
- else:
526
- upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
527
- kernel_size=4, stride=2,
528
- padding=1, bias=use_bias)
529
- down = [downrelu, downconv, downnorm]
530
- up = [uprelu, upconv, upnorm]
531
-
532
- if use_dropout:
533
- model = down + [submodule] + up + [nn.Dropout(0.5)]
534
- else:
535
- model = down + [submodule] + up
536
-
537
- self.model = nn.Sequential(*model)
538
-
539
- def forward(self, x):
540
- if self.outermost:
541
- return self.model(x)
542
- else: # add skip connections
543
- return torch.cat([x, self.model(x)], 1)
544
-
545
-
546
- class NLayerDiscriminator(nn.Module):
547
- """Defines a PatchGAN discriminator"""
548
-
549
- def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
550
- """Construct a PatchGAN discriminator
551
-
552
- Parameters:
553
- input_nc (int) -- the number of channels in input images
554
- ndf (int) -- the number of filters in the last conv layer
555
- n_layers (int) -- the number of conv layers in the discriminator
556
- norm_layer -- normalization layer
557
- """
558
- super(NLayerDiscriminator, self).__init__()
559
- if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
560
- use_bias = norm_layer.func == nn.InstanceNorm2d
561
- else:
562
- use_bias = norm_layer == nn.InstanceNorm2d
563
-
564
- kw = 4
565
- padw = 1
566
- sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
567
- nf_mult = 1
568
- nf_mult_prev = 1
569
- for n in range(1, n_layers): # gradually increase the number of filters
570
- nf_mult_prev = nf_mult
571
- nf_mult = min(2 ** n, 8)
572
- sequence += [
573
- nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
574
- norm_layer(ndf * nf_mult),
575
- nn.LeakyReLU(0.2, True)
576
- ]
577
-
578
- nf_mult_prev = nf_mult
579
- nf_mult = min(2 ** n_layers, 8)
580
- sequence += [
581
- nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
582
- norm_layer(ndf * nf_mult),
583
- nn.LeakyReLU(0.2, True)
584
- ]
585
-
586
- sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
587
- self.model = nn.Sequential(*sequence)
588
-
589
- def forward(self, input):
590
- """Standard forward."""
591
- return self.model(input)
592
-
593
-
594
- class PixelDiscriminator(nn.Module):
595
- """Defines a 1x1 PatchGAN discriminator (pixelGAN)"""
596
-
597
- def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):
598
- """Construct a 1x1 PatchGAN discriminator
599
-
600
- Parameters:
601
- input_nc (int) -- the number of channels in input images
602
- ndf (int) -- the number of filters in the last conv layer
603
- norm_layer -- normalization layer
604
- """
605
- super(PixelDiscriminator, self).__init__()
606
- if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
607
- use_bias = norm_layer.func == nn.InstanceNorm2d
608
- else:
609
- use_bias = norm_layer == nn.InstanceNorm2d
610
-
611
- self.net = [
612
- nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),
613
- nn.LeakyReLU(0.2, True),
614
- nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),
615
- norm_layer(ndf * 2),
616
- nn.LeakyReLU(0.2, True),
617
- nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]
618
-
619
- self.net = nn.Sequential(*self.net)
620
-
621
- def forward(self, input):
622
- """Standard forward."""
623
- return self.net(input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/models/pix2pix4depth_model.py DELETED
@@ -1,155 +0,0 @@
1
- import torch
2
- from .base_model import BaseModel
3
- from . import networks
4
-
5
-
6
- class Pix2Pix4DepthModel(BaseModel):
7
- """ This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.
8
-
9
- The model training requires '--dataset_mode aligned' dataset.
10
- By default, it uses a '--netG unet256' U-Net generator,
11
- a '--netD basic' discriminator (PatchGAN),
12
- and a '--gan_mode' vanilla GAN loss (the cross-entropy objective used in the orignal GAN paper).
13
-
14
- pix2pix paper: https://arxiv.org/pdf/1611.07004.pdf
15
- """
16
- @staticmethod
17
- def modify_commandline_options(parser, is_train=True):
18
- """Add new dataset-specific options, and rewrite default values for existing options.
19
-
20
- Parameters:
21
- parser -- original option parser
22
- is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
23
-
24
- Returns:
25
- the modified parser.
26
-
27
- For pix2pix, we do not use image buffer
28
- The training objective is: GAN Loss + lambda_L1 * ||G(A)-B||_1
29
- By default, we use vanilla GAN loss, UNet with batchnorm, and aligned datasets.
30
- """
31
- # changing the default values to match the pix2pix paper (https://phillipi.github.io/pix2pix/)
32
- parser.set_defaults(input_nc=2,output_nc=1,norm='none', netG='unet_1024', dataset_mode='depthmerge')
33
- if is_train:
34
- parser.set_defaults(pool_size=0, gan_mode='vanilla',)
35
- parser.add_argument('--lambda_L1', type=float, default=1000, help='weight for L1 loss')
36
- return parser
37
-
38
- def __init__(self, opt):
39
- """Initialize the pix2pix class.
40
-
41
- Parameters:
42
- opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
43
- """
44
- BaseModel.__init__(self, opt)
45
- # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
46
-
47
- self.loss_names = ['G_GAN', 'G_L1', 'D_real', 'D_fake']
48
- # self.loss_names = ['G_L1']
49
-
50
- # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
51
- if self.isTrain:
52
- self.visual_names = ['outer','inner', 'fake_B', 'real_B']
53
- else:
54
- self.visual_names = ['fake_B']
55
-
56
- # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>
57
- if self.isTrain:
58
- self.model_names = ['G','D']
59
- else: # during test time, only load G
60
- self.model_names = ['G']
61
-
62
- # define networks (both generator and discriminator)
63
- self.netG = networks.define_G(opt.input_nc, opt.output_nc, 64, 'unet_1024', 'none',
64
- False, 'normal', 0.02, self.gpu_ids)
65
-
66
- if self.isTrain: # define a discriminator; conditional GANs need to take both input and output images; Therefore, #channels for D is input_nc + output_nc
67
- self.netD = networks.define_D(opt.input_nc + opt.output_nc, opt.ndf, opt.netD,
68
- opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
69
-
70
- if self.isTrain:
71
- # define loss functions
72
- self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)
73
- self.criterionL1 = torch.nn.L1Loss()
74
- # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
75
- self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=1e-4, betas=(opt.beta1, 0.999))
76
- self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=2e-06, betas=(opt.beta1, 0.999))
77
- self.optimizers.append(self.optimizer_G)
78
- self.optimizers.append(self.optimizer_D)
79
-
80
- def set_input_train(self, input):
81
- self.outer = input['data_outer'].to(self.device)
82
- self.outer = torch.nn.functional.interpolate(self.outer,(1024,1024),mode='bilinear',align_corners=False)
83
-
84
- self.inner = input['data_inner'].to(self.device)
85
- self.inner = torch.nn.functional.interpolate(self.inner,(1024,1024),mode='bilinear',align_corners=False)
86
-
87
- self.image_paths = input['image_path']
88
-
89
- if self.isTrain:
90
- self.gtfake = input['data_gtfake'].to(self.device)
91
- self.gtfake = torch.nn.functional.interpolate(self.gtfake, (1024, 1024), mode='bilinear', align_corners=False)
92
- self.real_B = self.gtfake
93
-
94
- self.real_A = torch.cat((self.outer, self.inner), 1)
95
-
96
- def set_input(self, outer, inner):
97
- inner = torch.from_numpy(inner).unsqueeze(0).unsqueeze(0)
98
- outer = torch.from_numpy(outer).unsqueeze(0).unsqueeze(0)
99
-
100
- inner = (inner - torch.min(inner))/(torch.max(inner)-torch.min(inner))
101
- outer = (outer - torch.min(outer))/(torch.max(outer)-torch.min(outer))
102
-
103
- inner = self.normalize(inner)
104
- outer = self.normalize(outer)
105
-
106
- self.real_A = torch.cat((outer, inner), 1).to(self.device)
107
-
108
-
109
- def normalize(self, input):
110
- input = input * 2
111
- input = input - 1
112
- return input
113
-
114
- def forward(self):
115
- """Run forward pass; called by both functions <optimize_parameters> and <test>."""
116
- self.fake_B = self.netG(self.real_A) # G(A)
117
-
118
- def backward_D(self):
119
- """Calculate GAN loss for the discriminator"""
120
- # Fake; stop backprop to the generator by detaching fake_B
121
- fake_AB = torch.cat((self.real_A, self.fake_B), 1) # we use conditional GANs; we need to feed both input and output to the discriminator
122
- pred_fake = self.netD(fake_AB.detach())
123
- self.loss_D_fake = self.criterionGAN(pred_fake, False)
124
- # Real
125
- real_AB = torch.cat((self.real_A, self.real_B), 1)
126
- pred_real = self.netD(real_AB)
127
- self.loss_D_real = self.criterionGAN(pred_real, True)
128
- # combine loss and calculate gradients
129
- self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5
130
- self.loss_D.backward()
131
-
132
- def backward_G(self):
133
- """Calculate GAN and L1 loss for the generator"""
134
- # First, G(A) should fake the discriminator
135
- fake_AB = torch.cat((self.real_A, self.fake_B), 1)
136
- pred_fake = self.netD(fake_AB)
137
- self.loss_G_GAN = self.criterionGAN(pred_fake, True)
138
- # Second, G(A) = B
139
- self.loss_G_L1 = self.criterionL1(self.fake_B, self.real_B) * self.opt.lambda_L1
140
- # combine loss and calculate gradients
141
- self.loss_G = self.loss_G_L1 + self.loss_G_GAN
142
- self.loss_G.backward()
143
-
144
- def optimize_parameters(self):
145
- self.forward() # compute fake images: G(A)
146
- # update D
147
- self.set_requires_grad(self.netD, True) # enable backprop for D
148
- self.optimizer_D.zero_grad() # set D's gradients to zero
149
- self.backward_D() # calculate gradients for D
150
- self.optimizer_D.step() # update D's weights
151
- # update G
152
- self.set_requires_grad(self.netD, False) # D requires no gradients when optimizing G
153
- self.optimizer_G.zero_grad() # set G's gradients to zero
154
- self.backward_G() # calculate graidents for G
155
- self.optimizer_G.step() # udpate G's weights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/options/__init__.py DELETED
@@ -1 +0,0 @@
1
- """This package options includes option modules: training options, test options, and basic options (used in both training and test)."""
 
 
controlnet_aux_local/leres/pix2pix/options/base_options.py DELETED
@@ -1,156 +0,0 @@
1
- import argparse
2
- import os
3
- from ...pix2pix.util import util
4
- # import torch
5
- from ...pix2pix import models
6
- # import pix2pix.data
7
- import numpy as np
8
-
9
- class BaseOptions():
10
- """This class defines options used during both training and test time.
11
-
12
- It also implements several helper functions such as parsing, printing, and saving the options.
13
- It also gathers additional options defined in <modify_commandline_options> functions in both dataset class and model class.
14
- """
15
-
16
- def __init__(self):
17
- """Reset the class; indicates the class hasn't been initailized"""
18
- self.initialized = False
19
-
20
- def initialize(self, parser):
21
- """Define the common options that are used in both training and test."""
22
- # basic parameters
23
- parser.add_argument('--dataroot', help='path to images (should have subfolders trainA, trainB, valA, valB, etc)')
24
- parser.add_argument('--name', type=str, default='void', help='mahdi_unet_new, scaled_unet')
25
- parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')
26
- parser.add_argument('--checkpoints_dir', type=str, default='./pix2pix/checkpoints', help='models are saved here')
27
- # model parameters
28
- parser.add_argument('--model', type=str, default='cycle_gan', help='chooses which model to use. [cycle_gan | pix2pix | test | colorization]')
29
- parser.add_argument('--input_nc', type=int, default=2, help='# of input image channels: 3 for RGB and 1 for grayscale')
30
- parser.add_argument('--output_nc', type=int, default=1, help='# of output image channels: 3 for RGB and 1 for grayscale')
31
- parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in the last conv layer')
32
- parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in the first conv layer')
33
- parser.add_argument('--netD', type=str, default='basic', help='specify discriminator architecture [basic | n_layers | pixel]. The basic model is a 70x70 PatchGAN. n_layers allows you to specify the layers in the discriminator')
34
- parser.add_argument('--netG', type=str, default='resnet_9blocks', help='specify generator architecture [resnet_9blocks | resnet_6blocks | unet_256 | unet_128]')
35
- parser.add_argument('--n_layers_D', type=int, default=3, help='only used if netD==n_layers')
36
- parser.add_argument('--norm', type=str, default='instance', help='instance normalization or batch normalization [instance | batch | none]')
37
- parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal | xavier | kaiming | orthogonal]')
38
- parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')
39
- parser.add_argument('--no_dropout', action='store_true', help='no dropout for the generator')
40
- # dataset parameters
41
- parser.add_argument('--dataset_mode', type=str, default='unaligned', help='chooses how datasets are loaded. [unaligned | aligned | single | colorization]')
42
- parser.add_argument('--direction', type=str, default='AtoB', help='AtoB or BtoA')
43
- parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')
44
- parser.add_argument('--num_threads', default=4, type=int, help='# threads for loading data')
45
- parser.add_argument('--batch_size', type=int, default=1, help='input batch size')
46
- parser.add_argument('--load_size', type=int, default=672, help='scale images to this size')
47
- parser.add_argument('--crop_size', type=int, default=672, help='then crop to this size')
48
- parser.add_argument('--max_dataset_size', type=int, default=10000, help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.')
49
- parser.add_argument('--preprocess', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop | crop | scale_width | scale_width_and_crop | none]')
50
- parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation')
51
- parser.add_argument('--display_winsize', type=int, default=256, help='display window size for both visdom and HTML')
52
- # additional parameters
53
- parser.add_argument('--epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model')
54
- parser.add_argument('--load_iter', type=int, default='0', help='which iteration to load? if load_iter > 0, the code will load models by iter_[load_iter]; otherwise, the code will load models by [epoch]')
55
- parser.add_argument('--verbose', action='store_true', help='if specified, print more debugging information')
56
- parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{load_size}')
57
-
58
- parser.add_argument('--data_dir', type=str, required=False,
59
- help='input files directory images can be .png .jpg .tiff')
60
- parser.add_argument('--output_dir', type=str, required=False,
61
- help='result dir. result depth will be png. vides are JMPG as avi')
62
- parser.add_argument('--savecrops', type=int, required=False)
63
- parser.add_argument('--savewholeest', type=int, required=False)
64
- parser.add_argument('--output_resolution', type=int, required=False,
65
- help='0 for no restriction 1 for resize to input size')
66
- parser.add_argument('--net_receptive_field_size', type=int, required=False)
67
- parser.add_argument('--pix2pixsize', type=int, required=False)
68
- parser.add_argument('--generatevideo', type=int, required=False)
69
- parser.add_argument('--depthNet', type=int, required=False, help='0: midas 1:strurturedRL')
70
- parser.add_argument('--R0', action='store_true')
71
- parser.add_argument('--R20', action='store_true')
72
- parser.add_argument('--Final', action='store_true')
73
- parser.add_argument('--colorize_results', action='store_true')
74
- parser.add_argument('--max_res', type=float, default=np.inf)
75
-
76
- self.initialized = True
77
- return parser
78
-
79
- def gather_options(self):
80
- """Initialize our parser with basic options(only once).
81
- Add additional model-specific and dataset-specific options.
82
- These options are defined in the <modify_commandline_options> function
83
- in model and dataset classes.
84
- """
85
- if not self.initialized: # check if it has been initialized
86
- parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
87
- parser = self.initialize(parser)
88
-
89
- # get the basic options
90
- opt, _ = parser.parse_known_args()
91
-
92
- # modify model-related parser options
93
- model_name = opt.model
94
- model_option_setter = models.get_option_setter(model_name)
95
- parser = model_option_setter(parser, self.isTrain)
96
- opt, _ = parser.parse_known_args() # parse again with new defaults
97
-
98
- # modify dataset-related parser options
99
- # dataset_name = opt.dataset_mode
100
- # dataset_option_setter = pix2pix.data.get_option_setter(dataset_name)
101
- # parser = dataset_option_setter(parser, self.isTrain)
102
-
103
- # save and return the parser
104
- self.parser = parser
105
- #return parser.parse_args() #EVIL
106
- return opt
107
-
108
- def print_options(self, opt):
109
- """Print and save options
110
-
111
- It will print both current options and default values(if different).
112
- It will save options into a text file / [checkpoints_dir] / opt.txt
113
- """
114
- message = ''
115
- message += '----------------- Options ---------------\n'
116
- for k, v in sorted(vars(opt).items()):
117
- comment = ''
118
- default = self.parser.get_default(k)
119
- if v != default:
120
- comment = '\t[default: %s]' % str(default)
121
- message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment)
122
- message += '----------------- End -------------------'
123
- print(message)
124
-
125
- # save to the disk
126
- expr_dir = os.path.join(opt.checkpoints_dir, opt.name)
127
- util.mkdirs(expr_dir)
128
- file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase))
129
- with open(file_name, 'wt') as opt_file:
130
- opt_file.write(message)
131
- opt_file.write('\n')
132
-
133
- def parse(self):
134
- """Parse our options, create checkpoints directory suffix, and set up gpu device."""
135
- opt = self.gather_options()
136
- opt.isTrain = self.isTrain # train or test
137
-
138
- # process opt.suffix
139
- if opt.suffix:
140
- suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''
141
- opt.name = opt.name + suffix
142
-
143
- #self.print_options(opt)
144
-
145
- # set gpu ids
146
- str_ids = opt.gpu_ids.split(',')
147
- opt.gpu_ids = []
148
- for str_id in str_ids:
149
- id = int(str_id)
150
- if id >= 0:
151
- opt.gpu_ids.append(id)
152
- #if len(opt.gpu_ids) > 0:
153
- # torch.cuda.set_device(opt.gpu_ids[0])
154
-
155
- self.opt = opt
156
- return self.opt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/options/test_options.py DELETED
@@ -1,22 +0,0 @@
1
- from .base_options import BaseOptions
2
-
3
-
4
- class TestOptions(BaseOptions):
5
- """This class includes test options.
6
-
7
- It also includes shared options defined in BaseOptions.
8
- """
9
-
10
- def initialize(self, parser):
11
- parser = BaseOptions.initialize(self, parser) # define shared options
12
- parser.add_argument('--aspect_ratio', type=float, default=1.0, help='aspect ratio of result images')
13
- parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
14
- # Dropout and Batchnorm has different behavioir during training and test.
15
- parser.add_argument('--eval', action='store_true', help='use eval mode during test time.')
16
- parser.add_argument('--num_test', type=int, default=50, help='how many test images to run')
17
- # rewrite devalue values
18
- parser.set_defaults(model='pix2pix4depth')
19
- # To avoid cropping, the load_size should be the same as crop_size
20
- parser.set_defaults(load_size=parser.get_default('crop_size'))
21
- self.isTrain = False
22
- return parser
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/leres/pix2pix/util/__init__.py DELETED
@@ -1 +0,0 @@
1
- """This package includes a miscellaneous collection of useful helper functions."""
 
 
controlnet_aux_local/leres/pix2pix/util/util.py DELETED
@@ -1,105 +0,0 @@
1
- """This module contains simple helper functions """
2
- from __future__ import print_function
3
- import torch
4
- import numpy as np
5
- from PIL import Image
6
- import os
7
-
8
-
9
- def tensor2im(input_image, imtype=np.uint16):
10
- """"Converts a Tensor array into a numpy image array.
11
-
12
- Parameters:
13
- input_image (tensor) -- the input image tensor array
14
- imtype (type) -- the desired type of the converted numpy array
15
- """
16
- if not isinstance(input_image, np.ndarray):
17
- if isinstance(input_image, torch.Tensor): # get the data from a variable
18
- image_tensor = input_image.data
19
- else:
20
- return input_image
21
- image_numpy = torch.squeeze(image_tensor).cpu().numpy() # convert it into a numpy array
22
- image_numpy = (image_numpy + 1) / 2.0 * (2**16-1) #
23
- else: # if it is a numpy array, do nothing
24
- image_numpy = input_image
25
- return image_numpy.astype(imtype)
26
-
27
-
28
- def diagnose_network(net, name='network'):
29
- """Calculate and print the mean of average absolute(gradients)
30
-
31
- Parameters:
32
- net (torch network) -- Torch network
33
- name (str) -- the name of the network
34
- """
35
- mean = 0.0
36
- count = 0
37
- for param in net.parameters():
38
- if param.grad is not None:
39
- mean += torch.mean(torch.abs(param.grad.data))
40
- count += 1
41
- if count > 0:
42
- mean = mean / count
43
- print(name)
44
- print(mean)
45
-
46
-
47
- def save_image(image_numpy, image_path, aspect_ratio=1.0):
48
- """Save a numpy image to the disk
49
-
50
- Parameters:
51
- image_numpy (numpy array) -- input numpy array
52
- image_path (str) -- the path of the image
53
- """
54
- image_pil = Image.fromarray(image_numpy)
55
-
56
- image_pil = image_pil.convert('I;16')
57
-
58
- # image_pil = Image.fromarray(image_numpy)
59
- # h, w, _ = image_numpy.shape
60
- #
61
- # if aspect_ratio > 1.0:
62
- # image_pil = image_pil.resize((h, int(w * aspect_ratio)), Image.BICUBIC)
63
- # if aspect_ratio < 1.0:
64
- # image_pil = image_pil.resize((int(h / aspect_ratio), w), Image.BICUBIC)
65
-
66
- image_pil.save(image_path)
67
-
68
-
69
- def print_numpy(x, val=True, shp=False):
70
- """Print the mean, min, max, median, std, and size of a numpy array
71
-
72
- Parameters:
73
- val (bool) -- if print the values of the numpy array
74
- shp (bool) -- if print the shape of the numpy array
75
- """
76
- x = x.astype(np.float64)
77
- if shp:
78
- print('shape,', x.shape)
79
- if val:
80
- x = x.flatten()
81
- print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (
82
- np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
83
-
84
-
85
- def mkdirs(paths):
86
- """create empty directories if they don't exist
87
-
88
- Parameters:
89
- paths (str list) -- a list of directory paths
90
- """
91
- if isinstance(paths, list) and not isinstance(paths, str):
92
- for path in paths:
93
- mkdir(path)
94
- else:
95
- mkdir(paths)
96
-
97
-
98
- def mkdir(path):
99
- """create a single empty directory if it didn't exist
100
-
101
- Parameters:
102
- path (str) -- a single directory path
103
- """
104
- if not os.path.exists(path):
105
- os.makedirs(path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/lineart/__init__.py DELETED
@@ -1,167 +0,0 @@
1
- import os
2
- import warnings
3
-
4
- import cv2
5
- import numpy as np
6
- import torch
7
- import torch.nn as nn
8
- from einops import rearrange
9
- from huggingface_hub import hf_hub_download
10
- from PIL import Image
11
-
12
- from ..util import HWC3, resize_image
13
-
14
- norm_layer = nn.InstanceNorm2d
15
-
16
-
17
- class ResidualBlock(nn.Module):
18
- def __init__(self, in_features):
19
- super(ResidualBlock, self).__init__()
20
-
21
- conv_block = [ nn.ReflectionPad2d(1),
22
- nn.Conv2d(in_features, in_features, 3),
23
- norm_layer(in_features),
24
- nn.ReLU(inplace=True),
25
- nn.ReflectionPad2d(1),
26
- nn.Conv2d(in_features, in_features, 3),
27
- norm_layer(in_features)
28
- ]
29
-
30
- self.conv_block = nn.Sequential(*conv_block)
31
-
32
- def forward(self, x):
33
- return x + self.conv_block(x)
34
-
35
-
36
- class Generator(nn.Module):
37
- def __init__(self, input_nc, output_nc, n_residual_blocks=9, sigmoid=True):
38
- super(Generator, self).__init__()
39
-
40
- # Initial convolution block
41
- model0 = [ nn.ReflectionPad2d(3),
42
- nn.Conv2d(input_nc, 64, 7),
43
- norm_layer(64),
44
- nn.ReLU(inplace=True) ]
45
- self.model0 = nn.Sequential(*model0)
46
-
47
- # Downsampling
48
- model1 = []
49
- in_features = 64
50
- out_features = in_features*2
51
- for _ in range(2):
52
- model1 += [ nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
53
- norm_layer(out_features),
54
- nn.ReLU(inplace=True) ]
55
- in_features = out_features
56
- out_features = in_features*2
57
- self.model1 = nn.Sequential(*model1)
58
-
59
- model2 = []
60
- # Residual blocks
61
- for _ in range(n_residual_blocks):
62
- model2 += [ResidualBlock(in_features)]
63
- self.model2 = nn.Sequential(*model2)
64
-
65
- # Upsampling
66
- model3 = []
67
- out_features = in_features//2
68
- for _ in range(2):
69
- model3 += [ nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),
70
- norm_layer(out_features),
71
- nn.ReLU(inplace=True) ]
72
- in_features = out_features
73
- out_features = in_features//2
74
- self.model3 = nn.Sequential(*model3)
75
-
76
- # Output layer
77
- model4 = [ nn.ReflectionPad2d(3),
78
- nn.Conv2d(64, output_nc, 7)]
79
- if sigmoid:
80
- model4 += [nn.Sigmoid()]
81
-
82
- self.model4 = nn.Sequential(*model4)
83
-
84
- def forward(self, x, cond=None):
85
- out = self.model0(x)
86
- out = self.model1(out)
87
- out = self.model2(out)
88
- out = self.model3(out)
89
- out = self.model4(out)
90
-
91
- return out
92
-
93
-
94
- class LineartDetector:
95
- def __init__(self, model, coarse_model):
96
- self.model = model
97
- self.model_coarse = coarse_model
98
-
99
- @classmethod
100
- def from_pretrained(cls, pretrained_model_or_path, filename=None, coarse_filename=None, cache_dir=None, local_files_only=False):
101
- filename = filename or "sk_model.pth"
102
- coarse_filename = coarse_filename or "sk_model2.pth"
103
-
104
- if os.path.isdir(pretrained_model_or_path):
105
- model_path = os.path.join(pretrained_model_or_path, filename)
106
- coarse_model_path = os.path.join(pretrained_model_or_path, coarse_filename)
107
- else:
108
- model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
109
- coarse_model_path = hf_hub_download(pretrained_model_or_path, coarse_filename, cache_dir=cache_dir, local_files_only=local_files_only)
110
-
111
- model = Generator(3, 1, 3)
112
- model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
113
- model.eval()
114
-
115
- coarse_model = Generator(3, 1, 3)
116
- coarse_model.load_state_dict(torch.load(coarse_model_path, map_location=torch.device('cpu')))
117
- coarse_model.eval()
118
-
119
- return cls(model, coarse_model)
120
-
121
- def to(self, device):
122
- self.model.to(device)
123
- self.model_coarse.to(device)
124
- return self
125
-
126
- def __call__(self, input_image, coarse=False, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
127
- if "return_pil" in kwargs:
128
- warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
129
- output_type = "pil" if kwargs["return_pil"] else "np"
130
- if type(output_type) is bool:
131
- warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
132
- if output_type:
133
- output_type = "pil"
134
-
135
- device = next(iter(self.model.parameters())).device
136
- if not isinstance(input_image, np.ndarray):
137
- input_image = np.array(input_image, dtype=np.uint8)
138
-
139
- input_image = HWC3(input_image)
140
- input_image = resize_image(input_image, detect_resolution)
141
-
142
- model = self.model_coarse if coarse else self.model
143
- assert input_image.ndim == 3
144
- image = input_image
145
- with torch.no_grad():
146
- image = torch.from_numpy(image).float().to(device)
147
- image = image / 255.0
148
- image = rearrange(image, 'h w c -> 1 c h w')
149
- line = model(image)[0][0]
150
-
151
- line = line.cpu().numpy()
152
- line = (line * 255.0).clip(0, 255).astype(np.uint8)
153
-
154
- detected_map = line
155
-
156
- detected_map = HWC3(detected_map)
157
-
158
- img = resize_image(input_image, image_resolution)
159
- H, W, C = img.shape
160
-
161
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
162
- detected_map = 255 - detected_map
163
-
164
- if output_type == "pil":
165
- detected_map = Image.fromarray(detected_map)
166
-
167
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/lineart_anime/__init__.py DELETED
@@ -1,189 +0,0 @@
1
- import functools
2
- import os
3
- import warnings
4
-
5
- import cv2
6
- import numpy as np
7
- import torch
8
- import torch.nn as nn
9
- from einops import rearrange
10
- from huggingface_hub import hf_hub_download
11
- from PIL import Image
12
-
13
- from ..util import HWC3, resize_image
14
-
15
-
16
- class UnetGenerator(nn.Module):
17
- """Create a Unet-based generator"""
18
-
19
- def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):
20
- """Construct a Unet generator
21
- Parameters:
22
- input_nc (int) -- the number of channels in input images
23
- output_nc (int) -- the number of channels in output images
24
- num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,
25
- image of size 128x128 will become of size 1x1 # at the bottleneck
26
- ngf (int) -- the number of filters in the last conv layer
27
- norm_layer -- normalization layer
28
- We construct the U-Net from the innermost layer to the outermost layer.
29
- It is a recursive process.
30
- """
31
- super(UnetGenerator, self).__init__()
32
- # construct unet structure
33
- unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer
34
- for _ in range(num_downs - 5): # add intermediate layers with ngf * 8 filters
35
- unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)
36
- # gradually reduce the number of filters from ngf * 8 to ngf
37
- unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
38
- unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
39
- unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
40
- self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer
41
-
42
- def forward(self, input):
43
- """Standard forward"""
44
- return self.model(input)
45
-
46
-
47
- class UnetSkipConnectionBlock(nn.Module):
48
- """Defines the Unet submodule with skip connection.
49
- X -------------------identity----------------------
50
- |-- downsampling -- |submodule| -- upsampling --|
51
- """
52
-
53
- def __init__(self, outer_nc, inner_nc, input_nc=None,
54
- submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):
55
- """Construct a Unet submodule with skip connections.
56
- Parameters:
57
- outer_nc (int) -- the number of filters in the outer conv layer
58
- inner_nc (int) -- the number of filters in the inner conv layer
59
- input_nc (int) -- the number of channels in input images/features
60
- submodule (UnetSkipConnectionBlock) -- previously defined submodules
61
- outermost (bool) -- if this module is the outermost module
62
- innermost (bool) -- if this module is the innermost module
63
- norm_layer -- normalization layer
64
- use_dropout (bool) -- if use dropout layers.
65
- """
66
- super(UnetSkipConnectionBlock, self).__init__()
67
- self.outermost = outermost
68
- if type(norm_layer) == functools.partial:
69
- use_bias = norm_layer.func == nn.InstanceNorm2d
70
- else:
71
- use_bias = norm_layer == nn.InstanceNorm2d
72
- if input_nc is None:
73
- input_nc = outer_nc
74
- downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,
75
- stride=2, padding=1, bias=use_bias)
76
- downrelu = nn.LeakyReLU(0.2, True)
77
- downnorm = norm_layer(inner_nc)
78
- uprelu = nn.ReLU(True)
79
- upnorm = norm_layer(outer_nc)
80
-
81
- if outermost:
82
- upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
83
- kernel_size=4, stride=2,
84
- padding=1)
85
- down = [downconv]
86
- up = [uprelu, upconv, nn.Tanh()]
87
- model = down + [submodule] + up
88
- elif innermost:
89
- upconv = nn.ConvTranspose2d(inner_nc, outer_nc,
90
- kernel_size=4, stride=2,
91
- padding=1, bias=use_bias)
92
- down = [downrelu, downconv]
93
- up = [uprelu, upconv, upnorm]
94
- model = down + up
95
- else:
96
- upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
97
- kernel_size=4, stride=2,
98
- padding=1, bias=use_bias)
99
- down = [downrelu, downconv, downnorm]
100
- up = [uprelu, upconv, upnorm]
101
-
102
- if use_dropout:
103
- model = down + [submodule] + up + [nn.Dropout(0.5)]
104
- else:
105
- model = down + [submodule] + up
106
-
107
- self.model = nn.Sequential(*model)
108
-
109
- def forward(self, x):
110
- if self.outermost:
111
- return self.model(x)
112
- else: # add skip connections
113
- return torch.cat([x, self.model(x)], 1)
114
-
115
-
116
- class LineartAnimeDetector:
117
- def __init__(self, model):
118
- self.model = model
119
-
120
- @classmethod
121
- def from_pretrained(cls, pretrained_model_or_path, filename=None, cache_dir=None, local_files_only=False):
122
- filename = filename or "netG.pth"
123
-
124
- if os.path.isdir(pretrained_model_or_path):
125
- model_path = os.path.join(pretrained_model_or_path, filename)
126
- else:
127
- model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
128
-
129
- norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)
130
- net = UnetGenerator(3, 1, 8, 64, norm_layer=norm_layer, use_dropout=False)
131
- ckpt = torch.load(model_path)
132
- for key in list(ckpt.keys()):
133
- if 'module.' in key:
134
- ckpt[key.replace('module.', '')] = ckpt[key]
135
- del ckpt[key]
136
- net.load_state_dict(ckpt)
137
- net.eval()
138
-
139
- return cls(net)
140
-
141
- def to(self, device):
142
- self.model.to(device)
143
- return self
144
-
145
- def __call__(self, input_image, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
146
- if "return_pil" in kwargs:
147
- warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
148
- output_type = "pil" if kwargs["return_pil"] else "np"
149
- if type(output_type) is bool:
150
- warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
151
- if output_type:
152
- output_type = "pil"
153
-
154
- device = next(iter(self.model.parameters())).device
155
- if not isinstance(input_image, np.ndarray):
156
- input_image = np.array(input_image, dtype=np.uint8)
157
-
158
- input_image = HWC3(input_image)
159
- input_image = resize_image(input_image, detect_resolution)
160
-
161
- H, W, C = input_image.shape
162
- Hn = 256 * int(np.ceil(float(H) / 256.0))
163
- Wn = 256 * int(np.ceil(float(W) / 256.0))
164
- img = cv2.resize(input_image, (Wn, Hn), interpolation=cv2.INTER_CUBIC)
165
- with torch.no_grad():
166
- image_feed = torch.from_numpy(img).float().to(device)
167
- image_feed = image_feed / 127.5 - 1.0
168
- image_feed = rearrange(image_feed, 'h w c -> 1 c h w')
169
-
170
- line = self.model(image_feed)[0, 0] * 127.5 + 127.5
171
- line = line.cpu().numpy()
172
-
173
- line = cv2.resize(line, (W, H), interpolation=cv2.INTER_CUBIC)
174
- line = line.clip(0, 255).astype(np.uint8)
175
-
176
- detected_map = line
177
-
178
- detected_map = HWC3(detected_map)
179
-
180
- img = resize_image(input_image, image_resolution)
181
- H, W, C = img.shape
182
-
183
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
184
- detected_map = 255 - detected_map
185
-
186
- if output_type == "pil":
187
- detected_map = Image.fromarray(detected_map)
188
-
189
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/mediapipe_face/__init__.py DELETED
@@ -1,53 +0,0 @@
1
- import warnings
2
- from typing import Union
3
-
4
- import cv2
5
- import numpy as np
6
- from PIL import Image
7
-
8
- from ..util import HWC3, resize_image
9
- from .mediapipe_face_common import generate_annotation
10
-
11
-
12
- class MediapipeFaceDetector:
13
- def __call__(self,
14
- input_image: Union[np.ndarray, Image.Image] = None,
15
- max_faces: int = 1,
16
- min_confidence: float = 0.5,
17
- output_type: str = "pil",
18
- detect_resolution: int = 512,
19
- image_resolution: int = 512,
20
- **kwargs):
21
-
22
- if "image" in kwargs:
23
- warnings.warn("image is deprecated, please use `input_image=...` instead.", DeprecationWarning)
24
- input_image = kwargs.pop("image")
25
- if input_image is None:
26
- raise ValueError("input_image must be defined.")
27
-
28
- if "return_pil" in kwargs:
29
- warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
30
- output_type = "pil" if kwargs["return_pil"] else "np"
31
- if type(output_type) is bool:
32
- warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
33
- if output_type:
34
- output_type = "pil"
35
-
36
- if not isinstance(input_image, np.ndarray):
37
- input_image = np.array(input_image, dtype=np.uint8)
38
-
39
- input_image = HWC3(input_image)
40
- input_image = resize_image(input_image, detect_resolution)
41
-
42
- detected_map = generate_annotation(input_image, max_faces, min_confidence)
43
- detected_map = HWC3(detected_map)
44
-
45
- img = resize_image(input_image, image_resolution)
46
- H, W, C = img.shape
47
-
48
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
49
-
50
- if output_type == "pil":
51
- detected_map = Image.fromarray(detected_map)
52
-
53
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/mediapipe_face/mediapipe_face_common.py DELETED
@@ -1,164 +0,0 @@
1
- from typing import Mapping
2
- import warnings
3
-
4
- try:
5
- import mediapipe as mp
6
- except ImportError:
7
- warnings.warn(
8
- "The module 'mediapipe' is not installed. The package will have limited functionality. Please install it using the command: pip install 'mediapipe'"
9
- )
10
-
11
- mp = None
12
-
13
- import numpy
14
-
15
- if mp:
16
- mp_drawing = mp.solutions.drawing_utils
17
- mp_drawing_styles = mp.solutions.drawing_styles
18
- mp_face_detection = mp.solutions.face_detection # Only for counting faces.
19
- mp_face_mesh = mp.solutions.face_mesh
20
- mp_face_connections = mp.solutions.face_mesh_connections.FACEMESH_TESSELATION
21
- mp_hand_connections = mp.solutions.hands_connections.HAND_CONNECTIONS
22
- mp_body_connections = mp.solutions.pose_connections.POSE_CONNECTIONS
23
-
24
- DrawingSpec = mp.solutions.drawing_styles.DrawingSpec
25
- PoseLandmark = mp.solutions.drawing_styles.PoseLandmark
26
-
27
- min_face_size_pixels: int = 64
28
- f_thick = 2
29
- f_rad = 1
30
- right_iris_draw = DrawingSpec(color=(10, 200, 250), thickness=f_thick, circle_radius=f_rad)
31
- right_eye_draw = DrawingSpec(color=(10, 200, 180), thickness=f_thick, circle_radius=f_rad)
32
- right_eyebrow_draw = DrawingSpec(color=(10, 220, 180), thickness=f_thick, circle_radius=f_rad)
33
- left_iris_draw = DrawingSpec(color=(250, 200, 10), thickness=f_thick, circle_radius=f_rad)
34
- left_eye_draw = DrawingSpec(color=(180, 200, 10), thickness=f_thick, circle_radius=f_rad)
35
- left_eyebrow_draw = DrawingSpec(color=(180, 220, 10), thickness=f_thick, circle_radius=f_rad)
36
- mouth_draw = DrawingSpec(color=(10, 180, 10), thickness=f_thick, circle_radius=f_rad)
37
- head_draw = DrawingSpec(color=(10, 200, 10), thickness=f_thick, circle_radius=f_rad)
38
-
39
- # mp_face_mesh.FACEMESH_CONTOURS has all the items we care about.
40
- face_connection_spec = {}
41
- for edge in mp_face_mesh.FACEMESH_FACE_OVAL:
42
- face_connection_spec[edge] = head_draw
43
- for edge in mp_face_mesh.FACEMESH_LEFT_EYE:
44
- face_connection_spec[edge] = left_eye_draw
45
- for edge in mp_face_mesh.FACEMESH_LEFT_EYEBROW:
46
- face_connection_spec[edge] = left_eyebrow_draw
47
- # for edge in mp_face_mesh.FACEMESH_LEFT_IRIS:
48
- # face_connection_spec[edge] = left_iris_draw
49
- for edge in mp_face_mesh.FACEMESH_RIGHT_EYE:
50
- face_connection_spec[edge] = right_eye_draw
51
- for edge in mp_face_mesh.FACEMESH_RIGHT_EYEBROW:
52
- face_connection_spec[edge] = right_eyebrow_draw
53
- # for edge in mp_face_mesh.FACEMESH_RIGHT_IRIS:
54
- # face_connection_spec[edge] = right_iris_draw
55
- for edge in mp_face_mesh.FACEMESH_LIPS:
56
- face_connection_spec[edge] = mouth_draw
57
- iris_landmark_spec = {468: right_iris_draw, 473: left_iris_draw}
58
-
59
-
60
- def draw_pupils(image, landmark_list, drawing_spec, halfwidth: int = 2):
61
- """We have a custom function to draw the pupils because the mp.draw_landmarks method requires a parameter for all
62
- landmarks. Until our PR is merged into mediapipe, we need this separate method."""
63
- if len(image.shape) != 3:
64
- raise ValueError("Input image must be H,W,C.")
65
- image_rows, image_cols, image_channels = image.shape
66
- if image_channels != 3: # BGR channels
67
- raise ValueError('Input image must contain three channel bgr data.')
68
- for idx, landmark in enumerate(landmark_list.landmark):
69
- if (
70
- (landmark.HasField('visibility') and landmark.visibility < 0.9) or
71
- (landmark.HasField('presence') and landmark.presence < 0.5)
72
- ):
73
- continue
74
- if landmark.x >= 1.0 or landmark.x < 0 or landmark.y >= 1.0 or landmark.y < 0:
75
- continue
76
- image_x = int(image_cols*landmark.x)
77
- image_y = int(image_rows*landmark.y)
78
- draw_color = None
79
- if isinstance(drawing_spec, Mapping):
80
- if drawing_spec.get(idx) is None:
81
- continue
82
- else:
83
- draw_color = drawing_spec[idx].color
84
- elif isinstance(drawing_spec, DrawingSpec):
85
- draw_color = drawing_spec.color
86
- image[image_y-halfwidth:image_y+halfwidth, image_x-halfwidth:image_x+halfwidth, :] = draw_color
87
-
88
-
89
- def reverse_channels(image):
90
- """Given a numpy array in RGB form, convert to BGR. Will also convert from BGR to RGB."""
91
- # im[:,:,::-1] is a neat hack to convert BGR to RGB by reversing the indexing order.
92
- # im[:,:,::[2,1,0]] would also work but makes a copy of the data.
93
- return image[:, :, ::-1]
94
-
95
-
96
- def generate_annotation(
97
- img_rgb,
98
- max_faces: int,
99
- min_confidence: float
100
- ):
101
- """
102
- Find up to 'max_faces' inside the provided input image.
103
- If min_face_size_pixels is provided and nonzero it will be used to filter faces that occupy less than this many
104
- pixels in the image.
105
- """
106
- with mp_face_mesh.FaceMesh(
107
- static_image_mode=True,
108
- max_num_faces=max_faces,
109
- refine_landmarks=True,
110
- min_detection_confidence=min_confidence,
111
- ) as facemesh:
112
- img_height, img_width, img_channels = img_rgb.shape
113
- assert(img_channels == 3)
114
-
115
- results = facemesh.process(img_rgb).multi_face_landmarks
116
-
117
- if results is None:
118
- print("No faces detected in controlnet image for Mediapipe face annotator.")
119
- return numpy.zeros_like(img_rgb)
120
-
121
- # Filter faces that are too small
122
- filtered_landmarks = []
123
- for lm in results:
124
- landmarks = lm.landmark
125
- face_rect = [
126
- landmarks[0].x,
127
- landmarks[0].y,
128
- landmarks[0].x,
129
- landmarks[0].y,
130
- ] # Left, up, right, down.
131
- for i in range(len(landmarks)):
132
- face_rect[0] = min(face_rect[0], landmarks[i].x)
133
- face_rect[1] = min(face_rect[1], landmarks[i].y)
134
- face_rect[2] = max(face_rect[2], landmarks[i].x)
135
- face_rect[3] = max(face_rect[3], landmarks[i].y)
136
- if min_face_size_pixels > 0:
137
- face_width = abs(face_rect[2] - face_rect[0])
138
- face_height = abs(face_rect[3] - face_rect[1])
139
- face_width_pixels = face_width * img_width
140
- face_height_pixels = face_height * img_height
141
- face_size = min(face_width_pixels, face_height_pixels)
142
- if face_size >= min_face_size_pixels:
143
- filtered_landmarks.append(lm)
144
- else:
145
- filtered_landmarks.append(lm)
146
-
147
- # Annotations are drawn in BGR for some reason, but we don't need to flip a zero-filled image at the start.
148
- empty = numpy.zeros_like(img_rgb)
149
-
150
- # Draw detected faces:
151
- for face_landmarks in filtered_landmarks:
152
- mp_drawing.draw_landmarks(
153
- empty,
154
- face_landmarks,
155
- connections=face_connection_spec.keys(),
156
- landmark_drawing_spec=None,
157
- connection_drawing_spec=face_connection_spec
158
- )
159
- draw_pupils(empty, face_landmarks, iris_landmark_spec, 2)
160
-
161
- # Flip BGR back to RGB.
162
- empty = reverse_channels(empty).copy()
163
-
164
- return empty
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/__init__.py DELETED
@@ -1,95 +0,0 @@
1
- import os
2
-
3
- import cv2
4
- import numpy as np
5
- import torch
6
- from einops import rearrange
7
- from huggingface_hub import hf_hub_download
8
- from PIL import Image
9
-
10
- from ..util import HWC3, resize_image
11
- from .api import MiDaSInference
12
-
13
-
14
- class MidasDetector:
15
- def __init__(self, model):
16
- self.model = model
17
-
18
- @classmethod
19
- def from_pretrained(cls, pretrained_model_or_path, model_type="dpt_hybrid", filename=None, cache_dir=None, local_files_only=False):
20
- if pretrained_model_or_path == "lllyasviel/ControlNet":
21
- filename = filename or "annotator/ckpts/dpt_hybrid-midas-501f0c75.pt"
22
- else:
23
- filename = filename or "dpt_hybrid-midas-501f0c75.pt"
24
-
25
- if os.path.isdir(pretrained_model_or_path):
26
- model_path = os.path.join(pretrained_model_or_path, filename)
27
- else:
28
- model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
29
-
30
- model = MiDaSInference(model_type=model_type, model_path=model_path)
31
-
32
- return cls(model)
33
-
34
-
35
- def to(self, device):
36
- self.model.to(device)
37
- return self
38
-
39
- def __call__(self, input_image, a=np.pi * 2.0, bg_th=0.1, depth_and_normal=False, detect_resolution=512, image_resolution=512, output_type=None):
40
- device = next(iter(self.model.parameters())).device
41
- if not isinstance(input_image, np.ndarray):
42
- input_image = np.array(input_image, dtype=np.uint8)
43
- output_type = output_type or "pil"
44
- else:
45
- output_type = output_type or "np"
46
-
47
- input_image = HWC3(input_image)
48
- input_image = resize_image(input_image, detect_resolution)
49
-
50
- assert input_image.ndim == 3
51
- image_depth = input_image
52
- with torch.no_grad():
53
- image_depth = torch.from_numpy(image_depth).float()
54
- image_depth = image_depth.to(device)
55
- image_depth = image_depth / 127.5 - 1.0
56
- image_depth = rearrange(image_depth, 'h w c -> 1 c h w')
57
- depth = self.model(image_depth)[0]
58
-
59
- depth_pt = depth.clone()
60
- depth_pt -= torch.min(depth_pt)
61
- depth_pt /= torch.max(depth_pt)
62
- depth_pt = depth_pt.cpu().numpy()
63
- depth_image = (depth_pt * 255.0).clip(0, 255).astype(np.uint8)
64
-
65
- if depth_and_normal:
66
- depth_np = depth.cpu().numpy()
67
- x = cv2.Sobel(depth_np, cv2.CV_32F, 1, 0, ksize=3)
68
- y = cv2.Sobel(depth_np, cv2.CV_32F, 0, 1, ksize=3)
69
- z = np.ones_like(x) * a
70
- x[depth_pt < bg_th] = 0
71
- y[depth_pt < bg_th] = 0
72
- normal = np.stack([x, y, z], axis=2)
73
- normal /= np.sum(normal ** 2.0, axis=2, keepdims=True) ** 0.5
74
- normal_image = (normal * 127.5 + 127.5).clip(0, 255).astype(np.uint8)[:, :, ::-1]
75
-
76
- depth_image = HWC3(depth_image)
77
- if depth_and_normal:
78
- normal_image = HWC3(normal_image)
79
-
80
- img = resize_image(input_image, image_resolution)
81
- H, W, C = img.shape
82
-
83
- depth_image = cv2.resize(depth_image, (W, H), interpolation=cv2.INTER_LINEAR)
84
- if depth_and_normal:
85
- normal_image = cv2.resize(normal_image, (W, H), interpolation=cv2.INTER_LINEAR)
86
-
87
- if output_type == "pil":
88
- depth_image = Image.fromarray(depth_image)
89
- if depth_and_normal:
90
- normal_image = Image.fromarray(normal_image)
91
-
92
- if depth_and_normal:
93
- return depth_image, normal_image
94
- else:
95
- return depth_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/api.py DELETED
@@ -1,169 +0,0 @@
1
- # based on https://github.com/isl-org/MiDaS
2
-
3
- import cv2
4
- import os
5
- import torch
6
- import torch.nn as nn
7
- from torchvision.transforms import Compose
8
-
9
- from .midas.dpt_depth import DPTDepthModel
10
- from .midas.midas_net import MidasNet
11
- from .midas.midas_net_custom import MidasNet_small
12
- from .midas.transforms import Resize, NormalizeImage, PrepareForNet
13
- from ..util import annotator_ckpts_path
14
-
15
-
16
- ISL_PATHS = {
17
- "dpt_large": os.path.join(annotator_ckpts_path, "dpt_large-midas-2f21e586.pt"),
18
- "dpt_hybrid": os.path.join(annotator_ckpts_path, "dpt_hybrid-midas-501f0c75.pt"),
19
- "midas_v21": "",
20
- "midas_v21_small": "",
21
- }
22
-
23
- remote_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/dpt_hybrid-midas-501f0c75.pt"
24
-
25
-
26
- def disabled_train(self, mode=True):
27
- """Overwrite model.train with this function to make sure train/eval mode
28
- does not change anymore."""
29
- return self
30
-
31
-
32
- def load_midas_transform(model_type):
33
- # https://github.com/isl-org/MiDaS/blob/master/run.py
34
- # load transform only
35
- if model_type == "dpt_large": # DPT-Large
36
- net_w, net_h = 384, 384
37
- resize_mode = "minimal"
38
- normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
39
-
40
- elif model_type == "dpt_hybrid": # DPT-Hybrid
41
- net_w, net_h = 384, 384
42
- resize_mode = "minimal"
43
- normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
44
-
45
- elif model_type == "midas_v21":
46
- net_w, net_h = 384, 384
47
- resize_mode = "upper_bound"
48
- normalization = NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
49
-
50
- elif model_type == "midas_v21_small":
51
- net_w, net_h = 256, 256
52
- resize_mode = "upper_bound"
53
- normalization = NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
54
-
55
- else:
56
- assert False, f"model_type '{model_type}' not implemented, use: --model_type large"
57
-
58
- transform = Compose(
59
- [
60
- Resize(
61
- net_w,
62
- net_h,
63
- resize_target=None,
64
- keep_aspect_ratio=True,
65
- ensure_multiple_of=32,
66
- resize_method=resize_mode,
67
- image_interpolation_method=cv2.INTER_CUBIC,
68
- ),
69
- normalization,
70
- PrepareForNet(),
71
- ]
72
- )
73
-
74
- return transform
75
-
76
-
77
- def load_model(model_type, model_path=None):
78
- # https://github.com/isl-org/MiDaS/blob/master/run.py
79
- # load network
80
- model_path = model_path or ISL_PATHS[model_type]
81
- if model_type == "dpt_large": # DPT-Large
82
- model = DPTDepthModel(
83
- path=model_path,
84
- backbone="vitl16_384",
85
- non_negative=True,
86
- )
87
- net_w, net_h = 384, 384
88
- resize_mode = "minimal"
89
- normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
90
-
91
- elif model_type == "dpt_hybrid": # DPT-Hybrid
92
- if not os.path.exists(model_path):
93
- from basicsr.utils.download_util import load_file_from_url
94
- load_file_from_url(remote_model_path, model_dir=annotator_ckpts_path)
95
-
96
- model = DPTDepthModel(
97
- path=model_path,
98
- backbone="vitb_rn50_384",
99
- non_negative=True,
100
- )
101
- net_w, net_h = 384, 384
102
- resize_mode = "minimal"
103
- normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
104
-
105
- elif model_type == "midas_v21":
106
- model = MidasNet(model_path, non_negative=True)
107
- net_w, net_h = 384, 384
108
- resize_mode = "upper_bound"
109
- normalization = NormalizeImage(
110
- mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
111
- )
112
-
113
- elif model_type == "midas_v21_small":
114
- model = MidasNet_small(model_path, features=64, backbone="efficientnet_lite3", exportable=True,
115
- non_negative=True, blocks={'expand': True})
116
- net_w, net_h = 256, 256
117
- resize_mode = "upper_bound"
118
- normalization = NormalizeImage(
119
- mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
120
- )
121
-
122
- else:
123
- print(f"model_type '{model_type}' not implemented, use: --model_type large")
124
- assert False
125
-
126
- transform = Compose(
127
- [
128
- Resize(
129
- net_w,
130
- net_h,
131
- resize_target=None,
132
- keep_aspect_ratio=True,
133
- ensure_multiple_of=32,
134
- resize_method=resize_mode,
135
- image_interpolation_method=cv2.INTER_CUBIC,
136
- ),
137
- normalization,
138
- PrepareForNet(),
139
- ]
140
- )
141
-
142
- return model.eval(), transform
143
-
144
-
145
- class MiDaSInference(nn.Module):
146
- MODEL_TYPES_TORCH_HUB = [
147
- "DPT_Large",
148
- "DPT_Hybrid",
149
- "MiDaS_small"
150
- ]
151
- MODEL_TYPES_ISL = [
152
- "dpt_large",
153
- "dpt_hybrid",
154
- "midas_v21",
155
- "midas_v21_small",
156
- ]
157
-
158
- def __init__(self, model_type, model_path):
159
- super().__init__()
160
- assert (model_type in self.MODEL_TYPES_ISL)
161
- model, _ = load_model(model_type, model_path)
162
- self.model = model
163
- self.model.train = disabled_train
164
-
165
- def forward(self, x):
166
- with torch.no_grad():
167
- prediction = self.model(x)
168
- return prediction
169
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/__init__.py DELETED
File without changes
controlnet_aux_local/midas/midas/base_model.py DELETED
@@ -1,16 +0,0 @@
1
- import torch
2
-
3
-
4
- class BaseModel(torch.nn.Module):
5
- def load(self, path):
6
- """Load model from file.
7
-
8
- Args:
9
- path (str): file path
10
- """
11
- parameters = torch.load(path, map_location=torch.device('cpu'))
12
-
13
- if "optimizer" in parameters:
14
- parameters = parameters["model"]
15
-
16
- self.load_state_dict(parameters)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/blocks.py DELETED
@@ -1,342 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
-
4
- from .vit import (
5
- _make_pretrained_vitb_rn50_384,
6
- _make_pretrained_vitl16_384,
7
- _make_pretrained_vitb16_384,
8
- forward_vit,
9
- )
10
-
11
- def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore",):
12
- if backbone == "vitl16_384":
13
- pretrained = _make_pretrained_vitl16_384(
14
- use_pretrained, hooks=hooks, use_readout=use_readout
15
- )
16
- scratch = _make_scratch(
17
- [256, 512, 1024, 1024], features, groups=groups, expand=expand
18
- ) # ViT-L/16 - 85.0% Top1 (backbone)
19
- elif backbone == "vitb_rn50_384":
20
- pretrained = _make_pretrained_vitb_rn50_384(
21
- use_pretrained,
22
- hooks=hooks,
23
- use_vit_only=use_vit_only,
24
- use_readout=use_readout,
25
- )
26
- scratch = _make_scratch(
27
- [256, 512, 768, 768], features, groups=groups, expand=expand
28
- ) # ViT-H/16 - 85.0% Top1 (backbone)
29
- elif backbone == "vitb16_384":
30
- pretrained = _make_pretrained_vitb16_384(
31
- use_pretrained, hooks=hooks, use_readout=use_readout
32
- )
33
- scratch = _make_scratch(
34
- [96, 192, 384, 768], features, groups=groups, expand=expand
35
- ) # ViT-B/16 - 84.6% Top1 (backbone)
36
- elif backbone == "resnext101_wsl":
37
- pretrained = _make_pretrained_resnext101_wsl(use_pretrained)
38
- scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3
39
- elif backbone == "efficientnet_lite3":
40
- pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable)
41
- scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3
42
- else:
43
- print(f"Backbone '{backbone}' not implemented")
44
- assert False
45
-
46
- return pretrained, scratch
47
-
48
-
49
- def _make_scratch(in_shape, out_shape, groups=1, expand=False):
50
- scratch = nn.Module()
51
-
52
- out_shape1 = out_shape
53
- out_shape2 = out_shape
54
- out_shape3 = out_shape
55
- out_shape4 = out_shape
56
- if expand==True:
57
- out_shape1 = out_shape
58
- out_shape2 = out_shape*2
59
- out_shape3 = out_shape*4
60
- out_shape4 = out_shape*8
61
-
62
- scratch.layer1_rn = nn.Conv2d(
63
- in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
64
- )
65
- scratch.layer2_rn = nn.Conv2d(
66
- in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
67
- )
68
- scratch.layer3_rn = nn.Conv2d(
69
- in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
70
- )
71
- scratch.layer4_rn = nn.Conv2d(
72
- in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
73
- )
74
-
75
- return scratch
76
-
77
-
78
- def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False):
79
- efficientnet = torch.hub.load(
80
- "rwightman/gen-efficientnet-pytorch",
81
- "tf_efficientnet_lite3",
82
- pretrained=use_pretrained,
83
- exportable=exportable
84
- )
85
- return _make_efficientnet_backbone(efficientnet)
86
-
87
-
88
- def _make_efficientnet_backbone(effnet):
89
- pretrained = nn.Module()
90
-
91
- pretrained.layer1 = nn.Sequential(
92
- effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2]
93
- )
94
- pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3])
95
- pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5])
96
- pretrained.layer4 = nn.Sequential(*effnet.blocks[5:9])
97
-
98
- return pretrained
99
-
100
-
101
- def _make_resnet_backbone(resnet):
102
- pretrained = nn.Module()
103
- pretrained.layer1 = nn.Sequential(
104
- resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1
105
- )
106
-
107
- pretrained.layer2 = resnet.layer2
108
- pretrained.layer3 = resnet.layer3
109
- pretrained.layer4 = resnet.layer4
110
-
111
- return pretrained
112
-
113
-
114
- def _make_pretrained_resnext101_wsl(use_pretrained):
115
- resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl")
116
- return _make_resnet_backbone(resnet)
117
-
118
-
119
-
120
- class Interpolate(nn.Module):
121
- """Interpolation module.
122
- """
123
-
124
- def __init__(self, scale_factor, mode, align_corners=False):
125
- """Init.
126
-
127
- Args:
128
- scale_factor (float): scaling
129
- mode (str): interpolation mode
130
- """
131
- super(Interpolate, self).__init__()
132
-
133
- self.interp = nn.functional.interpolate
134
- self.scale_factor = scale_factor
135
- self.mode = mode
136
- self.align_corners = align_corners
137
-
138
- def forward(self, x):
139
- """Forward pass.
140
-
141
- Args:
142
- x (tensor): input
143
-
144
- Returns:
145
- tensor: interpolated data
146
- """
147
-
148
- x = self.interp(
149
- x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners
150
- )
151
-
152
- return x
153
-
154
-
155
- class ResidualConvUnit(nn.Module):
156
- """Residual convolution module.
157
- """
158
-
159
- def __init__(self, features):
160
- """Init.
161
-
162
- Args:
163
- features (int): number of features
164
- """
165
- super().__init__()
166
-
167
- self.conv1 = nn.Conv2d(
168
- features, features, kernel_size=3, stride=1, padding=1, bias=True
169
- )
170
-
171
- self.conv2 = nn.Conv2d(
172
- features, features, kernel_size=3, stride=1, padding=1, bias=True
173
- )
174
-
175
- self.relu = nn.ReLU(inplace=True)
176
-
177
- def forward(self, x):
178
- """Forward pass.
179
-
180
- Args:
181
- x (tensor): input
182
-
183
- Returns:
184
- tensor: output
185
- """
186
- out = self.relu(x)
187
- out = self.conv1(out)
188
- out = self.relu(out)
189
- out = self.conv2(out)
190
-
191
- return out + x
192
-
193
-
194
- class FeatureFusionBlock(nn.Module):
195
- """Feature fusion block.
196
- """
197
-
198
- def __init__(self, features):
199
- """Init.
200
-
201
- Args:
202
- features (int): number of features
203
- """
204
- super(FeatureFusionBlock, self).__init__()
205
-
206
- self.resConfUnit1 = ResidualConvUnit(features)
207
- self.resConfUnit2 = ResidualConvUnit(features)
208
-
209
- def forward(self, *xs):
210
- """Forward pass.
211
-
212
- Returns:
213
- tensor: output
214
- """
215
- output = xs[0]
216
-
217
- if len(xs) == 2:
218
- output += self.resConfUnit1(xs[1])
219
-
220
- output = self.resConfUnit2(output)
221
-
222
- output = nn.functional.interpolate(
223
- output, scale_factor=2, mode="bilinear", align_corners=True
224
- )
225
-
226
- return output
227
-
228
-
229
-
230
-
231
- class ResidualConvUnit_custom(nn.Module):
232
- """Residual convolution module.
233
- """
234
-
235
- def __init__(self, features, activation, bn):
236
- """Init.
237
-
238
- Args:
239
- features (int): number of features
240
- """
241
- super().__init__()
242
-
243
- self.bn = bn
244
-
245
- self.groups=1
246
-
247
- self.conv1 = nn.Conv2d(
248
- features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
249
- )
250
-
251
- self.conv2 = nn.Conv2d(
252
- features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
253
- )
254
-
255
- if self.bn==True:
256
- self.bn1 = nn.BatchNorm2d(features)
257
- self.bn2 = nn.BatchNorm2d(features)
258
-
259
- self.activation = activation
260
-
261
- self.skip_add = nn.quantized.FloatFunctional()
262
-
263
- def forward(self, x):
264
- """Forward pass.
265
-
266
- Args:
267
- x (tensor): input
268
-
269
- Returns:
270
- tensor: output
271
- """
272
-
273
- out = self.activation(x)
274
- out = self.conv1(out)
275
- if self.bn==True:
276
- out = self.bn1(out)
277
-
278
- out = self.activation(out)
279
- out = self.conv2(out)
280
- if self.bn==True:
281
- out = self.bn2(out)
282
-
283
- if self.groups > 1:
284
- out = self.conv_merge(out)
285
-
286
- return self.skip_add.add(out, x)
287
-
288
- # return out + x
289
-
290
-
291
- class FeatureFusionBlock_custom(nn.Module):
292
- """Feature fusion block.
293
- """
294
-
295
- def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True):
296
- """Init.
297
-
298
- Args:
299
- features (int): number of features
300
- """
301
- super(FeatureFusionBlock_custom, self).__init__()
302
-
303
- self.deconv = deconv
304
- self.align_corners = align_corners
305
-
306
- self.groups=1
307
-
308
- self.expand = expand
309
- out_features = features
310
- if self.expand==True:
311
- out_features = features//2
312
-
313
- self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
314
-
315
- self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn)
316
- self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn)
317
-
318
- self.skip_add = nn.quantized.FloatFunctional()
319
-
320
- def forward(self, *xs):
321
- """Forward pass.
322
-
323
- Returns:
324
- tensor: output
325
- """
326
- output = xs[0]
327
-
328
- if len(xs) == 2:
329
- res = self.resConfUnit1(xs[1])
330
- output = self.skip_add.add(output, res)
331
- # output += res
332
-
333
- output = self.resConfUnit2(output)
334
-
335
- output = nn.functional.interpolate(
336
- output, scale_factor=2, mode="bilinear", align_corners=self.align_corners
337
- )
338
-
339
- output = self.out_conv(output)
340
-
341
- return output
342
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/dpt_depth.py DELETED
@@ -1,109 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.nn.functional as F
4
-
5
- from .base_model import BaseModel
6
- from .blocks import (
7
- FeatureFusionBlock,
8
- FeatureFusionBlock_custom,
9
- Interpolate,
10
- _make_encoder,
11
- forward_vit,
12
- )
13
-
14
-
15
- def _make_fusion_block(features, use_bn):
16
- return FeatureFusionBlock_custom(
17
- features,
18
- nn.ReLU(False),
19
- deconv=False,
20
- bn=use_bn,
21
- expand=False,
22
- align_corners=True,
23
- )
24
-
25
-
26
- class DPT(BaseModel):
27
- def __init__(
28
- self,
29
- head,
30
- features=256,
31
- backbone="vitb_rn50_384",
32
- readout="project",
33
- channels_last=False,
34
- use_bn=False,
35
- ):
36
-
37
- super(DPT, self).__init__()
38
-
39
- self.channels_last = channels_last
40
-
41
- hooks = {
42
- "vitb_rn50_384": [0, 1, 8, 11],
43
- "vitb16_384": [2, 5, 8, 11],
44
- "vitl16_384": [5, 11, 17, 23],
45
- }
46
-
47
- # Instantiate backbone and reassemble blocks
48
- self.pretrained, self.scratch = _make_encoder(
49
- backbone,
50
- features,
51
- False, # Set to true of you want to train from scratch, uses ImageNet weights
52
- groups=1,
53
- expand=False,
54
- exportable=False,
55
- hooks=hooks[backbone],
56
- use_readout=readout,
57
- )
58
-
59
- self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
60
- self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
61
- self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
62
- self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
63
-
64
- self.scratch.output_conv = head
65
-
66
-
67
- def forward(self, x):
68
- if self.channels_last == True:
69
- x.contiguous(memory_format=torch.channels_last)
70
-
71
- layer_1, layer_2, layer_3, layer_4 = forward_vit(self.pretrained, x)
72
-
73
- layer_1_rn = self.scratch.layer1_rn(layer_1)
74
- layer_2_rn = self.scratch.layer2_rn(layer_2)
75
- layer_3_rn = self.scratch.layer3_rn(layer_3)
76
- layer_4_rn = self.scratch.layer4_rn(layer_4)
77
-
78
- path_4 = self.scratch.refinenet4(layer_4_rn)
79
- path_3 = self.scratch.refinenet3(path_4, layer_3_rn)
80
- path_2 = self.scratch.refinenet2(path_3, layer_2_rn)
81
- path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
82
-
83
- out = self.scratch.output_conv(path_1)
84
-
85
- return out
86
-
87
-
88
- class DPTDepthModel(DPT):
89
- def __init__(self, path=None, non_negative=True, **kwargs):
90
- features = kwargs["features"] if "features" in kwargs else 256
91
-
92
- head = nn.Sequential(
93
- nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1),
94
- Interpolate(scale_factor=2, mode="bilinear", align_corners=True),
95
- nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1),
96
- nn.ReLU(True),
97
- nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
98
- nn.ReLU(True) if non_negative else nn.Identity(),
99
- nn.Identity(),
100
- )
101
-
102
- super().__init__(head, **kwargs)
103
-
104
- if path is not None:
105
- self.load(path)
106
-
107
- def forward(self, x):
108
- return super().forward(x).squeeze(dim=1)
109
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/midas_net.py DELETED
@@ -1,76 +0,0 @@
1
- """MidashNet: Network for monocular depth estimation trained by mixing several datasets.
2
- This file contains code that is adapted from
3
- https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py
4
- """
5
- import torch
6
- import torch.nn as nn
7
-
8
- from .base_model import BaseModel
9
- from .blocks import FeatureFusionBlock, Interpolate, _make_encoder
10
-
11
-
12
- class MidasNet(BaseModel):
13
- """Network for monocular depth estimation.
14
- """
15
-
16
- def __init__(self, path=None, features=256, non_negative=True):
17
- """Init.
18
-
19
- Args:
20
- path (str, optional): Path to saved model. Defaults to None.
21
- features (int, optional): Number of features. Defaults to 256.
22
- backbone (str, optional): Backbone network for encoder. Defaults to resnet50
23
- """
24
- print("Loading weights: ", path)
25
-
26
- super(MidasNet, self).__init__()
27
-
28
- use_pretrained = False if path is None else True
29
-
30
- self.pretrained, self.scratch = _make_encoder(backbone="resnext101_wsl", features=features, use_pretrained=use_pretrained)
31
-
32
- self.scratch.refinenet4 = FeatureFusionBlock(features)
33
- self.scratch.refinenet3 = FeatureFusionBlock(features)
34
- self.scratch.refinenet2 = FeatureFusionBlock(features)
35
- self.scratch.refinenet1 = FeatureFusionBlock(features)
36
-
37
- self.scratch.output_conv = nn.Sequential(
38
- nn.Conv2d(features, 128, kernel_size=3, stride=1, padding=1),
39
- Interpolate(scale_factor=2, mode="bilinear"),
40
- nn.Conv2d(128, 32, kernel_size=3, stride=1, padding=1),
41
- nn.ReLU(True),
42
- nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
43
- nn.ReLU(True) if non_negative else nn.Identity(),
44
- )
45
-
46
- if path:
47
- self.load(path)
48
-
49
- def forward(self, x):
50
- """Forward pass.
51
-
52
- Args:
53
- x (tensor): input data (image)
54
-
55
- Returns:
56
- tensor: depth
57
- """
58
-
59
- layer_1 = self.pretrained.layer1(x)
60
- layer_2 = self.pretrained.layer2(layer_1)
61
- layer_3 = self.pretrained.layer3(layer_2)
62
- layer_4 = self.pretrained.layer4(layer_3)
63
-
64
- layer_1_rn = self.scratch.layer1_rn(layer_1)
65
- layer_2_rn = self.scratch.layer2_rn(layer_2)
66
- layer_3_rn = self.scratch.layer3_rn(layer_3)
67
- layer_4_rn = self.scratch.layer4_rn(layer_4)
68
-
69
- path_4 = self.scratch.refinenet4(layer_4_rn)
70
- path_3 = self.scratch.refinenet3(path_4, layer_3_rn)
71
- path_2 = self.scratch.refinenet2(path_3, layer_2_rn)
72
- path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
73
-
74
- out = self.scratch.output_conv(path_1)
75
-
76
- return torch.squeeze(out, dim=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/midas_net_custom.py DELETED
@@ -1,128 +0,0 @@
1
- """MidashNet: Network for monocular depth estimation trained by mixing several datasets.
2
- This file contains code that is adapted from
3
- https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py
4
- """
5
- import torch
6
- import torch.nn as nn
7
-
8
- from .base_model import BaseModel
9
- from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder
10
-
11
-
12
- class MidasNet_small(BaseModel):
13
- """Network for monocular depth estimation.
14
- """
15
-
16
- def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negative=True, exportable=True, channels_last=False, align_corners=True,
17
- blocks={'expand': True}):
18
- """Init.
19
-
20
- Args:
21
- path (str, optional): Path to saved model. Defaults to None.
22
- features (int, optional): Number of features. Defaults to 256.
23
- backbone (str, optional): Backbone network for encoder. Defaults to resnet50
24
- """
25
- print("Loading weights: ", path)
26
-
27
- super(MidasNet_small, self).__init__()
28
-
29
- use_pretrained = False if path else True
30
-
31
- self.channels_last = channels_last
32
- self.blocks = blocks
33
- self.backbone = backbone
34
-
35
- self.groups = 1
36
-
37
- features1=features
38
- features2=features
39
- features3=features
40
- features4=features
41
- self.expand = False
42
- if "expand" in self.blocks and self.blocks['expand'] == True:
43
- self.expand = True
44
- features1=features
45
- features2=features*2
46
- features3=features*4
47
- features4=features*8
48
-
49
- self.pretrained, self.scratch = _make_encoder(self.backbone, features, use_pretrained, groups=self.groups, expand=self.expand, exportable=exportable)
50
-
51
- self.scratch.activation = nn.ReLU(False)
52
-
53
- self.scratch.refinenet4 = FeatureFusionBlock_custom(features4, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners)
54
- self.scratch.refinenet3 = FeatureFusionBlock_custom(features3, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners)
55
- self.scratch.refinenet2 = FeatureFusionBlock_custom(features2, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners)
56
- self.scratch.refinenet1 = FeatureFusionBlock_custom(features1, self.scratch.activation, deconv=False, bn=False, align_corners=align_corners)
57
-
58
-
59
- self.scratch.output_conv = nn.Sequential(
60
- nn.Conv2d(features, features//2, kernel_size=3, stride=1, padding=1, groups=self.groups),
61
- Interpolate(scale_factor=2, mode="bilinear"),
62
- nn.Conv2d(features//2, 32, kernel_size=3, stride=1, padding=1),
63
- self.scratch.activation,
64
- nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
65
- nn.ReLU(True) if non_negative else nn.Identity(),
66
- nn.Identity(),
67
- )
68
-
69
- if path:
70
- self.load(path)
71
-
72
-
73
- def forward(self, x):
74
- """Forward pass.
75
-
76
- Args:
77
- x (tensor): input data (image)
78
-
79
- Returns:
80
- tensor: depth
81
- """
82
- if self.channels_last==True:
83
- print("self.channels_last = ", self.channels_last)
84
- x.contiguous(memory_format=torch.channels_last)
85
-
86
-
87
- layer_1 = self.pretrained.layer1(x)
88
- layer_2 = self.pretrained.layer2(layer_1)
89
- layer_3 = self.pretrained.layer3(layer_2)
90
- layer_4 = self.pretrained.layer4(layer_3)
91
-
92
- layer_1_rn = self.scratch.layer1_rn(layer_1)
93
- layer_2_rn = self.scratch.layer2_rn(layer_2)
94
- layer_3_rn = self.scratch.layer3_rn(layer_3)
95
- layer_4_rn = self.scratch.layer4_rn(layer_4)
96
-
97
-
98
- path_4 = self.scratch.refinenet4(layer_4_rn)
99
- path_3 = self.scratch.refinenet3(path_4, layer_3_rn)
100
- path_2 = self.scratch.refinenet2(path_3, layer_2_rn)
101
- path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
102
-
103
- out = self.scratch.output_conv(path_1)
104
-
105
- return torch.squeeze(out, dim=1)
106
-
107
-
108
-
109
- def fuse_model(m):
110
- prev_previous_type = nn.Identity()
111
- prev_previous_name = ''
112
- previous_type = nn.Identity()
113
- previous_name = ''
114
- for name, module in m.named_modules():
115
- if prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d and type(module) == nn.ReLU:
116
- # print("FUSED ", prev_previous_name, previous_name, name)
117
- torch.quantization.fuse_modules(m, [prev_previous_name, previous_name, name], inplace=True)
118
- elif prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d:
119
- # print("FUSED ", prev_previous_name, previous_name)
120
- torch.quantization.fuse_modules(m, [prev_previous_name, previous_name], inplace=True)
121
- # elif previous_type == nn.Conv2d and type(module) == nn.ReLU:
122
- # print("FUSED ", previous_name, name)
123
- # torch.quantization.fuse_modules(m, [previous_name, name], inplace=True)
124
-
125
- prev_previous_type = previous_type
126
- prev_previous_name = previous_name
127
- previous_type = type(module)
128
- previous_name = name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/transforms.py DELETED
@@ -1,234 +0,0 @@
1
- import numpy as np
2
- import cv2
3
- import math
4
-
5
-
6
- def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA):
7
- """Rezise the sample to ensure the given size. Keeps aspect ratio.
8
-
9
- Args:
10
- sample (dict): sample
11
- size (tuple): image size
12
-
13
- Returns:
14
- tuple: new size
15
- """
16
- shape = list(sample["disparity"].shape)
17
-
18
- if shape[0] >= size[0] and shape[1] >= size[1]:
19
- return sample
20
-
21
- scale = [0, 0]
22
- scale[0] = size[0] / shape[0]
23
- scale[1] = size[1] / shape[1]
24
-
25
- scale = max(scale)
26
-
27
- shape[0] = math.ceil(scale * shape[0])
28
- shape[1] = math.ceil(scale * shape[1])
29
-
30
- # resize
31
- sample["image"] = cv2.resize(
32
- sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method
33
- )
34
-
35
- sample["disparity"] = cv2.resize(
36
- sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST
37
- )
38
- sample["mask"] = cv2.resize(
39
- sample["mask"].astype(np.float32),
40
- tuple(shape[::-1]),
41
- interpolation=cv2.INTER_NEAREST,
42
- )
43
- sample["mask"] = sample["mask"].astype(bool)
44
-
45
- return tuple(shape)
46
-
47
-
48
- class Resize(object):
49
- """Resize sample to given size (width, height).
50
- """
51
-
52
- def __init__(
53
- self,
54
- width,
55
- height,
56
- resize_target=True,
57
- keep_aspect_ratio=False,
58
- ensure_multiple_of=1,
59
- resize_method="lower_bound",
60
- image_interpolation_method=cv2.INTER_AREA,
61
- ):
62
- """Init.
63
-
64
- Args:
65
- width (int): desired output width
66
- height (int): desired output height
67
- resize_target (bool, optional):
68
- True: Resize the full sample (image, mask, target).
69
- False: Resize image only.
70
- Defaults to True.
71
- keep_aspect_ratio (bool, optional):
72
- True: Keep the aspect ratio of the input sample.
73
- Output sample might not have the given width and height, and
74
- resize behaviour depends on the parameter 'resize_method'.
75
- Defaults to False.
76
- ensure_multiple_of (int, optional):
77
- Output width and height is constrained to be multiple of this parameter.
78
- Defaults to 1.
79
- resize_method (str, optional):
80
- "lower_bound": Output will be at least as large as the given size.
81
- "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
82
- "minimal": Scale as least as possible. (Output size might be smaller than given size.)
83
- Defaults to "lower_bound".
84
- """
85
- self.__width = width
86
- self.__height = height
87
-
88
- self.__resize_target = resize_target
89
- self.__keep_aspect_ratio = keep_aspect_ratio
90
- self.__multiple_of = ensure_multiple_of
91
- self.__resize_method = resize_method
92
- self.__image_interpolation_method = image_interpolation_method
93
-
94
- def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
95
- y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
96
-
97
- if max_val is not None and y > max_val:
98
- y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
99
-
100
- if y < min_val:
101
- y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
102
-
103
- return y
104
-
105
- def get_size(self, width, height):
106
- # determine new height and width
107
- scale_height = self.__height / height
108
- scale_width = self.__width / width
109
-
110
- if self.__keep_aspect_ratio:
111
- if self.__resize_method == "lower_bound":
112
- # scale such that output size is lower bound
113
- if scale_width > scale_height:
114
- # fit width
115
- scale_height = scale_width
116
- else:
117
- # fit height
118
- scale_width = scale_height
119
- elif self.__resize_method == "upper_bound":
120
- # scale such that output size is upper bound
121
- if scale_width < scale_height:
122
- # fit width
123
- scale_height = scale_width
124
- else:
125
- # fit height
126
- scale_width = scale_height
127
- elif self.__resize_method == "minimal":
128
- # scale as least as possbile
129
- if abs(1 - scale_width) < abs(1 - scale_height):
130
- # fit width
131
- scale_height = scale_width
132
- else:
133
- # fit height
134
- scale_width = scale_height
135
- else:
136
- raise ValueError(
137
- f"resize_method {self.__resize_method} not implemented"
138
- )
139
-
140
- if self.__resize_method == "lower_bound":
141
- new_height = self.constrain_to_multiple_of(
142
- scale_height * height, min_val=self.__height
143
- )
144
- new_width = self.constrain_to_multiple_of(
145
- scale_width * width, min_val=self.__width
146
- )
147
- elif self.__resize_method == "upper_bound":
148
- new_height = self.constrain_to_multiple_of(
149
- scale_height * height, max_val=self.__height
150
- )
151
- new_width = self.constrain_to_multiple_of(
152
- scale_width * width, max_val=self.__width
153
- )
154
- elif self.__resize_method == "minimal":
155
- new_height = self.constrain_to_multiple_of(scale_height * height)
156
- new_width = self.constrain_to_multiple_of(scale_width * width)
157
- else:
158
- raise ValueError(f"resize_method {self.__resize_method} not implemented")
159
-
160
- return (new_width, new_height)
161
-
162
- def __call__(self, sample):
163
- width, height = self.get_size(
164
- sample["image"].shape[1], sample["image"].shape[0]
165
- )
166
-
167
- # resize sample
168
- sample["image"] = cv2.resize(
169
- sample["image"],
170
- (width, height),
171
- interpolation=self.__image_interpolation_method,
172
- )
173
-
174
- if self.__resize_target:
175
- if "disparity" in sample:
176
- sample["disparity"] = cv2.resize(
177
- sample["disparity"],
178
- (width, height),
179
- interpolation=cv2.INTER_NEAREST,
180
- )
181
-
182
- if "depth" in sample:
183
- sample["depth"] = cv2.resize(
184
- sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST
185
- )
186
-
187
- sample["mask"] = cv2.resize(
188
- sample["mask"].astype(np.float32),
189
- (width, height),
190
- interpolation=cv2.INTER_NEAREST,
191
- )
192
- sample["mask"] = sample["mask"].astype(bool)
193
-
194
- return sample
195
-
196
-
197
- class NormalizeImage(object):
198
- """Normlize image by given mean and std.
199
- """
200
-
201
- def __init__(self, mean, std):
202
- self.__mean = mean
203
- self.__std = std
204
-
205
- def __call__(self, sample):
206
- sample["image"] = (sample["image"] - self.__mean) / self.__std
207
-
208
- return sample
209
-
210
-
211
- class PrepareForNet(object):
212
- """Prepare sample for usage as network input.
213
- """
214
-
215
- def __init__(self):
216
- pass
217
-
218
- def __call__(self, sample):
219
- image = np.transpose(sample["image"], (2, 0, 1))
220
- sample["image"] = np.ascontiguousarray(image).astype(np.float32)
221
-
222
- if "mask" in sample:
223
- sample["mask"] = sample["mask"].astype(np.float32)
224
- sample["mask"] = np.ascontiguousarray(sample["mask"])
225
-
226
- if "disparity" in sample:
227
- disparity = sample["disparity"].astype(np.float32)
228
- sample["disparity"] = np.ascontiguousarray(disparity)
229
-
230
- if "depth" in sample:
231
- depth = sample["depth"].astype(np.float32)
232
- sample["depth"] = np.ascontiguousarray(depth)
233
-
234
- return sample
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/midas/vit.py DELETED
@@ -1,491 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import timm
4
- import types
5
- import math
6
- import torch.nn.functional as F
7
-
8
-
9
- class Slice(nn.Module):
10
- def __init__(self, start_index=1):
11
- super(Slice, self).__init__()
12
- self.start_index = start_index
13
-
14
- def forward(self, x):
15
- return x[:, self.start_index :]
16
-
17
-
18
- class AddReadout(nn.Module):
19
- def __init__(self, start_index=1):
20
- super(AddReadout, self).__init__()
21
- self.start_index = start_index
22
-
23
- def forward(self, x):
24
- if self.start_index == 2:
25
- readout = (x[:, 0] + x[:, 1]) / 2
26
- else:
27
- readout = x[:, 0]
28
- return x[:, self.start_index :] + readout.unsqueeze(1)
29
-
30
-
31
- class ProjectReadout(nn.Module):
32
- def __init__(self, in_features, start_index=1):
33
- super(ProjectReadout, self).__init__()
34
- self.start_index = start_index
35
-
36
- self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU())
37
-
38
- def forward(self, x):
39
- readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index :])
40
- features = torch.cat((x[:, self.start_index :], readout), -1)
41
-
42
- return self.project(features)
43
-
44
-
45
- class Transpose(nn.Module):
46
- def __init__(self, dim0, dim1):
47
- super(Transpose, self).__init__()
48
- self.dim0 = dim0
49
- self.dim1 = dim1
50
-
51
- def forward(self, x):
52
- x = x.transpose(self.dim0, self.dim1)
53
- return x
54
-
55
-
56
- def forward_vit(pretrained, x):
57
- b, c, h, w = x.shape
58
-
59
- glob = pretrained.model.forward_flex(x)
60
-
61
- layer_1 = pretrained.activations["1"]
62
- layer_2 = pretrained.activations["2"]
63
- layer_3 = pretrained.activations["3"]
64
- layer_4 = pretrained.activations["4"]
65
-
66
- layer_1 = pretrained.act_postprocess1[0:2](layer_1)
67
- layer_2 = pretrained.act_postprocess2[0:2](layer_2)
68
- layer_3 = pretrained.act_postprocess3[0:2](layer_3)
69
- layer_4 = pretrained.act_postprocess4[0:2](layer_4)
70
-
71
- unflatten = nn.Sequential(
72
- nn.Unflatten(
73
- 2,
74
- torch.Size(
75
- [
76
- h // pretrained.model.patch_size[1],
77
- w // pretrained.model.patch_size[0],
78
- ]
79
- ),
80
- )
81
- )
82
-
83
- if layer_1.ndim == 3:
84
- layer_1 = unflatten(layer_1)
85
- if layer_2.ndim == 3:
86
- layer_2 = unflatten(layer_2)
87
- if layer_3.ndim == 3:
88
- layer_3 = unflatten(layer_3)
89
- if layer_4.ndim == 3:
90
- layer_4 = unflatten(layer_4)
91
-
92
- layer_1 = pretrained.act_postprocess1[3 : len(pretrained.act_postprocess1)](layer_1)
93
- layer_2 = pretrained.act_postprocess2[3 : len(pretrained.act_postprocess2)](layer_2)
94
- layer_3 = pretrained.act_postprocess3[3 : len(pretrained.act_postprocess3)](layer_3)
95
- layer_4 = pretrained.act_postprocess4[3 : len(pretrained.act_postprocess4)](layer_4)
96
-
97
- return layer_1, layer_2, layer_3, layer_4
98
-
99
-
100
- def _resize_pos_embed(self, posemb, gs_h, gs_w):
101
- posemb_tok, posemb_grid = (
102
- posemb[:, : self.start_index],
103
- posemb[0, self.start_index :],
104
- )
105
-
106
- gs_old = int(math.sqrt(len(posemb_grid)))
107
-
108
- posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)
109
- posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear")
110
- posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1)
111
-
112
- posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
113
-
114
- return posemb
115
-
116
-
117
- def forward_flex(self, x):
118
- b, c, h, w = x.shape
119
-
120
- pos_embed = self._resize_pos_embed(
121
- self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]
122
- )
123
-
124
- B = x.shape[0]
125
-
126
- if hasattr(self.patch_embed, "backbone"):
127
- x = self.patch_embed.backbone(x)
128
- if isinstance(x, (list, tuple)):
129
- x = x[-1] # last feature if backbone outputs list/tuple of features
130
-
131
- x = self.patch_embed.proj(x).flatten(2).transpose(1, 2)
132
-
133
- if getattr(self, "dist_token", None) is not None:
134
- cls_tokens = self.cls_token.expand(
135
- B, -1, -1
136
- ) # stole cls_tokens impl from Phil Wang, thanks
137
- dist_token = self.dist_token.expand(B, -1, -1)
138
- x = torch.cat((cls_tokens, dist_token, x), dim=1)
139
- else:
140
- cls_tokens = self.cls_token.expand(
141
- B, -1, -1
142
- ) # stole cls_tokens impl from Phil Wang, thanks
143
- x = torch.cat((cls_tokens, x), dim=1)
144
-
145
- x = x + pos_embed
146
- x = self.pos_drop(x)
147
-
148
- for blk in self.blocks:
149
- x = blk(x)
150
-
151
- x = self.norm(x)
152
-
153
- return x
154
-
155
-
156
- activations = {}
157
-
158
-
159
- def get_activation(name):
160
- def hook(model, input, output):
161
- activations[name] = output
162
-
163
- return hook
164
-
165
-
166
- def get_readout_oper(vit_features, features, use_readout, start_index=1):
167
- if use_readout == "ignore":
168
- readout_oper = [Slice(start_index)] * len(features)
169
- elif use_readout == "add":
170
- readout_oper = [AddReadout(start_index)] * len(features)
171
- elif use_readout == "project":
172
- readout_oper = [
173
- ProjectReadout(vit_features, start_index) for out_feat in features
174
- ]
175
- else:
176
- assert (
177
- False
178
- ), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'"
179
-
180
- return readout_oper
181
-
182
-
183
- def _make_vit_b16_backbone(
184
- model,
185
- features=[96, 192, 384, 768],
186
- size=[384, 384],
187
- hooks=[2, 5, 8, 11],
188
- vit_features=768,
189
- use_readout="ignore",
190
- start_index=1,
191
- ):
192
- pretrained = nn.Module()
193
-
194
- pretrained.model = model
195
- pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
196
- pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
197
- pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
198
- pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))
199
-
200
- pretrained.activations = activations
201
-
202
- readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)
203
-
204
- # 32, 48, 136, 384
205
- pretrained.act_postprocess1 = nn.Sequential(
206
- readout_oper[0],
207
- Transpose(1, 2),
208
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
209
- nn.Conv2d(
210
- in_channels=vit_features,
211
- out_channels=features[0],
212
- kernel_size=1,
213
- stride=1,
214
- padding=0,
215
- ),
216
- nn.ConvTranspose2d(
217
- in_channels=features[0],
218
- out_channels=features[0],
219
- kernel_size=4,
220
- stride=4,
221
- padding=0,
222
- bias=True,
223
- dilation=1,
224
- groups=1,
225
- ),
226
- )
227
-
228
- pretrained.act_postprocess2 = nn.Sequential(
229
- readout_oper[1],
230
- Transpose(1, 2),
231
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
232
- nn.Conv2d(
233
- in_channels=vit_features,
234
- out_channels=features[1],
235
- kernel_size=1,
236
- stride=1,
237
- padding=0,
238
- ),
239
- nn.ConvTranspose2d(
240
- in_channels=features[1],
241
- out_channels=features[1],
242
- kernel_size=2,
243
- stride=2,
244
- padding=0,
245
- bias=True,
246
- dilation=1,
247
- groups=1,
248
- ),
249
- )
250
-
251
- pretrained.act_postprocess3 = nn.Sequential(
252
- readout_oper[2],
253
- Transpose(1, 2),
254
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
255
- nn.Conv2d(
256
- in_channels=vit_features,
257
- out_channels=features[2],
258
- kernel_size=1,
259
- stride=1,
260
- padding=0,
261
- ),
262
- )
263
-
264
- pretrained.act_postprocess4 = nn.Sequential(
265
- readout_oper[3],
266
- Transpose(1, 2),
267
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
268
- nn.Conv2d(
269
- in_channels=vit_features,
270
- out_channels=features[3],
271
- kernel_size=1,
272
- stride=1,
273
- padding=0,
274
- ),
275
- nn.Conv2d(
276
- in_channels=features[3],
277
- out_channels=features[3],
278
- kernel_size=3,
279
- stride=2,
280
- padding=1,
281
- ),
282
- )
283
-
284
- pretrained.model.start_index = start_index
285
- pretrained.model.patch_size = [16, 16]
286
-
287
- # We inject this function into the VisionTransformer instances so that
288
- # we can use it with interpolated position embeddings without modifying the library source.
289
- pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
290
- pretrained.model._resize_pos_embed = types.MethodType(
291
- _resize_pos_embed, pretrained.model
292
- )
293
-
294
- return pretrained
295
-
296
-
297
- def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None):
298
- model = timm.create_model("vit_large_patch16_384", pretrained=pretrained)
299
-
300
- hooks = [5, 11, 17, 23] if hooks == None else hooks
301
- return _make_vit_b16_backbone(
302
- model,
303
- features=[256, 512, 1024, 1024],
304
- hooks=hooks,
305
- vit_features=1024,
306
- use_readout=use_readout,
307
- )
308
-
309
-
310
- def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None):
311
- model = timm.create_model("vit_base_patch16_384", pretrained=pretrained)
312
-
313
- hooks = [2, 5, 8, 11] if hooks == None else hooks
314
- return _make_vit_b16_backbone(
315
- model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout
316
- )
317
-
318
-
319
- def _make_pretrained_deitb16_384(pretrained, use_readout="ignore", hooks=None):
320
- model = timm.create_model("vit_deit_base_patch16_384", pretrained=pretrained)
321
-
322
- hooks = [2, 5, 8, 11] if hooks == None else hooks
323
- return _make_vit_b16_backbone(
324
- model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout
325
- )
326
-
327
-
328
- def _make_pretrained_deitb16_distil_384(pretrained, use_readout="ignore", hooks=None):
329
- model = timm.create_model(
330
- "vit_deit_base_distilled_patch16_384", pretrained=pretrained
331
- )
332
-
333
- hooks = [2, 5, 8, 11] if hooks == None else hooks
334
- return _make_vit_b16_backbone(
335
- model,
336
- features=[96, 192, 384, 768],
337
- hooks=hooks,
338
- use_readout=use_readout,
339
- start_index=2,
340
- )
341
-
342
-
343
- def _make_vit_b_rn50_backbone(
344
- model,
345
- features=[256, 512, 768, 768],
346
- size=[384, 384],
347
- hooks=[0, 1, 8, 11],
348
- vit_features=768,
349
- use_vit_only=False,
350
- use_readout="ignore",
351
- start_index=1,
352
- ):
353
- pretrained = nn.Module()
354
-
355
- pretrained.model = model
356
-
357
- if use_vit_only == True:
358
- pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
359
- pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
360
- else:
361
- pretrained.model.patch_embed.backbone.stages[0].register_forward_hook(
362
- get_activation("1")
363
- )
364
- pretrained.model.patch_embed.backbone.stages[1].register_forward_hook(
365
- get_activation("2")
366
- )
367
-
368
- pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
369
- pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))
370
-
371
- pretrained.activations = activations
372
-
373
- readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)
374
-
375
- if use_vit_only == True:
376
- pretrained.act_postprocess1 = nn.Sequential(
377
- readout_oper[0],
378
- Transpose(1, 2),
379
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
380
- nn.Conv2d(
381
- in_channels=vit_features,
382
- out_channels=features[0],
383
- kernel_size=1,
384
- stride=1,
385
- padding=0,
386
- ),
387
- nn.ConvTranspose2d(
388
- in_channels=features[0],
389
- out_channels=features[0],
390
- kernel_size=4,
391
- stride=4,
392
- padding=0,
393
- bias=True,
394
- dilation=1,
395
- groups=1,
396
- ),
397
- )
398
-
399
- pretrained.act_postprocess2 = nn.Sequential(
400
- readout_oper[1],
401
- Transpose(1, 2),
402
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
403
- nn.Conv2d(
404
- in_channels=vit_features,
405
- out_channels=features[1],
406
- kernel_size=1,
407
- stride=1,
408
- padding=0,
409
- ),
410
- nn.ConvTranspose2d(
411
- in_channels=features[1],
412
- out_channels=features[1],
413
- kernel_size=2,
414
- stride=2,
415
- padding=0,
416
- bias=True,
417
- dilation=1,
418
- groups=1,
419
- ),
420
- )
421
- else:
422
- pretrained.act_postprocess1 = nn.Sequential(
423
- nn.Identity(), nn.Identity(), nn.Identity()
424
- )
425
- pretrained.act_postprocess2 = nn.Sequential(
426
- nn.Identity(), nn.Identity(), nn.Identity()
427
- )
428
-
429
- pretrained.act_postprocess3 = nn.Sequential(
430
- readout_oper[2],
431
- Transpose(1, 2),
432
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
433
- nn.Conv2d(
434
- in_channels=vit_features,
435
- out_channels=features[2],
436
- kernel_size=1,
437
- stride=1,
438
- padding=0,
439
- ),
440
- )
441
-
442
- pretrained.act_postprocess4 = nn.Sequential(
443
- readout_oper[3],
444
- Transpose(1, 2),
445
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
446
- nn.Conv2d(
447
- in_channels=vit_features,
448
- out_channels=features[3],
449
- kernel_size=1,
450
- stride=1,
451
- padding=0,
452
- ),
453
- nn.Conv2d(
454
- in_channels=features[3],
455
- out_channels=features[3],
456
- kernel_size=3,
457
- stride=2,
458
- padding=1,
459
- ),
460
- )
461
-
462
- pretrained.model.start_index = start_index
463
- pretrained.model.patch_size = [16, 16]
464
-
465
- # We inject this function into the VisionTransformer instances so that
466
- # we can use it with interpolated position embeddings without modifying the library source.
467
- pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
468
-
469
- # We inject this function into the VisionTransformer instances so that
470
- # we can use it with interpolated position embeddings without modifying the library source.
471
- pretrained.model._resize_pos_embed = types.MethodType(
472
- _resize_pos_embed, pretrained.model
473
- )
474
-
475
- return pretrained
476
-
477
-
478
- def _make_pretrained_vitb_rn50_384(
479
- pretrained, use_readout="ignore", hooks=None, use_vit_only=False
480
- ):
481
- model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained)
482
-
483
- hooks = [0, 1, 8, 11] if hooks == None else hooks
484
- return _make_vit_b_rn50_backbone(
485
- model,
486
- features=[256, 512, 768, 768],
487
- size=[384, 384],
488
- hooks=hooks,
489
- use_vit_only=use_vit_only,
490
- use_readout=use_readout,
491
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/midas/utils.py DELETED
@@ -1,189 +0,0 @@
1
- """Utils for monoDepth."""
2
- import sys
3
- import re
4
- import numpy as np
5
- import cv2
6
- import torch
7
-
8
-
9
- def read_pfm(path):
10
- """Read pfm file.
11
-
12
- Args:
13
- path (str): path to file
14
-
15
- Returns:
16
- tuple: (data, scale)
17
- """
18
- with open(path, "rb") as file:
19
-
20
- color = None
21
- width = None
22
- height = None
23
- scale = None
24
- endian = None
25
-
26
- header = file.readline().rstrip()
27
- if header.decode("ascii") == "PF":
28
- color = True
29
- elif header.decode("ascii") == "Pf":
30
- color = False
31
- else:
32
- raise Exception("Not a PFM file: " + path)
33
-
34
- dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii"))
35
- if dim_match:
36
- width, height = list(map(int, dim_match.groups()))
37
- else:
38
- raise Exception("Malformed PFM header.")
39
-
40
- scale = float(file.readline().decode("ascii").rstrip())
41
- if scale < 0:
42
- # little-endian
43
- endian = "<"
44
- scale = -scale
45
- else:
46
- # big-endian
47
- endian = ">"
48
-
49
- data = np.fromfile(file, endian + "f")
50
- shape = (height, width, 3) if color else (height, width)
51
-
52
- data = np.reshape(data, shape)
53
- data = np.flipud(data)
54
-
55
- return data, scale
56
-
57
-
58
- def write_pfm(path, image, scale=1):
59
- """Write pfm file.
60
-
61
- Args:
62
- path (str): pathto file
63
- image (array): data
64
- scale (int, optional): Scale. Defaults to 1.
65
- """
66
-
67
- with open(path, "wb") as file:
68
- color = None
69
-
70
- if image.dtype.name != "float32":
71
- raise Exception("Image dtype must be float32.")
72
-
73
- image = np.flipud(image)
74
-
75
- if len(image.shape) == 3 and image.shape[2] == 3: # color image
76
- color = True
77
- elif (
78
- len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1
79
- ): # greyscale
80
- color = False
81
- else:
82
- raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.")
83
-
84
- file.write("PF\n" if color else "Pf\n".encode())
85
- file.write("%d %d\n".encode() % (image.shape[1], image.shape[0]))
86
-
87
- endian = image.dtype.byteorder
88
-
89
- if endian == "<" or endian == "=" and sys.byteorder == "little":
90
- scale = -scale
91
-
92
- file.write("%f\n".encode() % scale)
93
-
94
- image.tofile(file)
95
-
96
-
97
- def read_image(path):
98
- """Read image and output RGB image (0-1).
99
-
100
- Args:
101
- path (str): path to file
102
-
103
- Returns:
104
- array: RGB image (0-1)
105
- """
106
- img = cv2.imread(path)
107
-
108
- if img.ndim == 2:
109
- img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
110
-
111
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0
112
-
113
- return img
114
-
115
-
116
- def resize_image(img):
117
- """Resize image and make it fit for network.
118
-
119
- Args:
120
- img (array): image
121
-
122
- Returns:
123
- tensor: data ready for network
124
- """
125
- height_orig = img.shape[0]
126
- width_orig = img.shape[1]
127
-
128
- if width_orig > height_orig:
129
- scale = width_orig / 384
130
- else:
131
- scale = height_orig / 384
132
-
133
- height = (np.ceil(height_orig / scale / 32) * 32).astype(int)
134
- width = (np.ceil(width_orig / scale / 32) * 32).astype(int)
135
-
136
- img_resized = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)
137
-
138
- img_resized = (
139
- torch.from_numpy(np.transpose(img_resized, (2, 0, 1))).contiguous().float()
140
- )
141
- img_resized = img_resized.unsqueeze(0)
142
-
143
- return img_resized
144
-
145
-
146
- def resize_depth(depth, width, height):
147
- """Resize depth map and bring to CPU (numpy).
148
-
149
- Args:
150
- depth (tensor): depth
151
- width (int): image width
152
- height (int): image height
153
-
154
- Returns:
155
- array: processed depth
156
- """
157
- depth = torch.squeeze(depth[0, :, :, :]).to("cpu")
158
-
159
- depth_resized = cv2.resize(
160
- depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC
161
- )
162
-
163
- return depth_resized
164
-
165
- def write_depth(path, depth, bits=1):
166
- """Write depth map to pfm and png file.
167
-
168
- Args:
169
- path (str): filepath without extension
170
- depth (array): depth
171
- """
172
- write_pfm(path + ".pfm", depth.astype(np.float32))
173
-
174
- depth_min = depth.min()
175
- depth_max = depth.max()
176
-
177
- max_val = (2**(8*bits))-1
178
-
179
- if depth_max - depth_min > np.finfo("float").eps:
180
- out = max_val * (depth - depth_min) / (depth_max - depth_min)
181
- else:
182
- out = np.zeros(depth.shape, dtype=depth.type)
183
-
184
- if bits == 1:
185
- cv2.imwrite(path + ".png", out.astype("uint8"))
186
- elif bits == 2:
187
- cv2.imwrite(path + ".png", out.astype("uint16"))
188
-
189
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/mlsd/__init__.py DELETED
@@ -1,79 +0,0 @@
1
- import os
2
- import warnings
3
-
4
- import cv2
5
- import numpy as np
6
- import torch
7
- from huggingface_hub import hf_hub_download
8
- from PIL import Image
9
-
10
- from ..util import HWC3, resize_image
11
- from .models.mbv2_mlsd_large import MobileV2_MLSD_Large
12
- from .utils import pred_lines
13
-
14
-
15
- class MLSDdetector:
16
- def __init__(self, model):
17
- self.model = model
18
-
19
- @classmethod
20
- def from_pretrained(cls, pretrained_model_or_path, filename=None, cache_dir=None, local_files_only=False):
21
- if pretrained_model_or_path == "lllyasviel/ControlNet":
22
- filename = filename or "annotator/ckpts/mlsd_large_512_fp32.pth"
23
- else:
24
- filename = filename or "mlsd_large_512_fp32.pth"
25
-
26
- if os.path.isdir(pretrained_model_or_path):
27
- model_path = os.path.join(pretrained_model_or_path, filename)
28
- else:
29
- model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
30
-
31
- model = MobileV2_MLSD_Large()
32
- model.load_state_dict(torch.load(model_path), strict=True)
33
- model.eval()
34
-
35
- return cls(model)
36
-
37
- def to(self, device):
38
- self.model.to(device)
39
- return self
40
-
41
- def __call__(self, input_image, thr_v=0.1, thr_d=0.1, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
42
- if "return_pil" in kwargs:
43
- warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
44
- output_type = "pil" if kwargs["return_pil"] else "np"
45
- if type(output_type) is bool:
46
- warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
47
- if output_type:
48
- output_type = "pil"
49
-
50
- if not isinstance(input_image, np.ndarray):
51
- input_image = np.array(input_image, dtype=np.uint8)
52
-
53
- input_image = HWC3(input_image)
54
- input_image = resize_image(input_image, detect_resolution)
55
-
56
- assert input_image.ndim == 3
57
- img = input_image
58
- img_output = np.zeros_like(img)
59
- try:
60
- with torch.no_grad():
61
- lines = pred_lines(img, self.model, [img.shape[0], img.shape[1]], thr_v, thr_d)
62
- for line in lines:
63
- x_start, y_start, x_end, y_end = [int(val) for val in line]
64
- cv2.line(img_output, (x_start, y_start), (x_end, y_end), [255, 255, 255], 1)
65
- except Exception as e:
66
- pass
67
-
68
- detected_map = img_output[:, :, 0]
69
- detected_map = HWC3(detected_map)
70
-
71
- img = resize_image(input_image, image_resolution)
72
- H, W, C = img.shape
73
-
74
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
75
-
76
- if output_type == "pil":
77
- detected_map = Image.fromarray(detected_map)
78
-
79
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/mlsd/models/__init__.py DELETED
File without changes
controlnet_aux_local/mlsd/models/mbv2_mlsd_large.py DELETED
@@ -1,292 +0,0 @@
1
- import os
2
- import sys
3
- import torch
4
- import torch.nn as nn
5
- import torch.utils.model_zoo as model_zoo
6
- from torch.nn import functional as F
7
-
8
-
9
- class BlockTypeA(nn.Module):
10
- def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True):
11
- super(BlockTypeA, self).__init__()
12
- self.conv1 = nn.Sequential(
13
- nn.Conv2d(in_c2, out_c2, kernel_size=1),
14
- nn.BatchNorm2d(out_c2),
15
- nn.ReLU(inplace=True)
16
- )
17
- self.conv2 = nn.Sequential(
18
- nn.Conv2d(in_c1, out_c1, kernel_size=1),
19
- nn.BatchNorm2d(out_c1),
20
- nn.ReLU(inplace=True)
21
- )
22
- self.upscale = upscale
23
-
24
- def forward(self, a, b):
25
- b = self.conv1(b)
26
- a = self.conv2(a)
27
- if self.upscale:
28
- b = F.interpolate(b, scale_factor=2.0, mode='bilinear', align_corners=True)
29
- return torch.cat((a, b), dim=1)
30
-
31
-
32
- class BlockTypeB(nn.Module):
33
- def __init__(self, in_c, out_c):
34
- super(BlockTypeB, self).__init__()
35
- self.conv1 = nn.Sequential(
36
- nn.Conv2d(in_c, in_c, kernel_size=3, padding=1),
37
- nn.BatchNorm2d(in_c),
38
- nn.ReLU()
39
- )
40
- self.conv2 = nn.Sequential(
41
- nn.Conv2d(in_c, out_c, kernel_size=3, padding=1),
42
- nn.BatchNorm2d(out_c),
43
- nn.ReLU()
44
- )
45
-
46
- def forward(self, x):
47
- x = self.conv1(x) + x
48
- x = self.conv2(x)
49
- return x
50
-
51
- class BlockTypeC(nn.Module):
52
- def __init__(self, in_c, out_c):
53
- super(BlockTypeC, self).__init__()
54
- self.conv1 = nn.Sequential(
55
- nn.Conv2d(in_c, in_c, kernel_size=3, padding=5, dilation=5),
56
- nn.BatchNorm2d(in_c),
57
- nn.ReLU()
58
- )
59
- self.conv2 = nn.Sequential(
60
- nn.Conv2d(in_c, in_c, kernel_size=3, padding=1),
61
- nn.BatchNorm2d(in_c),
62
- nn.ReLU()
63
- )
64
- self.conv3 = nn.Conv2d(in_c, out_c, kernel_size=1)
65
-
66
- def forward(self, x):
67
- x = self.conv1(x)
68
- x = self.conv2(x)
69
- x = self.conv3(x)
70
- return x
71
-
72
- def _make_divisible(v, divisor, min_value=None):
73
- """
74
- This function is taken from the original tf repo.
75
- It ensures that all layers have a channel number that is divisible by 8
76
- It can be seen here:
77
- https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
78
- :param v:
79
- :param divisor:
80
- :param min_value:
81
- :return:
82
- """
83
- if min_value is None:
84
- min_value = divisor
85
- new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
86
- # Make sure that round down does not go down by more than 10%.
87
- if new_v < 0.9 * v:
88
- new_v += divisor
89
- return new_v
90
-
91
-
92
- class ConvBNReLU(nn.Sequential):
93
- def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
94
- self.channel_pad = out_planes - in_planes
95
- self.stride = stride
96
- #padding = (kernel_size - 1) // 2
97
-
98
- # TFLite uses slightly different padding than PyTorch
99
- if stride == 2:
100
- padding = 0
101
- else:
102
- padding = (kernel_size - 1) // 2
103
-
104
- super(ConvBNReLU, self).__init__(
105
- nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),
106
- nn.BatchNorm2d(out_planes),
107
- nn.ReLU6(inplace=True)
108
- )
109
- self.max_pool = nn.MaxPool2d(kernel_size=stride, stride=stride)
110
-
111
-
112
- def forward(self, x):
113
- # TFLite uses different padding
114
- if self.stride == 2:
115
- x = F.pad(x, (0, 1, 0, 1), "constant", 0)
116
- #print(x.shape)
117
-
118
- for module in self:
119
- if not isinstance(module, nn.MaxPool2d):
120
- x = module(x)
121
- return x
122
-
123
-
124
- class InvertedResidual(nn.Module):
125
- def __init__(self, inp, oup, stride, expand_ratio):
126
- super(InvertedResidual, self).__init__()
127
- self.stride = stride
128
- assert stride in [1, 2]
129
-
130
- hidden_dim = int(round(inp * expand_ratio))
131
- self.use_res_connect = self.stride == 1 and inp == oup
132
-
133
- layers = []
134
- if expand_ratio != 1:
135
- # pw
136
- layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))
137
- layers.extend([
138
- # dw
139
- ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim),
140
- # pw-linear
141
- nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
142
- nn.BatchNorm2d(oup),
143
- ])
144
- self.conv = nn.Sequential(*layers)
145
-
146
- def forward(self, x):
147
- if self.use_res_connect:
148
- return x + self.conv(x)
149
- else:
150
- return self.conv(x)
151
-
152
-
153
- class MobileNetV2(nn.Module):
154
- def __init__(self, pretrained=True):
155
- """
156
- MobileNet V2 main class
157
- Args:
158
- num_classes (int): Number of classes
159
- width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
160
- inverted_residual_setting: Network structure
161
- round_nearest (int): Round the number of channels in each layer to be a multiple of this number
162
- Set to 1 to turn off rounding
163
- block: Module specifying inverted residual building block for mobilenet
164
- """
165
- super(MobileNetV2, self).__init__()
166
-
167
- block = InvertedResidual
168
- input_channel = 32
169
- last_channel = 1280
170
- width_mult = 1.0
171
- round_nearest = 8
172
-
173
- inverted_residual_setting = [
174
- # t, c, n, s
175
- [1, 16, 1, 1],
176
- [6, 24, 2, 2],
177
- [6, 32, 3, 2],
178
- [6, 64, 4, 2],
179
- [6, 96, 3, 1],
180
- #[6, 160, 3, 2],
181
- #[6, 320, 1, 1],
182
- ]
183
-
184
- # only check the first element, assuming user knows t,c,n,s are required
185
- if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:
186
- raise ValueError("inverted_residual_setting should be non-empty "
187
- "or a 4-element list, got {}".format(inverted_residual_setting))
188
-
189
- # building first layer
190
- input_channel = _make_divisible(input_channel * width_mult, round_nearest)
191
- self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest)
192
- features = [ConvBNReLU(4, input_channel, stride=2)]
193
- # building inverted residual blocks
194
- for t, c, n, s in inverted_residual_setting:
195
- output_channel = _make_divisible(c * width_mult, round_nearest)
196
- for i in range(n):
197
- stride = s if i == 0 else 1
198
- features.append(block(input_channel, output_channel, stride, expand_ratio=t))
199
- input_channel = output_channel
200
-
201
- self.features = nn.Sequential(*features)
202
- self.fpn_selected = [1, 3, 6, 10, 13]
203
- # weight initialization
204
- for m in self.modules():
205
- if isinstance(m, nn.Conv2d):
206
- nn.init.kaiming_normal_(m.weight, mode='fan_out')
207
- if m.bias is not None:
208
- nn.init.zeros_(m.bias)
209
- elif isinstance(m, nn.BatchNorm2d):
210
- nn.init.ones_(m.weight)
211
- nn.init.zeros_(m.bias)
212
- elif isinstance(m, nn.Linear):
213
- nn.init.normal_(m.weight, 0, 0.01)
214
- nn.init.zeros_(m.bias)
215
- if pretrained:
216
- self._load_pretrained_model()
217
-
218
- def _forward_impl(self, x):
219
- # This exists since TorchScript doesn't support inheritance, so the superclass method
220
- # (this one) needs to have a name other than `forward` that can be accessed in a subclass
221
- fpn_features = []
222
- for i, f in enumerate(self.features):
223
- if i > self.fpn_selected[-1]:
224
- break
225
- x = f(x)
226
- if i in self.fpn_selected:
227
- fpn_features.append(x)
228
-
229
- c1, c2, c3, c4, c5 = fpn_features
230
- return c1, c2, c3, c4, c5
231
-
232
-
233
- def forward(self, x):
234
- return self._forward_impl(x)
235
-
236
- def _load_pretrained_model(self):
237
- pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/mobilenet_v2-b0353104.pth')
238
- model_dict = {}
239
- state_dict = self.state_dict()
240
- for k, v in pretrain_dict.items():
241
- if k in state_dict:
242
- model_dict[k] = v
243
- state_dict.update(model_dict)
244
- self.load_state_dict(state_dict)
245
-
246
-
247
- class MobileV2_MLSD_Large(nn.Module):
248
- def __init__(self):
249
- super(MobileV2_MLSD_Large, self).__init__()
250
-
251
- self.backbone = MobileNetV2(pretrained=False)
252
- ## A, B
253
- self.block15 = BlockTypeA(in_c1= 64, in_c2= 96,
254
- out_c1= 64, out_c2=64,
255
- upscale=False)
256
- self.block16 = BlockTypeB(128, 64)
257
-
258
- ## A, B
259
- self.block17 = BlockTypeA(in_c1 = 32, in_c2 = 64,
260
- out_c1= 64, out_c2= 64)
261
- self.block18 = BlockTypeB(128, 64)
262
-
263
- ## A, B
264
- self.block19 = BlockTypeA(in_c1=24, in_c2=64,
265
- out_c1=64, out_c2=64)
266
- self.block20 = BlockTypeB(128, 64)
267
-
268
- ## A, B, C
269
- self.block21 = BlockTypeA(in_c1=16, in_c2=64,
270
- out_c1=64, out_c2=64)
271
- self.block22 = BlockTypeB(128, 64)
272
-
273
- self.block23 = BlockTypeC(64, 16)
274
-
275
- def forward(self, x):
276
- c1, c2, c3, c4, c5 = self.backbone(x)
277
-
278
- x = self.block15(c4, c5)
279
- x = self.block16(x)
280
-
281
- x = self.block17(c3, x)
282
- x = self.block18(x)
283
-
284
- x = self.block19(c2, x)
285
- x = self.block20(x)
286
-
287
- x = self.block21(c1, x)
288
- x = self.block22(x)
289
- x = self.block23(x)
290
- x = x[:, 7:, :, :]
291
-
292
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/mlsd/models/mbv2_mlsd_tiny.py DELETED
@@ -1,275 +0,0 @@
1
- import os
2
- import sys
3
- import torch
4
- import torch.nn as nn
5
- import torch.utils.model_zoo as model_zoo
6
- from torch.nn import functional as F
7
-
8
-
9
- class BlockTypeA(nn.Module):
10
- def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True):
11
- super(BlockTypeA, self).__init__()
12
- self.conv1 = nn.Sequential(
13
- nn.Conv2d(in_c2, out_c2, kernel_size=1),
14
- nn.BatchNorm2d(out_c2),
15
- nn.ReLU(inplace=True)
16
- )
17
- self.conv2 = nn.Sequential(
18
- nn.Conv2d(in_c1, out_c1, kernel_size=1),
19
- nn.BatchNorm2d(out_c1),
20
- nn.ReLU(inplace=True)
21
- )
22
- self.upscale = upscale
23
-
24
- def forward(self, a, b):
25
- b = self.conv1(b)
26
- a = self.conv2(a)
27
- b = F.interpolate(b, scale_factor=2.0, mode='bilinear', align_corners=True)
28
- return torch.cat((a, b), dim=1)
29
-
30
-
31
- class BlockTypeB(nn.Module):
32
- def __init__(self, in_c, out_c):
33
- super(BlockTypeB, self).__init__()
34
- self.conv1 = nn.Sequential(
35
- nn.Conv2d(in_c, in_c, kernel_size=3, padding=1),
36
- nn.BatchNorm2d(in_c),
37
- nn.ReLU()
38
- )
39
- self.conv2 = nn.Sequential(
40
- nn.Conv2d(in_c, out_c, kernel_size=3, padding=1),
41
- nn.BatchNorm2d(out_c),
42
- nn.ReLU()
43
- )
44
-
45
- def forward(self, x):
46
- x = self.conv1(x) + x
47
- x = self.conv2(x)
48
- return x
49
-
50
- class BlockTypeC(nn.Module):
51
- def __init__(self, in_c, out_c):
52
- super(BlockTypeC, self).__init__()
53
- self.conv1 = nn.Sequential(
54
- nn.Conv2d(in_c, in_c, kernel_size=3, padding=5, dilation=5),
55
- nn.BatchNorm2d(in_c),
56
- nn.ReLU()
57
- )
58
- self.conv2 = nn.Sequential(
59
- nn.Conv2d(in_c, in_c, kernel_size=3, padding=1),
60
- nn.BatchNorm2d(in_c),
61
- nn.ReLU()
62
- )
63
- self.conv3 = nn.Conv2d(in_c, out_c, kernel_size=1)
64
-
65
- def forward(self, x):
66
- x = self.conv1(x)
67
- x = self.conv2(x)
68
- x = self.conv3(x)
69
- return x
70
-
71
- def _make_divisible(v, divisor, min_value=None):
72
- """
73
- This function is taken from the original tf repo.
74
- It ensures that all layers have a channel number that is divisible by 8
75
- It can be seen here:
76
- https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
77
- :param v:
78
- :param divisor:
79
- :param min_value:
80
- :return:
81
- """
82
- if min_value is None:
83
- min_value = divisor
84
- new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
85
- # Make sure that round down does not go down by more than 10%.
86
- if new_v < 0.9 * v:
87
- new_v += divisor
88
- return new_v
89
-
90
-
91
- class ConvBNReLU(nn.Sequential):
92
- def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
93
- self.channel_pad = out_planes - in_planes
94
- self.stride = stride
95
- #padding = (kernel_size - 1) // 2
96
-
97
- # TFLite uses slightly different padding than PyTorch
98
- if stride == 2:
99
- padding = 0
100
- else:
101
- padding = (kernel_size - 1) // 2
102
-
103
- super(ConvBNReLU, self).__init__(
104
- nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),
105
- nn.BatchNorm2d(out_planes),
106
- nn.ReLU6(inplace=True)
107
- )
108
- self.max_pool = nn.MaxPool2d(kernel_size=stride, stride=stride)
109
-
110
-
111
- def forward(self, x):
112
- # TFLite uses different padding
113
- if self.stride == 2:
114
- x = F.pad(x, (0, 1, 0, 1), "constant", 0)
115
- #print(x.shape)
116
-
117
- for module in self:
118
- if not isinstance(module, nn.MaxPool2d):
119
- x = module(x)
120
- return x
121
-
122
-
123
- class InvertedResidual(nn.Module):
124
- def __init__(self, inp, oup, stride, expand_ratio):
125
- super(InvertedResidual, self).__init__()
126
- self.stride = stride
127
- assert stride in [1, 2]
128
-
129
- hidden_dim = int(round(inp * expand_ratio))
130
- self.use_res_connect = self.stride == 1 and inp == oup
131
-
132
- layers = []
133
- if expand_ratio != 1:
134
- # pw
135
- layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))
136
- layers.extend([
137
- # dw
138
- ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim),
139
- # pw-linear
140
- nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
141
- nn.BatchNorm2d(oup),
142
- ])
143
- self.conv = nn.Sequential(*layers)
144
-
145
- def forward(self, x):
146
- if self.use_res_connect:
147
- return x + self.conv(x)
148
- else:
149
- return self.conv(x)
150
-
151
-
152
- class MobileNetV2(nn.Module):
153
- def __init__(self, pretrained=True):
154
- """
155
- MobileNet V2 main class
156
- Args:
157
- num_classes (int): Number of classes
158
- width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
159
- inverted_residual_setting: Network structure
160
- round_nearest (int): Round the number of channels in each layer to be a multiple of this number
161
- Set to 1 to turn off rounding
162
- block: Module specifying inverted residual building block for mobilenet
163
- """
164
- super(MobileNetV2, self).__init__()
165
-
166
- block = InvertedResidual
167
- input_channel = 32
168
- last_channel = 1280
169
- width_mult = 1.0
170
- round_nearest = 8
171
-
172
- inverted_residual_setting = [
173
- # t, c, n, s
174
- [1, 16, 1, 1],
175
- [6, 24, 2, 2],
176
- [6, 32, 3, 2],
177
- [6, 64, 4, 2],
178
- #[6, 96, 3, 1],
179
- #[6, 160, 3, 2],
180
- #[6, 320, 1, 1],
181
- ]
182
-
183
- # only check the first element, assuming user knows t,c,n,s are required
184
- if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:
185
- raise ValueError("inverted_residual_setting should be non-empty "
186
- "or a 4-element list, got {}".format(inverted_residual_setting))
187
-
188
- # building first layer
189
- input_channel = _make_divisible(input_channel * width_mult, round_nearest)
190
- self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest)
191
- features = [ConvBNReLU(4, input_channel, stride=2)]
192
- # building inverted residual blocks
193
- for t, c, n, s in inverted_residual_setting:
194
- output_channel = _make_divisible(c * width_mult, round_nearest)
195
- for i in range(n):
196
- stride = s if i == 0 else 1
197
- features.append(block(input_channel, output_channel, stride, expand_ratio=t))
198
- input_channel = output_channel
199
- self.features = nn.Sequential(*features)
200
-
201
- self.fpn_selected = [3, 6, 10]
202
- # weight initialization
203
- for m in self.modules():
204
- if isinstance(m, nn.Conv2d):
205
- nn.init.kaiming_normal_(m.weight, mode='fan_out')
206
- if m.bias is not None:
207
- nn.init.zeros_(m.bias)
208
- elif isinstance(m, nn.BatchNorm2d):
209
- nn.init.ones_(m.weight)
210
- nn.init.zeros_(m.bias)
211
- elif isinstance(m, nn.Linear):
212
- nn.init.normal_(m.weight, 0, 0.01)
213
- nn.init.zeros_(m.bias)
214
-
215
- #if pretrained:
216
- # self._load_pretrained_model()
217
-
218
- def _forward_impl(self, x):
219
- # This exists since TorchScript doesn't support inheritance, so the superclass method
220
- # (this one) needs to have a name other than `forward` that can be accessed in a subclass
221
- fpn_features = []
222
- for i, f in enumerate(self.features):
223
- if i > self.fpn_selected[-1]:
224
- break
225
- x = f(x)
226
- if i in self.fpn_selected:
227
- fpn_features.append(x)
228
-
229
- c2, c3, c4 = fpn_features
230
- return c2, c3, c4
231
-
232
-
233
- def forward(self, x):
234
- return self._forward_impl(x)
235
-
236
- def _load_pretrained_model(self):
237
- pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/mobilenet_v2-b0353104.pth')
238
- model_dict = {}
239
- state_dict = self.state_dict()
240
- for k, v in pretrain_dict.items():
241
- if k in state_dict:
242
- model_dict[k] = v
243
- state_dict.update(model_dict)
244
- self.load_state_dict(state_dict)
245
-
246
-
247
- class MobileV2_MLSD_Tiny(nn.Module):
248
- def __init__(self):
249
- super(MobileV2_MLSD_Tiny, self).__init__()
250
-
251
- self.backbone = MobileNetV2(pretrained=True)
252
-
253
- self.block12 = BlockTypeA(in_c1= 32, in_c2= 64,
254
- out_c1= 64, out_c2=64)
255
- self.block13 = BlockTypeB(128, 64)
256
-
257
- self.block14 = BlockTypeA(in_c1 = 24, in_c2 = 64,
258
- out_c1= 32, out_c2= 32)
259
- self.block15 = BlockTypeB(64, 64)
260
-
261
- self.block16 = BlockTypeC(64, 16)
262
-
263
- def forward(self, x):
264
- c2, c3, c4 = self.backbone(x)
265
-
266
- x = self.block12(c3, c4)
267
- x = self.block13(x)
268
- x = self.block14(c2, x)
269
- x = self.block15(x)
270
- x = self.block16(x)
271
- x = x[:, 7:, :, :]
272
- #print(x.shape)
273
- x = F.interpolate(x, scale_factor=2.0, mode='bilinear', align_corners=True)
274
-
275
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/mlsd/utils.py DELETED
@@ -1,584 +0,0 @@
1
- '''
2
- modified by lihaoweicv
3
- pytorch version
4
- '''
5
-
6
- '''
7
- M-LSD
8
- Copyright 2021-present NAVER Corp.
9
- Apache License v2.0
10
- '''
11
-
12
- import os
13
- import numpy as np
14
- import cv2
15
- import torch
16
- from torch.nn import functional as F
17
-
18
-
19
- def deccode_output_score_and_ptss(tpMap, topk_n = 200, ksize = 5):
20
- '''
21
- tpMap:
22
- center: tpMap[1, 0, :, :]
23
- displacement: tpMap[1, 1:5, :, :]
24
- '''
25
- b, c, h, w = tpMap.shape
26
- assert b==1, 'only support bsize==1'
27
- displacement = tpMap[:, 1:5, :, :][0]
28
- center = tpMap[:, 0, :, :]
29
- heat = torch.sigmoid(center)
30
- hmax = F.max_pool2d( heat, (ksize, ksize), stride=1, padding=(ksize-1)//2)
31
- keep = (hmax == heat).float()
32
- heat = heat * keep
33
- heat = heat.reshape(-1, )
34
-
35
- scores, indices = torch.topk(heat, topk_n, dim=-1, largest=True)
36
- yy = torch.floor_divide(indices, w).unsqueeze(-1)
37
- xx = torch.fmod(indices, w).unsqueeze(-1)
38
- ptss = torch.cat((yy, xx),dim=-1)
39
-
40
- ptss = ptss.detach().cpu().numpy()
41
- scores = scores.detach().cpu().numpy()
42
- displacement = displacement.detach().cpu().numpy()
43
- displacement = displacement.transpose((1,2,0))
44
- return ptss, scores, displacement
45
-
46
-
47
- def pred_lines(image, model,
48
- input_shape=[512, 512],
49
- score_thr=0.10,
50
- dist_thr=20.0):
51
- h, w, _ = image.shape
52
-
53
- device = next(iter(model.parameters())).device
54
- h_ratio, w_ratio = [h / input_shape[0], w / input_shape[1]]
55
-
56
- resized_image = np.concatenate([cv2.resize(image, (input_shape[1], input_shape[0]), interpolation=cv2.INTER_AREA),
57
- np.ones([input_shape[0], input_shape[1], 1])], axis=-1)
58
-
59
- resized_image = resized_image.transpose((2,0,1))
60
- batch_image = np.expand_dims(resized_image, axis=0).astype('float32')
61
- batch_image = (batch_image / 127.5) - 1.0
62
-
63
- batch_image = torch.from_numpy(batch_image).float()
64
- batch_image = batch_image.to(device)
65
- outputs = model(batch_image)
66
- pts, pts_score, vmap = deccode_output_score_and_ptss(outputs, 200, 3)
67
- start = vmap[:, :, :2]
68
- end = vmap[:, :, 2:]
69
- dist_map = np.sqrt(np.sum((start - end) ** 2, axis=-1))
70
-
71
- segments_list = []
72
- for center, score in zip(pts, pts_score):
73
- y, x = center
74
- distance = dist_map[y, x]
75
- if score > score_thr and distance > dist_thr:
76
- disp_x_start, disp_y_start, disp_x_end, disp_y_end = vmap[y, x, :]
77
- x_start = x + disp_x_start
78
- y_start = y + disp_y_start
79
- x_end = x + disp_x_end
80
- y_end = y + disp_y_end
81
- segments_list.append([x_start, y_start, x_end, y_end])
82
-
83
- lines = 2 * np.array(segments_list) # 256 > 512
84
- lines[:, 0] = lines[:, 0] * w_ratio
85
- lines[:, 1] = lines[:, 1] * h_ratio
86
- lines[:, 2] = lines[:, 2] * w_ratio
87
- lines[:, 3] = lines[:, 3] * h_ratio
88
-
89
- return lines
90
-
91
-
92
- def pred_squares(image,
93
- model,
94
- input_shape=[512, 512],
95
- params={'score': 0.06,
96
- 'outside_ratio': 0.28,
97
- 'inside_ratio': 0.45,
98
- 'w_overlap': 0.0,
99
- 'w_degree': 1.95,
100
- 'w_length': 0.0,
101
- 'w_area': 1.86,
102
- 'w_center': 0.14}):
103
- '''
104
- shape = [height, width]
105
- '''
106
- h, w, _ = image.shape
107
- original_shape = [h, w]
108
- device = next(iter(model.parameters())).device
109
-
110
- resized_image = np.concatenate([cv2.resize(image, (input_shape[0], input_shape[1]), interpolation=cv2.INTER_AREA),
111
- np.ones([input_shape[0], input_shape[1], 1])], axis=-1)
112
- resized_image = resized_image.transpose((2, 0, 1))
113
- batch_image = np.expand_dims(resized_image, axis=0).astype('float32')
114
- batch_image = (batch_image / 127.5) - 1.0
115
-
116
- batch_image = torch.from_numpy(batch_image).float().to(device)
117
- outputs = model(batch_image)
118
-
119
- pts, pts_score, vmap = deccode_output_score_and_ptss(outputs, 200, 3)
120
- start = vmap[:, :, :2] # (x, y)
121
- end = vmap[:, :, 2:] # (x, y)
122
- dist_map = np.sqrt(np.sum((start - end) ** 2, axis=-1))
123
-
124
- junc_list = []
125
- segments_list = []
126
- for junc, score in zip(pts, pts_score):
127
- y, x = junc
128
- distance = dist_map[y, x]
129
- if score > params['score'] and distance > 20.0:
130
- junc_list.append([x, y])
131
- disp_x_start, disp_y_start, disp_x_end, disp_y_end = vmap[y, x, :]
132
- d_arrow = 1.0
133
- x_start = x + d_arrow * disp_x_start
134
- y_start = y + d_arrow * disp_y_start
135
- x_end = x + d_arrow * disp_x_end
136
- y_end = y + d_arrow * disp_y_end
137
- segments_list.append([x_start, y_start, x_end, y_end])
138
-
139
- segments = np.array(segments_list)
140
-
141
- ####### post processing for squares
142
- # 1. get unique lines
143
- point = np.array([[0, 0]])
144
- point = point[0]
145
- start = segments[:, :2]
146
- end = segments[:, 2:]
147
- diff = start - end
148
- a = diff[:, 1]
149
- b = -diff[:, 0]
150
- c = a * start[:, 0] + b * start[:, 1]
151
-
152
- d = np.abs(a * point[0] + b * point[1] - c) / np.sqrt(a ** 2 + b ** 2 + 1e-10)
153
- theta = np.arctan2(diff[:, 0], diff[:, 1]) * 180 / np.pi
154
- theta[theta < 0.0] += 180
155
- hough = np.concatenate([d[:, None], theta[:, None]], axis=-1)
156
-
157
- d_quant = 1
158
- theta_quant = 2
159
- hough[:, 0] //= d_quant
160
- hough[:, 1] //= theta_quant
161
- _, indices, counts = np.unique(hough, axis=0, return_index=True, return_counts=True)
162
-
163
- acc_map = np.zeros([512 // d_quant + 1, 360 // theta_quant + 1], dtype='float32')
164
- idx_map = np.zeros([512 // d_quant + 1, 360 // theta_quant + 1], dtype='int32') - 1
165
- yx_indices = hough[indices, :].astype('int32')
166
- acc_map[yx_indices[:, 0], yx_indices[:, 1]] = counts
167
- idx_map[yx_indices[:, 0], yx_indices[:, 1]] = indices
168
-
169
- acc_map_np = acc_map
170
- # acc_map = acc_map[None, :, :, None]
171
- #
172
- # ### fast suppression using tensorflow op
173
- # acc_map = tf.constant(acc_map, dtype=tf.float32)
174
- # max_acc_map = tf.keras.layers.MaxPool2D(pool_size=(5, 5), strides=1, padding='same')(acc_map)
175
- # acc_map = acc_map * tf.cast(tf.math.equal(acc_map, max_acc_map), tf.float32)
176
- # flatten_acc_map = tf.reshape(acc_map, [1, -1])
177
- # topk_values, topk_indices = tf.math.top_k(flatten_acc_map, k=len(pts))
178
- # _, h, w, _ = acc_map.shape
179
- # y = tf.expand_dims(topk_indices // w, axis=-1)
180
- # x = tf.expand_dims(topk_indices % w, axis=-1)
181
- # yx = tf.concat([y, x], axis=-1)
182
-
183
- ### fast suppression using pytorch op
184
- acc_map = torch.from_numpy(acc_map_np).unsqueeze(0).unsqueeze(0)
185
- _,_, h, w = acc_map.shape
186
- max_acc_map = F.max_pool2d(acc_map,kernel_size=5, stride=1, padding=2)
187
- acc_map = acc_map * ( (acc_map == max_acc_map).float() )
188
- flatten_acc_map = acc_map.reshape([-1, ])
189
-
190
- scores, indices = torch.topk(flatten_acc_map, len(pts), dim=-1, largest=True)
191
- yy = torch.div(indices, w, rounding_mode='floor').unsqueeze(-1)
192
- xx = torch.fmod(indices, w).unsqueeze(-1)
193
- yx = torch.cat((yy, xx), dim=-1)
194
-
195
- yx = yx.detach().cpu().numpy()
196
-
197
- topk_values = scores.detach().cpu().numpy()
198
- indices = idx_map[yx[:, 0], yx[:, 1]]
199
- basis = 5 // 2
200
-
201
- merged_segments = []
202
- for yx_pt, max_indice, value in zip(yx, indices, topk_values):
203
- y, x = yx_pt
204
- if max_indice == -1 or value == 0:
205
- continue
206
- segment_list = []
207
- for y_offset in range(-basis, basis + 1):
208
- for x_offset in range(-basis, basis + 1):
209
- indice = idx_map[y + y_offset, x + x_offset]
210
- cnt = int(acc_map_np[y + y_offset, x + x_offset])
211
- if indice != -1:
212
- segment_list.append(segments[indice])
213
- if cnt > 1:
214
- check_cnt = 1
215
- current_hough = hough[indice]
216
- for new_indice, new_hough in enumerate(hough):
217
- if (current_hough == new_hough).all() and indice != new_indice:
218
- segment_list.append(segments[new_indice])
219
- check_cnt += 1
220
- if check_cnt == cnt:
221
- break
222
- group_segments = np.array(segment_list).reshape([-1, 2])
223
- sorted_group_segments = np.sort(group_segments, axis=0)
224
- x_min, y_min = sorted_group_segments[0, :]
225
- x_max, y_max = sorted_group_segments[-1, :]
226
-
227
- deg = theta[max_indice]
228
- if deg >= 90:
229
- merged_segments.append([x_min, y_max, x_max, y_min])
230
- else:
231
- merged_segments.append([x_min, y_min, x_max, y_max])
232
-
233
- # 2. get intersections
234
- new_segments = np.array(merged_segments) # (x1, y1, x2, y2)
235
- start = new_segments[:, :2] # (x1, y1)
236
- end = new_segments[:, 2:] # (x2, y2)
237
- new_centers = (start + end) / 2.0
238
- diff = start - end
239
- dist_segments = np.sqrt(np.sum(diff ** 2, axis=-1))
240
-
241
- # ax + by = c
242
- a = diff[:, 1]
243
- b = -diff[:, 0]
244
- c = a * start[:, 0] + b * start[:, 1]
245
- pre_det = a[:, None] * b[None, :]
246
- det = pre_det - np.transpose(pre_det)
247
-
248
- pre_inter_y = a[:, None] * c[None, :]
249
- inter_y = (pre_inter_y - np.transpose(pre_inter_y)) / (det + 1e-10)
250
- pre_inter_x = c[:, None] * b[None, :]
251
- inter_x = (pre_inter_x - np.transpose(pre_inter_x)) / (det + 1e-10)
252
- inter_pts = np.concatenate([inter_x[:, :, None], inter_y[:, :, None]], axis=-1).astype('int32')
253
-
254
- # 3. get corner information
255
- # 3.1 get distance
256
- '''
257
- dist_segments:
258
- | dist(0), dist(1), dist(2), ...|
259
- dist_inter_to_segment1:
260
- | dist(inter,0), dist(inter,0), dist(inter,0), ... |
261
- | dist(inter,1), dist(inter,1), dist(inter,1), ... |
262
- ...
263
- dist_inter_to_semgnet2:
264
- | dist(inter,0), dist(inter,1), dist(inter,2), ... |
265
- | dist(inter,0), dist(inter,1), dist(inter,2), ... |
266
- ...
267
- '''
268
-
269
- dist_inter_to_segment1_start = np.sqrt(
270
- np.sum(((inter_pts - start[:, None, :]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
271
- dist_inter_to_segment1_end = np.sqrt(
272
- np.sum(((inter_pts - end[:, None, :]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
273
- dist_inter_to_segment2_start = np.sqrt(
274
- np.sum(((inter_pts - start[None, :, :]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
275
- dist_inter_to_segment2_end = np.sqrt(
276
- np.sum(((inter_pts - end[None, :, :]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
277
-
278
- # sort ascending
279
- dist_inter_to_segment1 = np.sort(
280
- np.concatenate([dist_inter_to_segment1_start, dist_inter_to_segment1_end], axis=-1),
281
- axis=-1) # [n_batch, n_batch, 2]
282
- dist_inter_to_segment2 = np.sort(
283
- np.concatenate([dist_inter_to_segment2_start, dist_inter_to_segment2_end], axis=-1),
284
- axis=-1) # [n_batch, n_batch, 2]
285
-
286
- # 3.2 get degree
287
- inter_to_start = new_centers[:, None, :] - inter_pts
288
- deg_inter_to_start = np.arctan2(inter_to_start[:, :, 1], inter_to_start[:, :, 0]) * 180 / np.pi
289
- deg_inter_to_start[deg_inter_to_start < 0.0] += 360
290
- inter_to_end = new_centers[None, :, :] - inter_pts
291
- deg_inter_to_end = np.arctan2(inter_to_end[:, :, 1], inter_to_end[:, :, 0]) * 180 / np.pi
292
- deg_inter_to_end[deg_inter_to_end < 0.0] += 360
293
-
294
- '''
295
- B -- G
296
- | |
297
- C -- R
298
- B : blue / G: green / C: cyan / R: red
299
-
300
- 0 -- 1
301
- | |
302
- 3 -- 2
303
- '''
304
- # rename variables
305
- deg1_map, deg2_map = deg_inter_to_start, deg_inter_to_end
306
- # sort deg ascending
307
- deg_sort = np.sort(np.concatenate([deg1_map[:, :, None], deg2_map[:, :, None]], axis=-1), axis=-1)
308
-
309
- deg_diff_map = np.abs(deg1_map - deg2_map)
310
- # we only consider the smallest degree of intersect
311
- deg_diff_map[deg_diff_map > 180] = 360 - deg_diff_map[deg_diff_map > 180]
312
-
313
- # define available degree range
314
- deg_range = [60, 120]
315
-
316
- corner_dict = {corner_info: [] for corner_info in range(4)}
317
- inter_points = []
318
- for i in range(inter_pts.shape[0]):
319
- for j in range(i + 1, inter_pts.shape[1]):
320
- # i, j > line index, always i < j
321
- x, y = inter_pts[i, j, :]
322
- deg1, deg2 = deg_sort[i, j, :]
323
- deg_diff = deg_diff_map[i, j]
324
-
325
- check_degree = deg_diff > deg_range[0] and deg_diff < deg_range[1]
326
-
327
- outside_ratio = params['outside_ratio'] # over ratio >>> drop it!
328
- inside_ratio = params['inside_ratio'] # over ratio >>> drop it!
329
- check_distance = ((dist_inter_to_segment1[i, j, 1] >= dist_segments[i] and \
330
- dist_inter_to_segment1[i, j, 0] <= dist_segments[i] * outside_ratio) or \
331
- (dist_inter_to_segment1[i, j, 1] <= dist_segments[i] and \
332
- dist_inter_to_segment1[i, j, 0] <= dist_segments[i] * inside_ratio)) and \
333
- ((dist_inter_to_segment2[i, j, 1] >= dist_segments[j] and \
334
- dist_inter_to_segment2[i, j, 0] <= dist_segments[j] * outside_ratio) or \
335
- (dist_inter_to_segment2[i, j, 1] <= dist_segments[j] and \
336
- dist_inter_to_segment2[i, j, 0] <= dist_segments[j] * inside_ratio))
337
-
338
- if check_degree and check_distance:
339
- corner_info = None
340
-
341
- if (deg1 >= 0 and deg1 <= 45 and deg2 >= 45 and deg2 <= 120) or \
342
- (deg2 >= 315 and deg1 >= 45 and deg1 <= 120):
343
- corner_info, color_info = 0, 'blue'
344
- elif (deg1 >= 45 and deg1 <= 125 and deg2 >= 125 and deg2 <= 225):
345
- corner_info, color_info = 1, 'green'
346
- elif (deg1 >= 125 and deg1 <= 225 and deg2 >= 225 and deg2 <= 315):
347
- corner_info, color_info = 2, 'black'
348
- elif (deg1 >= 0 and deg1 <= 45 and deg2 >= 225 and deg2 <= 315) or \
349
- (deg2 >= 315 and deg1 >= 225 and deg1 <= 315):
350
- corner_info, color_info = 3, 'cyan'
351
- else:
352
- corner_info, color_info = 4, 'red' # we don't use it
353
- continue
354
-
355
- corner_dict[corner_info].append([x, y, i, j])
356
- inter_points.append([x, y])
357
-
358
- square_list = []
359
- connect_list = []
360
- segments_list = []
361
- for corner0 in corner_dict[0]:
362
- for corner1 in corner_dict[1]:
363
- connect01 = False
364
- for corner0_line in corner0[2:]:
365
- if corner0_line in corner1[2:]:
366
- connect01 = True
367
- break
368
- if connect01:
369
- for corner2 in corner_dict[2]:
370
- connect12 = False
371
- for corner1_line in corner1[2:]:
372
- if corner1_line in corner2[2:]:
373
- connect12 = True
374
- break
375
- if connect12:
376
- for corner3 in corner_dict[3]:
377
- connect23 = False
378
- for corner2_line in corner2[2:]:
379
- if corner2_line in corner3[2:]:
380
- connect23 = True
381
- break
382
- if connect23:
383
- for corner3_line in corner3[2:]:
384
- if corner3_line in corner0[2:]:
385
- # SQUARE!!!
386
- '''
387
- 0 -- 1
388
- | |
389
- 3 -- 2
390
- square_list:
391
- order: 0 > 1 > 2 > 3
392
- | x0, y0, x1, y1, x2, y2, x3, y3 |
393
- | x0, y0, x1, y1, x2, y2, x3, y3 |
394
- ...
395
- connect_list:
396
- order: 01 > 12 > 23 > 30
397
- | line_idx01, line_idx12, line_idx23, line_idx30 |
398
- | line_idx01, line_idx12, line_idx23, line_idx30 |
399
- ...
400
- segments_list:
401
- order: 0 > 1 > 2 > 3
402
- | line_idx0_i, line_idx0_j, line_idx1_i, line_idx1_j, line_idx2_i, line_idx2_j, line_idx3_i, line_idx3_j |
403
- | line_idx0_i, line_idx0_j, line_idx1_i, line_idx1_j, line_idx2_i, line_idx2_j, line_idx3_i, line_idx3_j |
404
- ...
405
- '''
406
- square_list.append(corner0[:2] + corner1[:2] + corner2[:2] + corner3[:2])
407
- connect_list.append([corner0_line, corner1_line, corner2_line, corner3_line])
408
- segments_list.append(corner0[2:] + corner1[2:] + corner2[2:] + corner3[2:])
409
-
410
- def check_outside_inside(segments_info, connect_idx):
411
- # return 'outside or inside', min distance, cover_param, peri_param
412
- if connect_idx == segments_info[0]:
413
- check_dist_mat = dist_inter_to_segment1
414
- else:
415
- check_dist_mat = dist_inter_to_segment2
416
-
417
- i, j = segments_info
418
- min_dist, max_dist = check_dist_mat[i, j, :]
419
- connect_dist = dist_segments[connect_idx]
420
- if max_dist > connect_dist:
421
- return 'outside', min_dist, 0, 1
422
- else:
423
- return 'inside', min_dist, -1, -1
424
-
425
- top_square = None
426
-
427
- try:
428
- map_size = input_shape[0] / 2
429
- squares = np.array(square_list).reshape([-1, 4, 2])
430
- score_array = []
431
- connect_array = np.array(connect_list)
432
- segments_array = np.array(segments_list).reshape([-1, 4, 2])
433
-
434
- # get degree of corners:
435
- squares_rollup = np.roll(squares, 1, axis=1)
436
- squares_rolldown = np.roll(squares, -1, axis=1)
437
- vec1 = squares_rollup - squares
438
- normalized_vec1 = vec1 / (np.linalg.norm(vec1, axis=-1, keepdims=True) + 1e-10)
439
- vec2 = squares_rolldown - squares
440
- normalized_vec2 = vec2 / (np.linalg.norm(vec2, axis=-1, keepdims=True) + 1e-10)
441
- inner_products = np.sum(normalized_vec1 * normalized_vec2, axis=-1) # [n_squares, 4]
442
- squares_degree = np.arccos(inner_products) * 180 / np.pi # [n_squares, 4]
443
-
444
- # get square score
445
- overlap_scores = []
446
- degree_scores = []
447
- length_scores = []
448
-
449
- for connects, segments, square, degree in zip(connect_array, segments_array, squares, squares_degree):
450
- '''
451
- 0 -- 1
452
- | |
453
- 3 -- 2
454
-
455
- # segments: [4, 2]
456
- # connects: [4]
457
- '''
458
-
459
- ###################################### OVERLAP SCORES
460
- cover = 0
461
- perimeter = 0
462
- # check 0 > 1 > 2 > 3
463
- square_length = []
464
-
465
- for start_idx in range(4):
466
- end_idx = (start_idx + 1) % 4
467
-
468
- connect_idx = connects[start_idx] # segment idx of segment01
469
- start_segments = segments[start_idx]
470
- end_segments = segments[end_idx]
471
-
472
- start_point = square[start_idx]
473
- end_point = square[end_idx]
474
-
475
- # check whether outside or inside
476
- start_position, start_min, start_cover_param, start_peri_param = check_outside_inside(start_segments,
477
- connect_idx)
478
- end_position, end_min, end_cover_param, end_peri_param = check_outside_inside(end_segments, connect_idx)
479
-
480
- cover += dist_segments[connect_idx] + start_cover_param * start_min + end_cover_param * end_min
481
- perimeter += dist_segments[connect_idx] + start_peri_param * start_min + end_peri_param * end_min
482
-
483
- square_length.append(
484
- dist_segments[connect_idx] + start_peri_param * start_min + end_peri_param * end_min)
485
-
486
- overlap_scores.append(cover / perimeter)
487
- ######################################
488
- ###################################### DEGREE SCORES
489
- '''
490
- deg0 vs deg2
491
- deg1 vs deg3
492
- '''
493
- deg0, deg1, deg2, deg3 = degree
494
- deg_ratio1 = deg0 / deg2
495
- if deg_ratio1 > 1.0:
496
- deg_ratio1 = 1 / deg_ratio1
497
- deg_ratio2 = deg1 / deg3
498
- if deg_ratio2 > 1.0:
499
- deg_ratio2 = 1 / deg_ratio2
500
- degree_scores.append((deg_ratio1 + deg_ratio2) / 2)
501
- ######################################
502
- ###################################### LENGTH SCORES
503
- '''
504
- len0 vs len2
505
- len1 vs len3
506
- '''
507
- len0, len1, len2, len3 = square_length
508
- len_ratio1 = len0 / len2 if len2 > len0 else len2 / len0
509
- len_ratio2 = len1 / len3 if len3 > len1 else len3 / len1
510
- length_scores.append((len_ratio1 + len_ratio2) / 2)
511
-
512
- ######################################
513
-
514
- overlap_scores = np.array(overlap_scores)
515
- overlap_scores /= np.max(overlap_scores)
516
-
517
- degree_scores = np.array(degree_scores)
518
- # degree_scores /= np.max(degree_scores)
519
-
520
- length_scores = np.array(length_scores)
521
-
522
- ###################################### AREA SCORES
523
- area_scores = np.reshape(squares, [-1, 4, 2])
524
- area_x = area_scores[:, :, 0]
525
- area_y = area_scores[:, :, 1]
526
- correction = area_x[:, -1] * area_y[:, 0] - area_y[:, -1] * area_x[:, 0]
527
- area_scores = np.sum(area_x[:, :-1] * area_y[:, 1:], axis=-1) - np.sum(area_y[:, :-1] * area_x[:, 1:], axis=-1)
528
- area_scores = 0.5 * np.abs(area_scores + correction)
529
- area_scores /= (map_size * map_size) # np.max(area_scores)
530
- ######################################
531
-
532
- ###################################### CENTER SCORES
533
- centers = np.array([[256 // 2, 256 // 2]], dtype='float32') # [1, 2]
534
- # squares: [n, 4, 2]
535
- square_centers = np.mean(squares, axis=1) # [n, 2]
536
- center2center = np.sqrt(np.sum((centers - square_centers) ** 2))
537
- center_scores = center2center / (map_size / np.sqrt(2.0))
538
-
539
- '''
540
- score_w = [overlap, degree, area, center, length]
541
- '''
542
- score_w = [0.0, 1.0, 10.0, 0.5, 1.0]
543
- score_array = params['w_overlap'] * overlap_scores \
544
- + params['w_degree'] * degree_scores \
545
- + params['w_area'] * area_scores \
546
- - params['w_center'] * center_scores \
547
- + params['w_length'] * length_scores
548
-
549
- best_square = []
550
-
551
- sorted_idx = np.argsort(score_array)[::-1]
552
- score_array = score_array[sorted_idx]
553
- squares = squares[sorted_idx]
554
-
555
- except Exception as e:
556
- pass
557
-
558
- '''return list
559
- merged_lines, squares, scores
560
- '''
561
-
562
- try:
563
- new_segments[:, 0] = new_segments[:, 0] * 2 / input_shape[1] * original_shape[1]
564
- new_segments[:, 1] = new_segments[:, 1] * 2 / input_shape[0] * original_shape[0]
565
- new_segments[:, 2] = new_segments[:, 2] * 2 / input_shape[1] * original_shape[1]
566
- new_segments[:, 3] = new_segments[:, 3] * 2 / input_shape[0] * original_shape[0]
567
- except:
568
- new_segments = []
569
-
570
- try:
571
- squares[:, :, 0] = squares[:, :, 0] * 2 / input_shape[1] * original_shape[1]
572
- squares[:, :, 1] = squares[:, :, 1] * 2 / input_shape[0] * original_shape[0]
573
- except:
574
- squares = []
575
- score_array = []
576
-
577
- try:
578
- inter_points = np.array(inter_points)
579
- inter_points[:, 0] = inter_points[:, 0] * 2 / input_shape[1] * original_shape[1]
580
- inter_points[:, 1] = inter_points[:, 1] * 2 / input_shape[0] * original_shape[0]
581
- except:
582
- inter_points = []
583
-
584
- return new_segments, squares, score_array, inter_points
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/open_pose/__init__.py DELETED
@@ -1,234 +0,0 @@
1
- # Openpose
2
- # Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose
3
- # 2nd Edited by https://github.com/Hzzone/pytorch-openpose
4
- # 3rd Edited by ControlNet
5
- # 4th Edited by ControlNet (added face and correct hands)
6
- # 5th Edited by ControlNet (Improved JSON serialization/deserialization, and lots of bug fixs)
7
- # This preprocessor is licensed by CMU for non-commercial use only.
8
-
9
-
10
- import os
11
-
12
- os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
13
-
14
- import json
15
- import warnings
16
- from typing import Callable, List, NamedTuple, Tuple, Union
17
-
18
- import cv2
19
- import numpy as np
20
- import torch
21
- from huggingface_hub import hf_hub_download
22
- from PIL import Image
23
-
24
- from ..util import HWC3, resize_image
25
- from . import util
26
- from .body import Body, BodyResult, Keypoint
27
- from .face import Face
28
- from .hand import Hand
29
-
30
- HandResult = List[Keypoint]
31
- FaceResult = List[Keypoint]
32
-
33
- class PoseResult(NamedTuple):
34
- body: BodyResult
35
- left_hand: Union[HandResult, None]
36
- right_hand: Union[HandResult, None]
37
- face: Union[FaceResult, None]
38
-
39
- def draw_poses(poses: List[PoseResult], H, W, draw_body=True, draw_hand=True, draw_face=True):
40
- """
41
- Draw the detected poses on an empty canvas.
42
-
43
- Args:
44
- poses (List[PoseResult]): A list of PoseResult objects containing the detected poses.
45
- H (int): The height of the canvas.
46
- W (int): The width of the canvas.
47
- draw_body (bool, optional): Whether to draw body keypoints. Defaults to True.
48
- draw_hand (bool, optional): Whether to draw hand keypoints. Defaults to True.
49
- draw_face (bool, optional): Whether to draw face keypoints. Defaults to True.
50
-
51
- Returns:
52
- numpy.ndarray: A 3D numpy array representing the canvas with the drawn poses.
53
- """
54
- canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)
55
-
56
- for pose in poses:
57
- if draw_body:
58
- canvas = util.draw_bodypose(canvas, pose.body.keypoints)
59
-
60
- if draw_hand:
61
- canvas = util.draw_handpose(canvas, pose.left_hand)
62
- canvas = util.draw_handpose(canvas, pose.right_hand)
63
-
64
- if draw_face:
65
- canvas = util.draw_facepose(canvas, pose.face)
66
-
67
- return canvas
68
-
69
-
70
- class OpenposeDetector:
71
- """
72
- A class for detecting human poses in images using the Openpose model.
73
-
74
- Attributes:
75
- model_dir (str): Path to the directory where the pose models are stored.
76
- """
77
- def __init__(self, body_estimation, hand_estimation=None, face_estimation=None):
78
- self.body_estimation = body_estimation
79
- self.hand_estimation = hand_estimation
80
- self.face_estimation = face_estimation
81
-
82
- @classmethod
83
- def from_pretrained(cls, pretrained_model_or_path, filename=None, hand_filename=None, face_filename=None, cache_dir=None, local_files_only=False):
84
-
85
- if pretrained_model_or_path == "lllyasviel/ControlNet":
86
- filename = filename or "annotator/ckpts/body_pose_model.pth"
87
- hand_filename = hand_filename or "annotator/ckpts/hand_pose_model.pth"
88
- face_filename = face_filename or "facenet.pth"
89
-
90
- face_pretrained_model_or_path = "lllyasviel/Annotators"
91
- else:
92
- filename = filename or "body_pose_model.pth"
93
- hand_filename = hand_filename or "hand_pose_model.pth"
94
- face_filename = face_filename or "facenet.pth"
95
-
96
- face_pretrained_model_or_path = pretrained_model_or_path
97
-
98
- if os.path.isdir(pretrained_model_or_path):
99
- body_model_path = os.path.join(pretrained_model_or_path, filename)
100
- hand_model_path = os.path.join(pretrained_model_or_path, hand_filename)
101
- face_model_path = os.path.join(face_pretrained_model_or_path, face_filename)
102
- else:
103
- body_model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir, local_files_only=local_files_only)
104
- hand_model_path = hf_hub_download(pretrained_model_or_path, hand_filename, cache_dir=cache_dir, local_files_only=local_files_only)
105
- face_model_path = hf_hub_download(face_pretrained_model_or_path, face_filename, cache_dir=cache_dir, local_files_only=local_files_only)
106
-
107
- body_estimation = Body(body_model_path)
108
- hand_estimation = Hand(hand_model_path)
109
- face_estimation = Face(face_model_path)
110
-
111
- return cls(body_estimation, hand_estimation, face_estimation)
112
-
113
- def to(self, device):
114
- self.body_estimation.to(device)
115
- self.hand_estimation.to(device)
116
- self.face_estimation.to(device)
117
- return self
118
-
119
- def detect_hands(self, body: BodyResult, oriImg) -> Tuple[Union[HandResult, None], Union[HandResult, None]]:
120
- left_hand = None
121
- right_hand = None
122
- H, W, _ = oriImg.shape
123
- for x, y, w, is_left in util.handDetect(body, oriImg):
124
- peaks = self.hand_estimation(oriImg[y:y+w, x:x+w, :]).astype(np.float32)
125
- if peaks.ndim == 2 and peaks.shape[1] == 2:
126
- peaks[:, 0] = np.where(peaks[:, 0] < 1e-6, -1, peaks[:, 0] + x) / float(W)
127
- peaks[:, 1] = np.where(peaks[:, 1] < 1e-6, -1, peaks[:, 1] + y) / float(H)
128
-
129
- hand_result = [
130
- Keypoint(x=peak[0], y=peak[1])
131
- for peak in peaks
132
- ]
133
-
134
- if is_left:
135
- left_hand = hand_result
136
- else:
137
- right_hand = hand_result
138
-
139
- return left_hand, right_hand
140
-
141
- def detect_face(self, body: BodyResult, oriImg) -> Union[FaceResult, None]:
142
- face = util.faceDetect(body, oriImg)
143
- if face is None:
144
- return None
145
-
146
- x, y, w = face
147
- H, W, _ = oriImg.shape
148
- heatmaps = self.face_estimation(oriImg[y:y+w, x:x+w, :])
149
- peaks = self.face_estimation.compute_peaks_from_heatmaps(heatmaps).astype(np.float32)
150
- if peaks.ndim == 2 and peaks.shape[1] == 2:
151
- peaks[:, 0] = np.where(peaks[:, 0] < 1e-6, -1, peaks[:, 0] + x) / float(W)
152
- peaks[:, 1] = np.where(peaks[:, 1] < 1e-6, -1, peaks[:, 1] + y) / float(H)
153
- return [
154
- Keypoint(x=peak[0], y=peak[1])
155
- for peak in peaks
156
- ]
157
-
158
- return None
159
-
160
- def detect_poses(self, oriImg, include_hand=False, include_face=False) -> List[PoseResult]:
161
- """
162
- Detect poses in the given image.
163
- Args:
164
- oriImg (numpy.ndarray): The input image for pose detection.
165
- include_hand (bool, optional): Whether to include hand detection. Defaults to False.
166
- include_face (bool, optional): Whether to include face detection. Defaults to False.
167
-
168
- Returns:
169
- List[PoseResult]: A list of PoseResult objects containing the detected poses.
170
- """
171
- oriImg = oriImg[:, :, ::-1].copy()
172
- H, W, C = oriImg.shape
173
- with torch.no_grad():
174
- candidate, subset = self.body_estimation(oriImg)
175
- bodies = self.body_estimation.format_body_result(candidate, subset)
176
-
177
- results = []
178
- for body in bodies:
179
- left_hand, right_hand, face = (None,) * 3
180
- if include_hand:
181
- left_hand, right_hand = self.detect_hands(body, oriImg)
182
- if include_face:
183
- face = self.detect_face(body, oriImg)
184
-
185
- results.append(PoseResult(BodyResult(
186
- keypoints=[
187
- Keypoint(
188
- x=keypoint.x / float(W),
189
- y=keypoint.y / float(H)
190
- ) if keypoint is not None else None
191
- for keypoint in body.keypoints
192
- ],
193
- total_score=body.total_score,
194
- total_parts=body.total_parts
195
- ), left_hand, right_hand, face))
196
-
197
- return results
198
-
199
- def __call__(self, input_image, detect_resolution=512, image_resolution=512, include_body=True, include_hand=False, include_face=False, hand_and_face=None, output_type="pil", **kwargs):
200
- if hand_and_face is not None:
201
- warnings.warn("hand_and_face is deprecated. Use include_hand and include_face instead.", DeprecationWarning)
202
- include_hand = hand_and_face
203
- include_face = hand_and_face
204
-
205
- if "return_pil" in kwargs:
206
- warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
207
- output_type = "pil" if kwargs["return_pil"] else "np"
208
- if type(output_type) is bool:
209
- warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
210
- if output_type:
211
- output_type = "pil"
212
-
213
- if not isinstance(input_image, np.ndarray):
214
- input_image = np.array(input_image, dtype=np.uint8)
215
-
216
- input_image = HWC3(input_image)
217
- input_image = resize_image(input_image, detect_resolution)
218
- H, W, C = input_image.shape
219
-
220
- poses = self.detect_poses(input_image, include_hand, include_face)
221
- canvas = draw_poses(poses, H, W, draw_body=include_body, draw_hand=include_hand, draw_face=include_face)
222
-
223
- detected_map = canvas
224
- detected_map = HWC3(detected_map)
225
-
226
- img = resize_image(input_image, image_resolution)
227
- H, W, C = img.shape
228
-
229
- detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
230
-
231
- if output_type == "pil":
232
- detected_map = Image.fromarray(detected_map)
233
-
234
- return detected_map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/open_pose/body.py DELETED
@@ -1,260 +0,0 @@
1
- import math
2
- from typing import List, NamedTuple, Union
3
-
4
- import cv2
5
- import numpy as np
6
- import torch
7
- from scipy.ndimage.filters import gaussian_filter
8
-
9
- from . import util
10
- from .model import bodypose_model
11
-
12
-
13
- class Keypoint(NamedTuple):
14
- x: float
15
- y: float
16
- score: float = 1.0
17
- id: int = -1
18
-
19
-
20
- class BodyResult(NamedTuple):
21
- # Note: Using `Union` instead of `|` operator as the ladder is a Python
22
- # 3.10 feature.
23
- # Annotator code should be Python 3.8 Compatible, as controlnet repo uses
24
- # Python 3.8 environment.
25
- # https://github.com/lllyasviel/ControlNet/blob/d3284fcd0972c510635a4f5abe2eeb71dc0de524/environment.yaml#L6
26
- keypoints: List[Union[Keypoint, None]]
27
- total_score: float
28
- total_parts: int
29
-
30
-
31
- class Body(object):
32
- def __init__(self, model_path):
33
- self.model = bodypose_model()
34
- model_dict = util.transfer(self.model, torch.load(model_path))
35
- self.model.load_state_dict(model_dict)
36
- self.model.eval()
37
-
38
- def to(self, device):
39
- self.model.to(device)
40
- return self
41
-
42
- def __call__(self, oriImg):
43
- device = next(iter(self.model.parameters())).device
44
- # scale_search = [0.5, 1.0, 1.5, 2.0]
45
- scale_search = [0.5]
46
- boxsize = 368
47
- stride = 8
48
- padValue = 128
49
- thre1 = 0.1
50
- thre2 = 0.05
51
- multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search]
52
- heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 19))
53
- paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))
54
-
55
- for m in range(len(multiplier)):
56
- scale = multiplier[m]
57
- imageToTest = util.smart_resize_k(oriImg, fx=scale, fy=scale)
58
- imageToTest_padded, pad = util.padRightDownCorner(imageToTest, stride, padValue)
59
- im = np.transpose(np.float32(imageToTest_padded[:, :, :, np.newaxis]), (3, 2, 0, 1)) / 256 - 0.5
60
- im = np.ascontiguousarray(im)
61
-
62
- data = torch.from_numpy(im).float()
63
- data = data.to(device)
64
- # data = data.permute([2, 0, 1]).unsqueeze(0).float()
65
- with torch.no_grad():
66
- Mconv7_stage6_L1, Mconv7_stage6_L2 = self.model(data)
67
- Mconv7_stage6_L1 = Mconv7_stage6_L1.cpu().numpy()
68
- Mconv7_stage6_L2 = Mconv7_stage6_L2.cpu().numpy()
69
-
70
- # extract outputs, resize, and remove padding
71
- # heatmap = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[1]].data), (1, 2, 0)) # output 1 is heatmaps
72
- heatmap = np.transpose(np.squeeze(Mconv7_stage6_L2), (1, 2, 0)) # output 1 is heatmaps
73
- heatmap = util.smart_resize_k(heatmap, fx=stride, fy=stride)
74
- heatmap = heatmap[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
75
- heatmap = util.smart_resize(heatmap, (oriImg.shape[0], oriImg.shape[1]))
76
-
77
- # paf = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[0]].data), (1, 2, 0)) # output 0 is PAFs
78
- paf = np.transpose(np.squeeze(Mconv7_stage6_L1), (1, 2, 0)) # output 0 is PAFs
79
- paf = util.smart_resize_k(paf, fx=stride, fy=stride)
80
- paf = paf[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
81
- paf = util.smart_resize(paf, (oriImg.shape[0], oriImg.shape[1]))
82
-
83
- heatmap_avg += heatmap_avg + heatmap / len(multiplier)
84
- paf_avg += + paf / len(multiplier)
85
-
86
- all_peaks = []
87
- peak_counter = 0
88
-
89
- for part in range(18):
90
- map_ori = heatmap_avg[:, :, part]
91
- one_heatmap = gaussian_filter(map_ori, sigma=3)
92
-
93
- map_left = np.zeros(one_heatmap.shape)
94
- map_left[1:, :] = one_heatmap[:-1, :]
95
- map_right = np.zeros(one_heatmap.shape)
96
- map_right[:-1, :] = one_heatmap[1:, :]
97
- map_up = np.zeros(one_heatmap.shape)
98
- map_up[:, 1:] = one_heatmap[:, :-1]
99
- map_down = np.zeros(one_heatmap.shape)
100
- map_down[:, :-1] = one_heatmap[:, 1:]
101
-
102
- peaks_binary = np.logical_and.reduce(
103
- (one_heatmap >= map_left, one_heatmap >= map_right, one_heatmap >= map_up, one_heatmap >= map_down, one_heatmap > thre1))
104
- peaks = list(zip(np.nonzero(peaks_binary)[1], np.nonzero(peaks_binary)[0])) # note reverse
105
- peaks_with_score = [x + (map_ori[x[1], x[0]],) for x in peaks]
106
- peak_id = range(peak_counter, peak_counter + len(peaks))
107
- peaks_with_score_and_id = [peaks_with_score[i] + (peak_id[i],) for i in range(len(peak_id))]
108
-
109
- all_peaks.append(peaks_with_score_and_id)
110
- peak_counter += len(peaks)
111
-
112
- # find connection in the specified sequence, center 29 is in the position 15
113
- limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
114
- [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
115
- [1, 16], [16, 18], [3, 17], [6, 18]]
116
- # the middle joints heatmap correpondence
117
- mapIdx = [[31, 32], [39, 40], [33, 34], [35, 36], [41, 42], [43, 44], [19, 20], [21, 22], \
118
- [23, 24], [25, 26], [27, 28], [29, 30], [47, 48], [49, 50], [53, 54], [51, 52], \
119
- [55, 56], [37, 38], [45, 46]]
120
-
121
- connection_all = []
122
- special_k = []
123
- mid_num = 10
124
-
125
- for k in range(len(mapIdx)):
126
- score_mid = paf_avg[:, :, [x - 19 for x in mapIdx[k]]]
127
- candA = all_peaks[limbSeq[k][0] - 1]
128
- candB = all_peaks[limbSeq[k][1] - 1]
129
- nA = len(candA)
130
- nB = len(candB)
131
- indexA, indexB = limbSeq[k]
132
- if (nA != 0 and nB != 0):
133
- connection_candidate = []
134
- for i in range(nA):
135
- for j in range(nB):
136
- vec = np.subtract(candB[j][:2], candA[i][:2])
137
- norm = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
138
- norm = max(0.001, norm)
139
- vec = np.divide(vec, norm)
140
-
141
- startend = list(zip(np.linspace(candA[i][0], candB[j][0], num=mid_num), \
142
- np.linspace(candA[i][1], candB[j][1], num=mid_num)))
143
-
144
- vec_x = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 0] \
145
- for I in range(len(startend))])
146
- vec_y = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 1] \
147
- for I in range(len(startend))])
148
-
149
- score_midpts = np.multiply(vec_x, vec[0]) + np.multiply(vec_y, vec[1])
150
- score_with_dist_prior = sum(score_midpts) / len(score_midpts) + min(
151
- 0.5 * oriImg.shape[0] / norm - 1, 0)
152
- criterion1 = len(np.nonzero(score_midpts > thre2)[0]) > 0.8 * len(score_midpts)
153
- criterion2 = score_with_dist_prior > 0
154
- if criterion1 and criterion2:
155
- connection_candidate.append(
156
- [i, j, score_with_dist_prior, score_with_dist_prior + candA[i][2] + candB[j][2]])
157
-
158
- connection_candidate = sorted(connection_candidate, key=lambda x: x[2], reverse=True)
159
- connection = np.zeros((0, 5))
160
- for c in range(len(connection_candidate)):
161
- i, j, s = connection_candidate[c][0:3]
162
- if (i not in connection[:, 3] and j not in connection[:, 4]):
163
- connection = np.vstack([connection, [candA[i][3], candB[j][3], s, i, j]])
164
- if (len(connection) >= min(nA, nB)):
165
- break
166
-
167
- connection_all.append(connection)
168
- else:
169
- special_k.append(k)
170
- connection_all.append([])
171
-
172
- # last number in each row is the total parts number of that person
173
- # the second last number in each row is the score of the overall configuration
174
- subset = -1 * np.ones((0, 20))
175
- candidate = np.array([item for sublist in all_peaks for item in sublist])
176
-
177
- for k in range(len(mapIdx)):
178
- if k not in special_k:
179
- partAs = connection_all[k][:, 0]
180
- partBs = connection_all[k][:, 1]
181
- indexA, indexB = np.array(limbSeq[k]) - 1
182
-
183
- for i in range(len(connection_all[k])): # = 1:size(temp,1)
184
- found = 0
185
- subset_idx = [-1, -1]
186
- for j in range(len(subset)): # 1:size(subset,1):
187
- if subset[j][indexA] == partAs[i] or subset[j][indexB] == partBs[i]:
188
- subset_idx[found] = j
189
- found += 1
190
-
191
- if found == 1:
192
- j = subset_idx[0]
193
- if subset[j][indexB] != partBs[i]:
194
- subset[j][indexB] = partBs[i]
195
- subset[j][-1] += 1
196
- subset[j][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
197
- elif found == 2: # if found 2 and disjoint, merge them
198
- j1, j2 = subset_idx
199
- membership = ((subset[j1] >= 0).astype(int) + (subset[j2] >= 0).astype(int))[:-2]
200
- if len(np.nonzero(membership == 2)[0]) == 0: # merge
201
- subset[j1][:-2] += (subset[j2][:-2] + 1)
202
- subset[j1][-2:] += subset[j2][-2:]
203
- subset[j1][-2] += connection_all[k][i][2]
204
- subset = np.delete(subset, j2, 0)
205
- else: # as like found == 1
206
- subset[j1][indexB] = partBs[i]
207
- subset[j1][-1] += 1
208
- subset[j1][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
209
-
210
- # if find no partA in the subset, create a new subset
211
- elif not found and k < 17:
212
- row = -1 * np.ones(20)
213
- row[indexA] = partAs[i]
214
- row[indexB] = partBs[i]
215
- row[-1] = 2
216
- row[-2] = sum(candidate[connection_all[k][i, :2].astype(int), 2]) + connection_all[k][i][2]
217
- subset = np.vstack([subset, row])
218
- # delete some rows of subset which has few parts occur
219
- deleteIdx = []
220
- for i in range(len(subset)):
221
- if subset[i][-1] < 4 or subset[i][-2] / subset[i][-1] < 0.4:
222
- deleteIdx.append(i)
223
- subset = np.delete(subset, deleteIdx, axis=0)
224
-
225
- # subset: n*20 array, 0-17 is the index in candidate, 18 is the total score, 19 is the total parts
226
- # candidate: x, y, score, id
227
- return candidate, subset
228
-
229
- @staticmethod
230
- def format_body_result(candidate: np.ndarray, subset: np.ndarray) -> List[BodyResult]:
231
- """
232
- Format the body results from the candidate and subset arrays into a list of BodyResult objects.
233
-
234
- Args:
235
- candidate (np.ndarray): An array of candidates containing the x, y coordinates, score, and id
236
- for each body part.
237
- subset (np.ndarray): An array of subsets containing indices to the candidate array for each
238
- person detected. The last two columns of each row hold the total score and total parts
239
- of the person.
240
-
241
- Returns:
242
- List[BodyResult]: A list of BodyResult objects, where each object represents a person with
243
- detected keypoints, total score, and total parts.
244
- """
245
- return [
246
- BodyResult(
247
- keypoints=[
248
- Keypoint(
249
- x=candidate[candidate_index][0],
250
- y=candidate[candidate_index][1],
251
- score=candidate[candidate_index][2],
252
- id=candidate[candidate_index][3]
253
- ) if candidate_index != -1 else None
254
- for candidate_index in person[:18].astype(int)
255
- ],
256
- total_score=person[18],
257
- total_parts=person[19]
258
- )
259
- for person in subset
260
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
controlnet_aux_local/open_pose/face.py DELETED
@@ -1,364 +0,0 @@
1
- import logging
2
-
3
- import numpy as np
4
- import torch
5
- import torch.nn.functional as F
6
- from torch.nn import Conv2d, MaxPool2d, Module, ReLU, init
7
- from torchvision.transforms import ToPILImage, ToTensor
8
-
9
- from . import util
10
-
11
-
12
- class FaceNet(Module):
13
- """Model the cascading heatmaps. """
14
- def __init__(self):
15
- super(FaceNet, self).__init__()
16
- # cnn to make feature map
17
- self.relu = ReLU()
18
- self.max_pooling_2d = MaxPool2d(kernel_size=2, stride=2)
19
- self.conv1_1 = Conv2d(in_channels=3, out_channels=64,
20
- kernel_size=3, stride=1, padding=1)
21
- self.conv1_2 = Conv2d(
22
- in_channels=64, out_channels=64, kernel_size=3, stride=1,
23
- padding=1)
24
- self.conv2_1 = Conv2d(
25
- in_channels=64, out_channels=128, kernel_size=3, stride=1,
26
- padding=1)
27
- self.conv2_2 = Conv2d(
28
- in_channels=128, out_channels=128, kernel_size=3, stride=1,
29
- padding=1)
30
- self.conv3_1 = Conv2d(
31
- in_channels=128, out_channels=256, kernel_size=3, stride=1,
32
- padding=1)
33
- self.conv3_2 = Conv2d(
34
- in_channels=256, out_channels=256, kernel_size=3, stride=1,
35
- padding=1)
36
- self.conv3_3 = Conv2d(
37
- in_channels=256, out_channels=256, kernel_size=3, stride=1,
38
- padding=1)
39
- self.conv3_4 = Conv2d(
40
- in_channels=256, out_channels=256, kernel_size=3, stride=1,
41
- padding=1)
42
- self.conv4_1 = Conv2d(
43
- in_channels=256, out_channels=512, kernel_size=3, stride=1,
44
- padding=1)
45
- self.conv4_2 = Conv2d(
46
- in_channels=512, out_channels=512, kernel_size=3, stride=1,
47
- padding=1)
48
- self.conv4_3 = Conv2d(
49
- in_channels=512, out_channels=512, kernel_size=3, stride=1,
50
- padding=1)
51
- self.conv4_4 = Conv2d(
52
- in_channels=512, out_channels=512, kernel_size=3, stride=1,
53
- padding=1)
54
- self.conv5_1 = Conv2d(
55
- in_channels=512, out_channels=512, kernel_size=3, stride=1,
56
- padding=1)
57
- self.conv5_2 = Conv2d(
58
- in_channels=512, out_channels=512, kernel_size=3, stride=1,
59
- padding=1)
60
- self.conv5_3_CPM = Conv2d(
61
- in_channels=512, out_channels=128, kernel_size=3, stride=1,
62
- padding=1)
63
-
64
- # stage1
65
- self.conv6_1_CPM = Conv2d(
66
- in_channels=128, out_channels=512, kernel_size=1, stride=1,
67
- padding=0)
68
- self.conv6_2_CPM = Conv2d(
69
- in_channels=512, out_channels=71, kernel_size=1, stride=1,
70
- padding=0)
71
-
72
- # stage2
73
- self.Mconv1_stage2 = Conv2d(
74
- in_channels=199, out_channels=128, kernel_size=7, stride=1,
75
- padding=3)
76
- self.Mconv2_stage2 = Conv2d(
77
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
78
- padding=3)
79
- self.Mconv3_stage2 = Conv2d(
80
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
81
- padding=3)
82
- self.Mconv4_stage2 = Conv2d(
83
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
84
- padding=3)
85
- self.Mconv5_stage2 = Conv2d(
86
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
87
- padding=3)
88
- self.Mconv6_stage2 = Conv2d(
89
- in_channels=128, out_channels=128, kernel_size=1, stride=1,
90
- padding=0)
91
- self.Mconv7_stage2 = Conv2d(
92
- in_channels=128, out_channels=71, kernel_size=1, stride=1,
93
- padding=0)
94
-
95
- # stage3
96
- self.Mconv1_stage3 = Conv2d(
97
- in_channels=199, out_channels=128, kernel_size=7, stride=1,
98
- padding=3)
99
- self.Mconv2_stage3 = Conv2d(
100
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
101
- padding=3)
102
- self.Mconv3_stage3 = Conv2d(
103
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
104
- padding=3)
105
- self.Mconv4_stage3 = Conv2d(
106
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
107
- padding=3)
108
- self.Mconv5_stage3 = Conv2d(
109
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
110
- padding=3)
111
- self.Mconv6_stage3 = Conv2d(
112
- in_channels=128, out_channels=128, kernel_size=1, stride=1,
113
- padding=0)
114
- self.Mconv7_stage3 = Conv2d(
115
- in_channels=128, out_channels=71, kernel_size=1, stride=1,
116
- padding=0)
117
-
118
- # stage4
119
- self.Mconv1_stage4 = Conv2d(
120
- in_channels=199, out_channels=128, kernel_size=7, stride=1,
121
- padding=3)
122
- self.Mconv2_stage4 = Conv2d(
123
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
124
- padding=3)
125
- self.Mconv3_stage4 = Conv2d(
126
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
127
- padding=3)
128
- self.Mconv4_stage4 = Conv2d(
129
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
130
- padding=3)
131
- self.Mconv5_stage4 = Conv2d(
132
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
133
- padding=3)
134
- self.Mconv6_stage4 = Conv2d(
135
- in_channels=128, out_channels=128, kernel_size=1, stride=1,
136
- padding=0)
137
- self.Mconv7_stage4 = Conv2d(
138
- in_channels=128, out_channels=71, kernel_size=1, stride=1,
139
- padding=0)
140
-
141
- # stage5
142
- self.Mconv1_stage5 = Conv2d(
143
- in_channels=199, out_channels=128, kernel_size=7, stride=1,
144
- padding=3)
145
- self.Mconv2_stage5 = Conv2d(
146
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
147
- padding=3)
148
- self.Mconv3_stage5 = Conv2d(
149
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
150
- padding=3)
151
- self.Mconv4_stage5 = Conv2d(
152
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
153
- padding=3)
154
- self.Mconv5_stage5 = Conv2d(
155
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
156
- padding=3)
157
- self.Mconv6_stage5 = Conv2d(
158
- in_channels=128, out_channels=128, kernel_size=1, stride=1,
159
- padding=0)
160
- self.Mconv7_stage5 = Conv2d(
161
- in_channels=128, out_channels=71, kernel_size=1, stride=1,
162
- padding=0)
163
-
164
- # stage6
165
- self.Mconv1_stage6 = Conv2d(
166
- in_channels=199, out_channels=128, kernel_size=7, stride=1,
167
- padding=3)
168
- self.Mconv2_stage6 = Conv2d(
169
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
170
- padding=3)
171
- self.Mconv3_stage6 = Conv2d(
172
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
173
- padding=3)
174
- self.Mconv4_stage6 = Conv2d(
175
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
176
- padding=3)
177
- self.Mconv5_stage6 = Conv2d(
178
- in_channels=128, out_channels=128, kernel_size=7, stride=1,
179
- padding=3)
180
- self.Mconv6_stage6 = Conv2d(
181
- in_channels=128, out_channels=128, kernel_size=1, stride=1,
182
- padding=0)
183
- self.Mconv7_stage6 = Conv2d(
184
- in_channels=128, out_channels=71, kernel_size=1, stride=1,
185
- padding=0)
186
-
187
- for m in self.modules():
188
- if isinstance(m, Conv2d):
189
- init.constant_(m.bias, 0)
190
-
191
- def forward(self, x):
192
- """Return a list of heatmaps."""
193
- heatmaps = []
194
-
195
- h = self.relu(self.conv1_1(x))
196
- h = self.relu(self.conv1_2(h))
197
- h = self.max_pooling_2d(h)
198
- h = self.relu(self.conv2_1(h))
199
- h = self.relu(self.conv2_2(h))
200
- h = self.max_pooling_2d(h)
201
- h = self.relu(self.conv3_1(h))
202
- h = self.relu(self.conv3_2(h))
203
- h = self.relu(self.conv3_3(h))
204
- h = self.relu(self.conv3_4(h))
205
- h = self.max_pooling_2d(h)
206
- h = self.relu(self.conv4_1(h))
207
- h = self.relu(self.conv4_2(h))
208
- h = self.relu(self.conv4_3(h))
209
- h = self.relu(self.conv4_4(h))
210
- h = self.relu(self.conv5_1(h))
211
- h = self.relu(self.conv5_2(h))
212
- h = self.relu(self.conv5_3_CPM(h))
213
- feature_map = h
214
-
215
- # stage1
216
- h = self.relu(self.conv6_1_CPM(h))
217
- h = self.conv6_2_CPM(h)
218
- heatmaps.append(h)
219
-
220
- # stage2
221
- h = torch.cat([h, feature_map], dim=1) # channel concat
222
- h = self.relu(self.Mconv1_stage2(h))
223
- h = self.relu(self.Mconv2_stage2(h))
224
- h = self.relu(self.Mconv3_stage2(h))
225
- h = self.relu(self.Mconv4_stage2(h))
226
- h = self.relu(self.Mconv5_stage2(h))
227
- h = self.relu(self.Mconv6_stage2(h))
228
- h = self.Mconv7_stage2(h)
229
- heatmaps.append(h)
230
-
231
- # stage3
232
- h = torch.cat([h, feature_map], dim=1) # channel concat
233
- h = self.relu(self.Mconv1_stage3(h))
234
- h = self.relu(self.Mconv2_stage3(h))
235
- h = self.relu(self.Mconv3_stage3(h))
236
- h = self.relu(self.Mconv4_stage3(h))
237
- h = self.relu(self.Mconv5_stage3(h))
238
- h = self.relu(self.Mconv6_stage3(h))
239
- h = self.Mconv7_stage3(h)
240
- heatmaps.append(h)
241
-
242
- # stage4
243
- h = torch.cat([h, feature_map], dim=1) # channel concat
244
- h = self.relu(self.Mconv1_stage4(h))
245
- h = self.relu(self.Mconv2_stage4(h))
246
- h = self.relu(self.Mconv3_stage4(h))
247
- h = self.relu(self.Mconv4_stage4(h))
248
- h = self.relu(self.Mconv5_stage4(h))
249
- h = self.relu(self.Mconv6_stage4(h))
250
- h = self.Mconv7_stage4(h)
251
- heatmaps.append(h)
252
-
253
- # stage5
254
- h = torch.cat([h, feature_map], dim=1) # channel concat
255
- h = self.relu(self.Mconv1_stage5(h))
256
- h = self.relu(self.Mconv2_stage5(h))
257
- h = self.relu(self.Mconv3_stage5(h))
258
- h = self.relu(self.Mconv4_stage5(h))
259
- h = self.relu(self.Mconv5_stage5(h))
260
- h = self.relu(self.Mconv6_stage5(h))
261
- h = self.Mconv7_stage5(h)
262
- heatmaps.append(h)
263
-
264
- # stage6
265
- h = torch.cat([h, feature_map], dim=1) # channel concat
266
- h = self.relu(self.Mconv1_stage6(h))
267
- h = self.relu(self.Mconv2_stage6(h))
268
- h = self.relu(self.Mconv3_stage6(h))
269
- h = self.relu(self.Mconv4_stage6(h))
270
- h = self.relu(self.Mconv5_stage6(h))
271
- h = self.relu(self.Mconv6_stage6(h))
272
- h = self.Mconv7_stage6(h)
273
- heatmaps.append(h)
274
-
275
- return heatmaps
276
-
277
-
278
- LOG = logging.getLogger(__name__)
279
- TOTEN = ToTensor()
280
- TOPIL = ToPILImage()
281
-
282
-
283
- params = {
284
- 'gaussian_sigma': 2.5,
285
- 'inference_img_size': 736, # 368, 736, 1312
286
- 'heatmap_peak_thresh': 0.1,
287
- 'crop_scale': 1.5,
288
- 'line_indices': [
289
- [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6],
290
- [6, 7], [7, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13],
291
- [13, 14], [14, 15], [15, 16],
292
- [17, 18], [18, 19], [19, 20], [20, 21],
293
- [22, 23], [23, 24], [24, 25], [25, 26],
294
- [27, 28], [28, 29], [29, 30],
295
- [31, 32], [32, 33], [33, 34], [34, 35],
296
- [36, 37], [37, 38], [38, 39], [39, 40], [40, 41], [41, 36],
297
- [42, 43], [43, 44], [44, 45], [45, 46], [46, 47], [47, 42],
298
- [48, 49], [49, 50], [50, 51], [51, 52], [52, 53], [53, 54],
299
- [54, 55], [55, 56], [56, 57], [57, 58], [58, 59], [59, 48],
300
- [60, 61], [61, 62], [62, 63], [63, 64], [64, 65], [65, 66],
301
- [66, 67], [67, 60]
302
- ],
303
- }
304
-
305
-
306
- class Face(object):
307
- """
308
- The OpenPose face landmark detector model.
309
-
310
- Args:
311
- inference_size: set the size of the inference image size, suggested:
312
- 368, 736, 1312, default 736
313
- gaussian_sigma: blur the heatmaps, default 2.5
314
- heatmap_peak_thresh: return landmark if over threshold, default 0.1
315
-
316
- """
317
- def __init__(self, face_model_path,
318
- inference_size=None,
319
- gaussian_sigma=None,
320
- heatmap_peak_thresh=None):
321
- self.inference_size = inference_size or params["inference_img_size"]
322
- self.sigma = gaussian_sigma or params['gaussian_sigma']
323
- self.threshold = heatmap_peak_thresh or params["heatmap_peak_thresh"]
324
- self.model = FaceNet()
325
- self.model.load_state_dict(torch.load(face_model_path))
326
- self.model.eval()
327
-
328
- def to(self, device):
329
- self.model.to(device)
330
- return self
331
-
332
- def __call__(self, face_img):
333
- device = next(iter(self.model.parameters())).device
334
- H, W, C = face_img.shape
335
-
336
- w_size = 384
337
- x_data = torch.from_numpy(util.smart_resize(face_img, (w_size, w_size))).permute([2, 0, 1]) / 256.0 - 0.5
338
-
339
- x_data = x_data.to(device)
340
-
341
- with torch.no_grad():
342
- hs = self.model(x_data[None, ...])
343
- heatmaps = F.interpolate(
344
- hs[-1],
345
- (H, W),
346
- mode='bilinear', align_corners=True).cpu().numpy()[0]
347
- return heatmaps
348
-
349
- def compute_peaks_from_heatmaps(self, heatmaps):
350
- all_peaks = []
351
- for part in range(heatmaps.shape[0]):
352
- map_ori = heatmaps[part].copy()
353
- binary = np.ascontiguousarray(map_ori > 0.05, dtype=np.uint8)
354
-
355
- if np.sum(binary) == 0:
356
- continue
357
-
358
- positions = np.where(binary > 0.5)
359
- intensities = map_ori[positions]
360
- mi = np.argmax(intensities)
361
- y, x = positions[0][mi], positions[1][mi]
362
- all_peaks.append([x, y])
363
-
364
- return np.array(all_peaks)