Spaces:
Running
on
Zero
Running
on
Zero
Upload 5 files
Browse files- README.md +11 -13
- app.py +136 -0
- app_mast3r.py +206 -0
- catmlp_dpt_head.py +94 -0
- requirements.txt +15 -0
README.md
CHANGED
@@ -1,13 +1,11 @@
|
|
1 |
-
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: mit
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
+
---
|
2 |
+
title: ControlNet_on_human_surface_normals
|
3 |
+
emoji: ⚡
|
4 |
+
colorFrom: purple
|
5 |
+
colorTo: pink
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 4.26.0
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
license: mit
|
11 |
+
---
|
|
|
|
app.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline, AutoencoderKL, EulerAncestralDiscreteScheduler
|
3 |
+
from diffusers.utils import load_image
|
4 |
+
from PIL import Image
|
5 |
+
import torch
|
6 |
+
import numpy as np
|
7 |
+
import cv2
|
8 |
+
import gradio as gr
|
9 |
+
from torchvision import transforms
|
10 |
+
import fire
|
11 |
+
import os
|
12 |
+
|
13 |
+
controlnet = ControlNetModel.from_pretrained(
|
14 |
+
"geyongtao/HumanWild",
|
15 |
+
torch_dtype=torch.float16
|
16 |
+
).to('cuda')
|
17 |
+
|
18 |
+
vae = AutoencoderKL.from_pretrained(
|
19 |
+
"madebyollin/sdxl-vae-fp16-fix",
|
20 |
+
torch_dtype=torch.float16).to("cuda")
|
21 |
+
|
22 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
23 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
24 |
+
controlnet=controlnet,
|
25 |
+
vae=vae,
|
26 |
+
torch_dtype=torch.float16,
|
27 |
+
use_safetensors=True,
|
28 |
+
low_cpu_mem_usage=True,
|
29 |
+
offload_state_dict=True,
|
30 |
+
).to('cuda')
|
31 |
+
pipe.controlnet.to(memory_format=torch.channels_last)
|
32 |
+
|
33 |
+
# pipe.enable_xformers_memory_efficient_attention()
|
34 |
+
pipe.force_zeros_for_empty_prompt = False
|
35 |
+
|
36 |
+
|
37 |
+
def resize_image(image):
|
38 |
+
image = image.convert('RGB')
|
39 |
+
current_size = image.size
|
40 |
+
if current_size[0] > current_size[1]:
|
41 |
+
center_cropped_image = transforms.functional.center_crop(image, (current_size[1], current_size[1]))
|
42 |
+
else:
|
43 |
+
center_cropped_image = transforms.functional.center_crop(image, (current_size[0], current_size[0]))
|
44 |
+
resized_image = transforms.functional.resize(center_cropped_image, (1024, 1024))
|
45 |
+
return resized_image
|
46 |
+
|
47 |
+
def get_normal_map(image):
|
48 |
+
image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
|
49 |
+
with torch.no_grad(), torch.autocast("cuda"):
|
50 |
+
depth_map = depth_estimator(image).predicted_depth
|
51 |
+
image = transforms.functional.center_crop(image, min(image.shape[-2:]))
|
52 |
+
depth_map = torch.nn.functional.interpolate(
|
53 |
+
depth_map.unsqueeze(1),
|
54 |
+
size=(1024, 1024),
|
55 |
+
mode="bicubic",
|
56 |
+
align_corners=False,
|
57 |
+
)
|
58 |
+
depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
59 |
+
depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
60 |
+
depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
61 |
+
image = torch.cat([depth_map] * 3, dim=1)
|
62 |
+
image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
|
63 |
+
image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
|
64 |
+
return image
|
65 |
+
|
66 |
+
|
67 |
+
@spaces.GPU
|
68 |
+
def generate_(prompt, negative_prompt, normal_image, num_steps, controlnet_conditioning_scale, seed):
|
69 |
+
generator = torch.Generator("cuda").manual_seed(seed)
|
70 |
+
images = pipe(
|
71 |
+
prompt,
|
72 |
+
negative_prompt=negative_prompt,
|
73 |
+
image=normal_image,
|
74 |
+
num_inference_steps=num_steps,
|
75 |
+
controlnet_conditioning_scale=float(controlnet_conditioning_scale),
|
76 |
+
num_images_per_prompt=2,
|
77 |
+
generator=generator,
|
78 |
+
).images
|
79 |
+
return images
|
80 |
+
|
81 |
+
@spaces.GPU
|
82 |
+
def process(normal_image, prompt, negative_prompt, num_steps, controlnet_conditioning_scale, seed):
|
83 |
+
# resize input_image to 1024x1024
|
84 |
+
normal_image = resize_image(normal_image)
|
85 |
+
# depth_image = get_depth_map(input_image)
|
86 |
+
images = generate_(prompt, negative_prompt, normal_image, num_steps, controlnet_conditioning_scale, seed)
|
87 |
+
|
88 |
+
return [images[0], images[1]]
|
89 |
+
|
90 |
+
|
91 |
+
def run_demo():
|
92 |
+
|
93 |
+
_TITLE = '''3D Human Reconstruction in the Wild with Synthetic Data Using Generative Models'''
|
94 |
+
|
95 |
+
block = gr.Blocks().queue()
|
96 |
+
|
97 |
+
with block:
|
98 |
+
gr.Markdown("# 3D Human Reconstruction in the Wild with Synthetic Data Using Generative Models ")
|
99 |
+
gr.HTML('''
|
100 |
+
<p style="margin-bottom: 10px; font-size: 94%">
|
101 |
+
This is a demo for Surface Normal ControlNet that using
|
102 |
+
<a href="https://huggingface.co/geyongtao/HumanWild" target="_blank"> HumanWild model</a> pretrained weight.
|
103 |
+
<a style="display:inline-block; margin-left: .5em" href='https://github.com/YongtaoGe/WildHuman/'><img src='https://img.shields.io/github/stars/YongtaoGe/WildHuman?style=social' /></a>
|
104 |
+
</p>
|
105 |
+
''')
|
106 |
+
with gr.Row():
|
107 |
+
with gr.Column():
|
108 |
+
input_image = gr.Image(sources=None, type="pil") # None for upload, ctrl+v and webcam
|
109 |
+
|
110 |
+
example_folder = os.path.join(os.path.dirname(__file__), "./assets")
|
111 |
+
example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)]
|
112 |
+
gr.Examples(
|
113 |
+
examples=example_fns,
|
114 |
+
inputs=[input_image],
|
115 |
+
cache_examples=False,
|
116 |
+
label='Examples (click one of the images below to start)',
|
117 |
+
examples_per_page=30
|
118 |
+
)
|
119 |
+
|
120 |
+
prompt = gr.Textbox(label="Prompt", value="a person, in the wild")
|
121 |
+
negative_prompt = gr.Textbox(visible=False, label="Negative prompt", value="Logo,Watermark,Text,Ugly,Morbid,Extra fingers,Poorly drawn hands,Mutation,Blurry,Extra limbs,Gross proportions,Missing arms,Mutated hands,Long neck,Duplicate,Mutilated,Mutilated hands,Poorly drawn face,Deformed,Bad anatomy,Cloned face,Malformed limbs,Missing legs,Too many fingers")
|
122 |
+
num_steps = gr.Slider(label="Number of steps", minimum=25, maximum=50, value=30, step=1)
|
123 |
+
controlnet_conditioning_scale = gr.Slider(label="ControlNet conditioning scale", minimum=0.1, maximum=1.0, value=0.95, step=0.05)
|
124 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, randomize=True,)
|
125 |
+
run_button = gr.Button(value="Run")
|
126 |
+
|
127 |
+
with gr.Column():
|
128 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery", columns=[2], height='auto')
|
129 |
+
ips = [input_image, prompt, negative_prompt, num_steps, controlnet_conditioning_scale, seed]
|
130 |
+
|
131 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
132 |
+
|
133 |
+
block.launch(debug = True)
|
134 |
+
|
135 |
+
if __name__ == '__main__':
|
136 |
+
fire.Fire(run_demo)
|
app_mast3r.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
import spaces
|
4 |
+
import torch
|
5 |
+
from gradio_rerun import Rerun
|
6 |
+
import rerun as rr
|
7 |
+
import rerun.blueprint as rrb
|
8 |
+
from pathlib import Path
|
9 |
+
import uuid
|
10 |
+
|
11 |
+
from mini_dust3r.api import OptimizedResult, inferece_dust3r, log_optimized_result
|
12 |
+
from mini_dust3r.model import AsymmetricCroCo3DStereo
|
13 |
+
from mini_dust3r.utils.misc import (
|
14 |
+
fill_default_args,
|
15 |
+
freeze_all_params,
|
16 |
+
is_symmetrized,
|
17 |
+
interleave,
|
18 |
+
transpose_to_landscape,
|
19 |
+
)
|
20 |
+
|
21 |
+
import os
|
22 |
+
from mini_dust3r.model import load_model
|
23 |
+
from catmlp_dpt_head import Cat_MLP_LocalFeatures_DPT_Pts3d, postprocess
|
24 |
+
|
25 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "CPU"
|
26 |
+
|
27 |
+
# model = AsymmetricCroCo3DStereo.from_pretrained(
|
28 |
+
# "naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt"
|
29 |
+
# ).to(DEVICE)
|
30 |
+
|
31 |
+
|
32 |
+
from mini_dust3r.heads.linear_head import LinearPts3d
|
33 |
+
from mini_dust3r.heads.dpt_head import create_dpt_head
|
34 |
+
|
35 |
+
def head_factory(head_type, output_mode, net, has_conf=False):
|
36 |
+
"""" build a prediction head for the decoder
|
37 |
+
"""
|
38 |
+
if head_type == 'linear' and output_mode == 'pts3d':
|
39 |
+
return LinearPts3d(net, has_conf)
|
40 |
+
elif head_type == 'dpt' and output_mode == 'pts3d':
|
41 |
+
return create_dpt_head(net, has_conf=has_conf)
|
42 |
+
if head_type == 'catmlp+dpt' and output_mode.startswith('pts3d+desc'):
|
43 |
+
local_feat_dim = int(output_mode[10:])
|
44 |
+
assert net.dec_depth > 9
|
45 |
+
l2 = net.dec_depth
|
46 |
+
feature_dim = 256
|
47 |
+
last_dim = feature_dim // 2
|
48 |
+
out_nchan = 3
|
49 |
+
ed = net.enc_embed_dim
|
50 |
+
dd = net.dec_embed_dim
|
51 |
+
return Cat_MLP_LocalFeatures_DPT_Pts3d(net, local_feat_dim=local_feat_dim, has_conf=has_conf,
|
52 |
+
num_channels=out_nchan + has_conf,
|
53 |
+
feature_dim=feature_dim,
|
54 |
+
last_dim=last_dim,
|
55 |
+
hooks_idx=[0, l2 * 2 // 4, l2 * 3 // 4, l2],
|
56 |
+
dim_tokens=[ed, dd, dd, dd],
|
57 |
+
postprocess=postprocess,
|
58 |
+
depth_mode=net.depth_mode,
|
59 |
+
conf_mode=net.conf_mode,
|
60 |
+
head_type='regression')
|
61 |
+
else:
|
62 |
+
raise NotImplementedError(f"unexpected {head_type=} and {output_mode=}")
|
63 |
+
|
64 |
+
|
65 |
+
class AsymmetricMASt3R(AsymmetricCroCo3DStereo):
|
66 |
+
def __init__(self, desc_mode=('norm'), two_confs=False, desc_conf_mode=None, **kwargs):
|
67 |
+
self.desc_mode = desc_mode
|
68 |
+
self.two_confs = two_confs
|
69 |
+
self.desc_conf_mode = desc_conf_mode
|
70 |
+
super().__init__(**kwargs)
|
71 |
+
|
72 |
+
@classmethod
|
73 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kw):
|
74 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
75 |
+
return load_model(pretrained_model_name_or_path, device='cpu')
|
76 |
+
else:
|
77 |
+
return super(AsymmetricMASt3R, cls).from_pretrained(pretrained_model_name_or_path, **kw)
|
78 |
+
|
79 |
+
def set_downstream_head(self, output_mode, head_type, landscape_only, depth_mode, conf_mode, patch_size, img_size, **kw):
|
80 |
+
assert img_size[0] % patch_size == 0 and img_size[
|
81 |
+
1] % patch_size == 0, f'{img_size=} must be multiple of {patch_size=}'
|
82 |
+
self.output_mode = output_mode
|
83 |
+
self.head_type = head_type
|
84 |
+
self.depth_mode = depth_mode
|
85 |
+
self.conf_mode = conf_mode
|
86 |
+
if self.desc_conf_mode is None:
|
87 |
+
self.desc_conf_mode = conf_mode
|
88 |
+
# allocate heads
|
89 |
+
self.downstream_head1 = head_factory(head_type, output_mode, self, has_conf=bool(conf_mode))
|
90 |
+
self.downstream_head2 = head_factory(head_type, output_mode, self, has_conf=bool(conf_mode))
|
91 |
+
# magic wrapper
|
92 |
+
self.head1 = transpose_to_landscape(self.downstream_head1, activate=landscape_only)
|
93 |
+
self.head2 = transpose_to_landscape(self.downstream_head2, activate=landscape_only)
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
model = AsymmetricMASt3R.from_pretrained(
|
98 |
+
"naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric").to(DEVICE)
|
99 |
+
|
100 |
+
|
101 |
+
def create_blueprint(image_name_list: list[str], log_path: Path) -> rrb.Blueprint:
|
102 |
+
# dont show 2d views if there are more than 4 images as to not clutter the view
|
103 |
+
if len(image_name_list) > 4:
|
104 |
+
blueprint = rrb.Blueprint(
|
105 |
+
rrb.Horizontal(
|
106 |
+
rrb.Spatial3DView(origin=f"{log_path}"),
|
107 |
+
),
|
108 |
+
collapse_panels=True,
|
109 |
+
)
|
110 |
+
else:
|
111 |
+
blueprint = rrb.Blueprint(
|
112 |
+
rrb.Horizontal(
|
113 |
+
contents=[
|
114 |
+
rrb.Spatial3DView(origin=f"{log_path}"),
|
115 |
+
rrb.Vertical(
|
116 |
+
contents=[
|
117 |
+
rrb.Spatial2DView(
|
118 |
+
origin=f"{log_path}/camera_{i}/pinhole/",
|
119 |
+
contents=[
|
120 |
+
"+ $origin/**",
|
121 |
+
],
|
122 |
+
)
|
123 |
+
for i in range(len(image_name_list))
|
124 |
+
]
|
125 |
+
),
|
126 |
+
],
|
127 |
+
column_shares=[3, 1],
|
128 |
+
),
|
129 |
+
collapse_panels=True,
|
130 |
+
)
|
131 |
+
return blueprint
|
132 |
+
|
133 |
+
|
134 |
+
@spaces.GPU
|
135 |
+
def predict(image_name_list: list[str] | str):
|
136 |
+
# check if is list or string and if not raise error
|
137 |
+
if not isinstance(image_name_list, list) and not isinstance(image_name_list, str):
|
138 |
+
raise gr.Error(
|
139 |
+
f"Input must be a list of strings or a string, got: {type(image_name_list)}"
|
140 |
+
)
|
141 |
+
uuid_str = str(uuid.uuid4())
|
142 |
+
filename = Path(f"/tmp/gradio/{uuid_str}.rrd")
|
143 |
+
rr.init(f"{uuid_str}")
|
144 |
+
log_path = Path("world")
|
145 |
+
|
146 |
+
if isinstance(image_name_list, str):
|
147 |
+
image_name_list = [image_name_list]
|
148 |
+
|
149 |
+
optimized_results: OptimizedResult = inferece_dust3r(
|
150 |
+
image_dir_or_list=image_name_list,
|
151 |
+
model=model,
|
152 |
+
device=DEVICE,
|
153 |
+
batch_size=1,
|
154 |
+
)
|
155 |
+
|
156 |
+
blueprint: rrb.Blueprint = create_blueprint(image_name_list, log_path)
|
157 |
+
rr.send_blueprint(blueprint)
|
158 |
+
|
159 |
+
rr.set_time_sequence("sequence", 0)
|
160 |
+
log_optimized_result(optimized_results, log_path)
|
161 |
+
rr.save(filename.as_posix())
|
162 |
+
return filename.as_posix()
|
163 |
+
|
164 |
+
|
165 |
+
with gr.Blocks(
|
166 |
+
css=""".gradio-container {margin: 0 !important; min-width: 100%};""",
|
167 |
+
title="Mini-DUSt3R Demo",
|
168 |
+
) as demo:
|
169 |
+
# scene state is save so that you can change conf_thr, cam_size... without rerunning the inference
|
170 |
+
gr.HTML('<h2 style="text-align: center;">Mini-DUSt3R Demo</h2>')
|
171 |
+
gr.HTML(
|
172 |
+
'<p style="text-align: center;">Unofficial DUSt3R demo using the mini-dust3r pip package</p>'
|
173 |
+
)
|
174 |
+
gr.HTML(
|
175 |
+
'<p style="text-align: center;">More info <a href="https://github.com/pablovela5620/mini-dust3r">here</a></p>'
|
176 |
+
)
|
177 |
+
with gr.Tab(label="Single Image"):
|
178 |
+
with gr.Column():
|
179 |
+
single_image = gr.Image(type="filepath", height=300)
|
180 |
+
run_btn_single = gr.Button("Run")
|
181 |
+
rerun_viewer_single = Rerun(height=900)
|
182 |
+
run_btn_single.click(
|
183 |
+
fn=predict, inputs=[single_image], outputs=[rerun_viewer_single]
|
184 |
+
)
|
185 |
+
|
186 |
+
example_single_dir = Path("examples/single_image")
|
187 |
+
example_single_files = sorted(example_single_dir.glob("*.png"))
|
188 |
+
|
189 |
+
examples_single = gr.Examples(
|
190 |
+
examples=example_single_files,
|
191 |
+
inputs=[single_image],
|
192 |
+
outputs=[rerun_viewer_single],
|
193 |
+
fn=predict,
|
194 |
+
cache_examples="lazy",
|
195 |
+
)
|
196 |
+
with gr.Tab(label="Multi Image"):
|
197 |
+
with gr.Column():
|
198 |
+
multi_files = gr.File(file_count="multiple")
|
199 |
+
run_btn_multi = gr.Button("Run")
|
200 |
+
rerun_viewer_multi = Rerun(height=900)
|
201 |
+
run_btn_multi.click(
|
202 |
+
fn=predict, inputs=[multi_files], outputs=[rerun_viewer_multi]
|
203 |
+
)
|
204 |
+
|
205 |
+
|
206 |
+
demo.launch()
|
catmlp_dpt_head.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
3 |
+
#
|
4 |
+
# --------------------------------------------------------
|
5 |
+
# MASt3R heads
|
6 |
+
# --------------------------------------------------------
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
|
10 |
+
from mini_dust3r.heads.postprocess import reg_dense_depth, reg_dense_conf # noqa
|
11 |
+
from mini_dust3r.heads.dpt_head import PixelwiseTaskWithDPT # noqa
|
12 |
+
from mini_dust3r.croco.blocks import Mlp # noqa
|
13 |
+
|
14 |
+
def reg_desc(desc, mode):
|
15 |
+
if 'norm' in mode:
|
16 |
+
desc = desc / desc.norm(dim=-1, keepdim=True)
|
17 |
+
else:
|
18 |
+
raise ValueError(f"Unknown desc mode {mode}")
|
19 |
+
return desc
|
20 |
+
|
21 |
+
|
22 |
+
def postprocess(out, depth_mode, conf_mode, desc_dim=None, desc_mode='norm', two_confs=False, desc_conf_mode=None):
|
23 |
+
if desc_conf_mode is None:
|
24 |
+
desc_conf_mode = conf_mode
|
25 |
+
fmap = out.permute(0, 2, 3, 1) # B,H,W,D
|
26 |
+
res = dict(pts3d=reg_dense_depth(fmap[..., 0:3], mode=depth_mode))
|
27 |
+
if conf_mode is not None:
|
28 |
+
res['conf'] = reg_dense_conf(fmap[..., 3], mode=conf_mode)
|
29 |
+
if desc_dim is not None:
|
30 |
+
start = 3 + int(conf_mode is not None)
|
31 |
+
res['desc'] = reg_desc(fmap[..., start:start + desc_dim], mode=desc_mode)
|
32 |
+
if two_confs:
|
33 |
+
res['desc_conf'] = reg_dense_conf(fmap[..., start + desc_dim], mode=desc_conf_mode)
|
34 |
+
else:
|
35 |
+
res['desc_conf'] = res['conf'].clone()
|
36 |
+
return res
|
37 |
+
|
38 |
+
|
39 |
+
class Cat_MLP_LocalFeatures_DPT_Pts3d(PixelwiseTaskWithDPT):
|
40 |
+
""" Mixture between MLP and DPT head that outputs 3d points and local features (with MLP).
|
41 |
+
The input for both heads is a concatenation of Encoder and Decoder outputs
|
42 |
+
"""
|
43 |
+
|
44 |
+
def __init__(self, net, has_conf=False, local_feat_dim=16, hidden_dim_factor=4., hooks_idx=None, dim_tokens=None,
|
45 |
+
num_channels=1, postprocess=None, feature_dim=256, last_dim=32, depth_mode=None, conf_mode=None, head_type="regression", **kwargs):
|
46 |
+
super().__init__(num_channels=num_channels, feature_dim=feature_dim, last_dim=last_dim, hooks_idx=hooks_idx,
|
47 |
+
dim_tokens=dim_tokens, depth_mode=depth_mode, postprocess=postprocess, conf_mode=conf_mode, head_type=head_type)
|
48 |
+
self.local_feat_dim = local_feat_dim
|
49 |
+
|
50 |
+
patch_size = net.patch_embed.patch_size
|
51 |
+
if isinstance(patch_size, tuple):
|
52 |
+
assert len(patch_size) == 2 and isinstance(patch_size[0], int) and isinstance(
|
53 |
+
patch_size[1], int), "What is your patchsize format? Expected a single int or a tuple of two ints."
|
54 |
+
assert patch_size[0] == patch_size[1], "Error, non square patches not managed"
|
55 |
+
patch_size = patch_size[0]
|
56 |
+
self.patch_size = patch_size
|
57 |
+
|
58 |
+
self.desc_mode = net.desc_mode
|
59 |
+
self.has_conf = has_conf
|
60 |
+
self.two_confs = net.two_confs # independent confs for 3D regr and descs
|
61 |
+
self.desc_conf_mode = net.desc_conf_mode
|
62 |
+
idim = net.enc_embed_dim + net.dec_embed_dim
|
63 |
+
|
64 |
+
self.head_local_features = Mlp(in_features=idim,
|
65 |
+
hidden_features=int(hidden_dim_factor * idim),
|
66 |
+
out_features=(self.local_feat_dim + self.two_confs) * self.patch_size**2)
|
67 |
+
|
68 |
+
def forward(self, decout, img_shape):
|
69 |
+
# pass through the heads
|
70 |
+
pts3d = self.dpt(decout, image_size=(img_shape[0], img_shape[1]))
|
71 |
+
|
72 |
+
# recover encoder and decoder outputs
|
73 |
+
enc_output, dec_output = decout[0], decout[-1]
|
74 |
+
cat_output = torch.cat([enc_output, dec_output], dim=-1) # concatenate
|
75 |
+
H, W = img_shape
|
76 |
+
B, S, D = cat_output.shape
|
77 |
+
|
78 |
+
# extract local_features
|
79 |
+
local_features = self.head_local_features(cat_output) # B,S,D
|
80 |
+
local_features = local_features.transpose(-1, -2).view(B, -1, H // self.patch_size, W // self.patch_size)
|
81 |
+
local_features = F.pixel_shuffle(local_features, self.patch_size) # B,d,H,W
|
82 |
+
|
83 |
+
# post process 3D pts, descriptors and confidences
|
84 |
+
out = torch.cat([pts3d, local_features], dim=1)
|
85 |
+
if self.postprocess:
|
86 |
+
out = self.postprocess(out,
|
87 |
+
depth_mode=self.depth_mode,
|
88 |
+
conf_mode=self.conf_mode,
|
89 |
+
desc_dim=self.local_feat_dim,
|
90 |
+
desc_mode=self.desc_mode,
|
91 |
+
two_confs=self.two_confs,
|
92 |
+
desc_conf_mode=self.desc_conf_mode)
|
93 |
+
return out
|
94 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#mini-dust3r==0.1.1
|
2 |
+
#pillow-heif
|
3 |
+
#rerun-sdk==0.15.1
|
4 |
+
|
5 |
+
accelerate
|
6 |
+
spaces
|
7 |
+
transformers
|
8 |
+
safetensors
|
9 |
+
opencv-python
|
10 |
+
diffusers
|
11 |
+
gradio
|
12 |
+
torch
|
13 |
+
torchvision
|
14 |
+
xformers
|
15 |
+
fire
|