Spaces:
Runtime error
Runtime error
Upload model/crm/model.py with huggingface_hub
Browse files- model/crm/model.py +213 -217
model/crm/model.py
CHANGED
@@ -1,217 +1,213 @@
|
|
1 |
-
import torch.nn as nn
|
2 |
-
import torch
|
3 |
-
import torch.nn.functional as F
|
4 |
-
|
5 |
-
import numpy as np
|
6 |
-
|
7 |
-
|
8 |
-
from pathlib import Path
|
9 |
-
import cv2
|
10 |
-
import trimesh
|
11 |
-
import nvdiffrast.torch as dr
|
12 |
-
|
13 |
-
from model.archs.decoders.shape_texture_net import TetTexNet
|
14 |
-
from model.archs.unet import UNetPP
|
15 |
-
from util.renderer import Renderer
|
16 |
-
from model.archs.mlp_head import SdfMlp, RgbMlp
|
17 |
-
import xatlas
|
18 |
-
|
19 |
-
|
20 |
-
class Dummy:
|
21 |
-
pass
|
22 |
-
|
23 |
-
class CRM(nn.Module):
|
24 |
-
def __init__(self, specs):
|
25 |
-
super(CRM, self).__init__()
|
26 |
-
|
27 |
-
self.specs = specs
|
28 |
-
# configs
|
29 |
-
input_specs = specs["Input"]
|
30 |
-
self.input = Dummy()
|
31 |
-
self.input.scale = input_specs['scale']
|
32 |
-
self.input.resolution = input_specs['resolution']
|
33 |
-
self.tet_grid_size = input_specs['tet_grid_size']
|
34 |
-
self.camera_angle_num = input_specs['camera_angle_num']
|
35 |
-
|
36 |
-
self.arch = Dummy()
|
37 |
-
self.arch.fea_concat = specs["ArchSpecs"]["fea_concat"]
|
38 |
-
self.arch.mlp_bias = specs["ArchSpecs"]["mlp_bias"]
|
39 |
-
|
40 |
-
self.dec = Dummy()
|
41 |
-
self.dec.c_dim = specs["DecoderSpecs"]["c_dim"]
|
42 |
-
self.dec.plane_resolution = specs["DecoderSpecs"]["plane_resolution"]
|
43 |
-
|
44 |
-
self.geo_type = specs["Train"].get("geo_type", "flex") # "dmtet" or "flex"
|
45 |
-
|
46 |
-
self.unet2 = UNetPP(in_channels=self.dec.c_dim)
|
47 |
-
|
48 |
-
mlp_chnl_s = 3 if self.arch.fea_concat else 1 # 3 for queried triplane feature concatenation
|
49 |
-
self.decoder = TetTexNet(plane_reso=self.dec.plane_resolution, fea_concat=self.arch.fea_concat)
|
50 |
-
|
51 |
-
if self.geo_type == "flex":
|
52 |
-
self.weightMlp = nn.Sequential(
|
53 |
-
nn.Linear(mlp_chnl_s * 32 * 8, 512),
|
54 |
-
nn.SiLU(),
|
55 |
-
nn.Linear(512, 21))
|
56 |
-
|
57 |
-
self.sdfMlp = SdfMlp(mlp_chnl_s * 32, 512, bias=self.arch.mlp_bias)
|
58 |
-
self.rgbMlp = RgbMlp(mlp_chnl_s * 32, 512, bias=self.arch.mlp_bias)
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
self.spob = True if specs['Pretrain']['mode'] is None else False # whether to add sphere
|
64 |
-
self.radius = specs['Pretrain']['radius'] # used when spob
|
65 |
-
|
66 |
-
self.denoising = True
|
67 |
-
from diffusers import DDIMScheduler
|
68 |
-
self.scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-2-1-base", subfolder="scheduler")
|
69 |
-
|
70 |
-
def decode(self, data, triplane_feature2):
|
71 |
-
if self.geo_type == "flex":
|
72 |
-
tet_verts = self.renderer.flexicubes.verts.unsqueeze(0)
|
73 |
-
tet_indices = self.renderer.flexicubes.indices
|
74 |
-
|
75 |
-
dec_verts = self.decoder(triplane_feature2, tet_verts)
|
76 |
-
out = self.sdfMlp(dec_verts)
|
77 |
-
|
78 |
-
weight = None
|
79 |
-
if self.geo_type == "flex":
|
80 |
-
grid_feat = torch.index_select(input=dec_verts, index=self.renderer.flexicubes.indices.reshape(-1),dim=1)
|
81 |
-
grid_feat = grid_feat.reshape(dec_verts.shape[0], self.renderer.flexicubes.indices.shape[0], self.renderer.flexicubes.indices.shape[1] * dec_verts.shape[-1])
|
82 |
-
weight = self.weightMlp(grid_feat)
|
83 |
-
weight = weight * 0.1
|
84 |
-
|
85 |
-
pred_sdf, deformation = out[..., 0], out[..., 1:]
|
86 |
-
if self.spob:
|
87 |
-
pred_sdf = pred_sdf + self.radius - torch.sqrt((tet_verts**2).sum(-1))
|
88 |
-
|
89 |
-
_, verts, faces = self.renderer(data, pred_sdf, deformation, tet_verts, tet_indices, weight= weight)
|
90 |
-
return verts[0].unsqueeze(0), faces[0].int()
|
91 |
-
|
92 |
-
def export_mesh(self, data, out_dir, tri_fea_2 = None):
|
93 |
-
verts = data['verts']
|
94 |
-
faces = data['faces']
|
95 |
-
|
96 |
-
dec_verts = self.decoder(tri_fea_2, verts.unsqueeze(0))
|
97 |
-
colors = self.rgbMlp(dec_verts).squeeze().detach().cpu().numpy()
|
98 |
-
# Expect predicted colors value range from [-1, 1]
|
99 |
-
colors = (colors * 0.5 + 0.5).clip(0, 1)
|
100 |
-
|
101 |
-
verts = verts
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
#
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
#
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
fid
|
179 |
-
fid.write('
|
180 |
-
fid.write('
|
181 |
-
fid.write('
|
182 |
-
|
183 |
-
fid.
|
184 |
-
|
185 |
-
fid
|
186 |
-
fid
|
187 |
-
fid.
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
for pidx, p in enumerate(
|
194 |
-
pp = p
|
195 |
-
fid.write('
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
img = img.clip(0, 255).astype(np.uint8)
|
215 |
-
|
216 |
-
cv2.imwrite(f'{out_dir}.png', img[..., [2, 1, 0]])
|
217 |
-
# cv2.imwrite(f'{out_dir}/{ind}.png', img[..., [2, 1, 0]])
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
|
8 |
+
from pathlib import Path
|
9 |
+
import cv2
|
10 |
+
import trimesh
|
11 |
+
import nvdiffrast.torch as dr
|
12 |
+
|
13 |
+
from model.archs.decoders.shape_texture_net import TetTexNet
|
14 |
+
from model.archs.unet import UNetPP
|
15 |
+
from util.renderer import Renderer
|
16 |
+
from model.archs.mlp_head import SdfMlp, RgbMlp
|
17 |
+
import xatlas
|
18 |
+
|
19 |
+
|
20 |
+
class Dummy:
|
21 |
+
pass
|
22 |
+
|
23 |
+
class CRM(nn.Module):
|
24 |
+
def __init__(self, specs):
|
25 |
+
super(CRM, self).__init__()
|
26 |
+
|
27 |
+
self.specs = specs
|
28 |
+
# configs
|
29 |
+
input_specs = specs["Input"]
|
30 |
+
self.input = Dummy()
|
31 |
+
self.input.scale = input_specs['scale']
|
32 |
+
self.input.resolution = input_specs['resolution']
|
33 |
+
self.tet_grid_size = input_specs['tet_grid_size']
|
34 |
+
self.camera_angle_num = input_specs['camera_angle_num']
|
35 |
+
|
36 |
+
self.arch = Dummy()
|
37 |
+
self.arch.fea_concat = specs["ArchSpecs"]["fea_concat"]
|
38 |
+
self.arch.mlp_bias = specs["ArchSpecs"]["mlp_bias"]
|
39 |
+
|
40 |
+
self.dec = Dummy()
|
41 |
+
self.dec.c_dim = specs["DecoderSpecs"]["c_dim"]
|
42 |
+
self.dec.plane_resolution = specs["DecoderSpecs"]["plane_resolution"]
|
43 |
+
|
44 |
+
self.geo_type = specs["Train"].get("geo_type", "flex") # "dmtet" or "flex"
|
45 |
+
|
46 |
+
self.unet2 = UNetPP(in_channels=self.dec.c_dim)
|
47 |
+
|
48 |
+
mlp_chnl_s = 3 if self.arch.fea_concat else 1 # 3 for queried triplane feature concatenation
|
49 |
+
self.decoder = TetTexNet(plane_reso=self.dec.plane_resolution, fea_concat=self.arch.fea_concat)
|
50 |
+
|
51 |
+
if self.geo_type == "flex":
|
52 |
+
self.weightMlp = nn.Sequential(
|
53 |
+
nn.Linear(mlp_chnl_s * 32 * 8, 512),
|
54 |
+
nn.SiLU(),
|
55 |
+
nn.Linear(512, 21))
|
56 |
+
|
57 |
+
self.sdfMlp = SdfMlp(mlp_chnl_s * 32, 512, bias=self.arch.mlp_bias)
|
58 |
+
self.rgbMlp = RgbMlp(mlp_chnl_s * 32, 512, bias=self.arch.mlp_bias)
|
59 |
+
self.renderer = Renderer(tet_grid_size=self.tet_grid_size, camera_angle_num=self.camera_angle_num,
|
60 |
+
scale=self.input.scale, geo_type = self.geo_type)
|
61 |
+
|
62 |
+
|
63 |
+
self.spob = True if specs['Pretrain']['mode'] is None else False # whether to add sphere
|
64 |
+
self.radius = specs['Pretrain']['radius'] # used when spob
|
65 |
+
|
66 |
+
self.denoising = True
|
67 |
+
from diffusers import DDIMScheduler
|
68 |
+
self.scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-2-1-base", subfolder="scheduler")
|
69 |
+
|
70 |
+
def decode(self, data, triplane_feature2):
|
71 |
+
if self.geo_type == "flex":
|
72 |
+
tet_verts = self.renderer.flexicubes.verts.unsqueeze(0)
|
73 |
+
tet_indices = self.renderer.flexicubes.indices
|
74 |
+
|
75 |
+
dec_verts = self.decoder(triplane_feature2, tet_verts)
|
76 |
+
out = self.sdfMlp(dec_verts)
|
77 |
+
|
78 |
+
weight = None
|
79 |
+
if self.geo_type == "flex":
|
80 |
+
grid_feat = torch.index_select(input=dec_verts, index=self.renderer.flexicubes.indices.reshape(-1),dim=1)
|
81 |
+
grid_feat = grid_feat.reshape(dec_verts.shape[0], self.renderer.flexicubes.indices.shape[0], self.renderer.flexicubes.indices.shape[1] * dec_verts.shape[-1])
|
82 |
+
weight = self.weightMlp(grid_feat)
|
83 |
+
weight = weight * 0.1
|
84 |
+
|
85 |
+
pred_sdf, deformation = out[..., 0], out[..., 1:]
|
86 |
+
if self.spob:
|
87 |
+
pred_sdf = pred_sdf + self.radius - torch.sqrt((tet_verts**2).sum(-1))
|
88 |
+
|
89 |
+
_, verts, faces = self.renderer(data, pred_sdf, deformation, tet_verts, tet_indices, weight= weight)
|
90 |
+
return verts[0].unsqueeze(0), faces[0].int()
|
91 |
+
|
92 |
+
def export_mesh(self, data, out_dir, ind, device=None, tri_fea_2 = None):
|
93 |
+
verts = data['verts']
|
94 |
+
faces = data['faces']
|
95 |
+
|
96 |
+
dec_verts = self.decoder(tri_fea_2, verts.unsqueeze(0))
|
97 |
+
colors = self.rgbMlp(dec_verts).squeeze().detach().cpu().numpy()
|
98 |
+
# Expect predicted colors value range from [-1, 1]
|
99 |
+
colors = (colors * 0.5 + 0.5).clip(0, 1)
|
100 |
+
|
101 |
+
verts = verts.squeeze().cpu().numpy()
|
102 |
+
faces = faces[..., [2, 1, 0]].squeeze().cpu().numpy()
|
103 |
+
|
104 |
+
# export the final mesh
|
105 |
+
with torch.no_grad():
|
106 |
+
mesh = trimesh.Trimesh(verts, faces, vertex_colors=colors, process=False) # important, process=True leads to seg fault...
|
107 |
+
mesh.export(out_dir / f'{ind}.obj')
|
108 |
+
|
109 |
+
def export_mesh_wt_uv(self, ctx, data, out_dir, ind, device, res, tri_fea_2=None):
|
110 |
+
|
111 |
+
mesh_v = data['verts'].squeeze().cpu().numpy()
|
112 |
+
mesh_pos_idx = data['faces'].squeeze().cpu().numpy()
|
113 |
+
|
114 |
+
def interpolate(attr, rast, attr_idx, rast_db=None):
|
115 |
+
return dr.interpolate(attr.contiguous(), rast, attr_idx, rast_db=rast_db,
|
116 |
+
diff_attrs=None if rast_db is None else 'all')
|
117 |
+
|
118 |
+
vmapping, indices, uvs = xatlas.parametrize(mesh_v, mesh_pos_idx)
|
119 |
+
|
120 |
+
mesh_v = torch.tensor(mesh_v, dtype=torch.float32, device=device)
|
121 |
+
mesh_pos_idx = torch.tensor(mesh_pos_idx, dtype=torch.int64, device=device)
|
122 |
+
|
123 |
+
# Convert to tensors
|
124 |
+
indices_int64 = indices.astype(np.uint64, casting='same_kind').view(np.int64)
|
125 |
+
|
126 |
+
uvs = torch.tensor(uvs, dtype=torch.float32, device=mesh_v.device)
|
127 |
+
mesh_tex_idx = torch.tensor(indices_int64, dtype=torch.int64, device=mesh_v.device)
|
128 |
+
# mesh_v_tex. ture
|
129 |
+
uv_clip = uvs[None, ...] * 2.0 - 1.0
|
130 |
+
|
131 |
+
# pad to four component coordinate
|
132 |
+
uv_clip4 = torch.cat((uv_clip, torch.zeros_like(uv_clip[..., 0:1]), torch.ones_like(uv_clip[..., 0:1])), dim=-1)
|
133 |
+
|
134 |
+
# rasterize
|
135 |
+
rast, _ = dr.rasterize(ctx, uv_clip4, mesh_tex_idx.int(), res)
|
136 |
+
|
137 |
+
# Interpolate world space position
|
138 |
+
gb_pos, _ = interpolate(mesh_v[None, ...], rast, mesh_pos_idx.int())
|
139 |
+
mask = rast[..., 3:4] > 0
|
140 |
+
|
141 |
+
# return uvs, mesh_tex_idx, gb_pos, mask
|
142 |
+
gb_pos_unsqz = gb_pos.view(-1, 3)
|
143 |
+
mask_unsqz = mask.view(-1)
|
144 |
+
tex_unsqz = torch.zeros_like(gb_pos_unsqz) + 1
|
145 |
+
|
146 |
+
gb_mask_pos = gb_pos_unsqz[mask_unsqz]
|
147 |
+
|
148 |
+
gb_mask_pos = gb_mask_pos[None, ]
|
149 |
+
|
150 |
+
with torch.no_grad():
|
151 |
+
|
152 |
+
dec_verts = self.decoder(tri_fea_2, gb_mask_pos)
|
153 |
+
colors = self.rgbMlp(dec_verts).squeeze()
|
154 |
+
|
155 |
+
# Expect predicted colors value range from [-1, 1]
|
156 |
+
lo, hi = (-1, 1)
|
157 |
+
colors = (colors - lo) * (255 / (hi - lo))
|
158 |
+
colors = colors.clip(0, 255)
|
159 |
+
|
160 |
+
tex_unsqz[mask_unsqz] = colors
|
161 |
+
|
162 |
+
tex = tex_unsqz.view(res + (3,))
|
163 |
+
|
164 |
+
verts = mesh_v.squeeze().cpu().numpy()
|
165 |
+
faces = mesh_pos_idx[..., [2, 1, 0]].squeeze().cpu().numpy()
|
166 |
+
# faces = mesh_pos_idx
|
167 |
+
# faces = faces.detach().cpu().numpy()
|
168 |
+
# faces = faces[..., [2, 1, 0]]
|
169 |
+
indices = indices[..., [2, 1, 0]]
|
170 |
+
|
171 |
+
# xatlas.export(f"{out_dir}/{ind}.obj", verts[vmapping], indices, uvs)
|
172 |
+
matname = f'{out_dir}.mtl'
|
173 |
+
# matname = f'{out_dir}/{ind}.mtl'
|
174 |
+
fid = open(matname, 'w')
|
175 |
+
fid.write('newmtl material_0\n')
|
176 |
+
fid.write('Kd 1 1 1\n')
|
177 |
+
fid.write('Ka 1 1 1\n')
|
178 |
+
# fid.write('Ks 0 0 0\n')
|
179 |
+
fid.write('Ks 0.4 0.4 0.4\n')
|
180 |
+
fid.write('Ns 10\n')
|
181 |
+
fid.write('illum 2\n')
|
182 |
+
fid.write(f'map_Kd {out_dir.split("/")[-1]}.png\n')
|
183 |
+
fid.close()
|
184 |
+
|
185 |
+
fid = open(f'{out_dir}.obj', 'w')
|
186 |
+
# fid = open(f'{out_dir}/{ind}.obj', 'w')
|
187 |
+
fid.write('mtllib %s.mtl\n' % out_dir.split("/")[-1])
|
188 |
+
|
189 |
+
for pidx, p in enumerate(verts):
|
190 |
+
pp = p
|
191 |
+
fid.write('v %f %f %f\n' % (pp[0], pp[2], - pp[1]))
|
192 |
+
|
193 |
+
for pidx, p in enumerate(uvs):
|
194 |
+
pp = p
|
195 |
+
fid.write('vt %f %f\n' % (pp[0], 1 - pp[1]))
|
196 |
+
|
197 |
+
fid.write('usemtl material_0\n')
|
198 |
+
for i, f in enumerate(faces):
|
199 |
+
f1 = f + 1
|
200 |
+
f2 = indices[i] + 1
|
201 |
+
fid.write('f %d/%d %d/%d %d/%d\n' % (f1[0], f2[0], f1[1], f2[1], f1[2], f2[2]))
|
202 |
+
fid.close()
|
203 |
+
|
204 |
+
img = np.asarray(tex.data.cpu().numpy(), dtype=np.float32)
|
205 |
+
mask = np.sum(img.astype(float), axis=-1, keepdims=True)
|
206 |
+
mask = (mask <= 3.0).astype(float)
|
207 |
+
kernel = np.ones((3, 3), 'uint8')
|
208 |
+
dilate_img = cv2.dilate(img, kernel, iterations=1)
|
209 |
+
img = img * (1 - mask) + dilate_img * mask
|
210 |
+
img = img.clip(0, 255).astype(np.uint8)
|
211 |
+
|
212 |
+
cv2.imwrite(f'{out_dir}.png', img[..., [2, 1, 0]])
|
213 |
+
# cv2.imwrite(f'{out_dir}/{ind}.png', img[..., [2, 1, 0]])
|
|
|
|
|
|
|
|