Spaces:
mucusz
/
Runtime error

File size: 13,454 Bytes
3577d3c
487ee6d
da48dbe
487ee6d
 
 
 
c3d3e4a
 
 
487ee6d
 
c3d3e4a
487ee6d
 
 
 
 
 
 
 
 
da48dbe
3577d3c
 
 
 
 
 
da48dbe
3577d3c
c3d3e4a
487ee6d
3577d3c
c3d3e4a
 
487ee6d
 
 
c3d3e4a
487ee6d
 
 
 
c3d3e4a
 
 
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
 
da48dbe
3577d3c
 
487ee6d
f4e5ac5
3577d3c
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
 
 
3577d3c
487ee6d
 
 
 
 
 
f4e5ac5
c3d3e4a
 
 
3577d3c
c3d3e4a
3577d3c
c3d3e4a
f4e5ac5
c3d3e4a
fb140f6
 
c3d3e4a
 
 
3577d3c
f4e5ac5
3577d3c
 
 
 
fb140f6
f4e5ac5
fb140f6
3577d3c
c3d3e4a
 
3577d3c
c3d3e4a
3577d3c
 
 
c3d3e4a
 
 
3577d3c
fb140f6
 
c3d3e4a
3577d3c
 
 
 
 
 
 
 
 
c3d3e4a
3577d3c
 
c3d3e4a
 
3577d3c
c3d3e4a
fb140f6
 
 
 
 
 
 
c3d3e4a
 
 
 
3577d3c
 
c3d3e4a
 
3577d3c
 
 
 
c3d3e4a
3577d3c
487ee6d
 
 
c3d3e4a
3577d3c
487ee6d
 
c3d3e4a
3577d3c
 
c3d3e4a
487ee6d
 
 
 
 
 
 
 
3577d3c
 
c3d3e4a
 
3577d3c
8cf0096
 
3577d3c
 
fb140f6
 
8cf0096
3577d3c
8cf0096
 
c3d3e4a
f4e5ac5
3577d3c
487ee6d
 
 
 
3577d3c
 
 
487ee6d
3577d3c
 
f4e5ac5
487ee6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4e5ac5
 
 
487ee6d
 
f4e5ac5
 
 
487ee6d
f4e5ac5
 
3577d3c
 
c3d3e4a
3577d3c
 
 
c3d3e4a
 
fb140f6
 
da48dbe
487ee6d
f4e5ac5
 
 
 
 
 
 
 
 
 
487ee6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import argparse
import os
import os.path as osp

import numpy as np
import torch
import trimesh
from pytorch3d.ops import SubdivideMeshes
from pytorch3d.structures import Meshes
from scipy.spatial import cKDTree

import lib.smplx as smplx
from lib.common.local_affine import register
from lib.dataset.mesh_util import (
    SMPLX,
    export_obj,
    keep_largest,
    o3d_ransac,
    poisson,
    remesh_laplacian,
)
from lib.smplx.lbs import general_lbs

# loading cfg file
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", type=str, default="")
parser.add_argument("-g", "--gpu", type=int, default=0)
args = parser.parse_args()

smplx_container = SMPLX()
device = torch.device(f"cuda:{args.gpu}")

# loading SMPL-X and econ objs inferred with ECON
prefix = f"./results/econ/obj/{args.name}"
smpl_path = f"{prefix}_smpl_00.npy"
smplx_param = np.load(smpl_path, allow_pickle=True).item()

# export econ obj with pre-computed normals
econ_path = f"{prefix}_0_full.obj"
econ_obj = trimesh.load(econ_path)
assert (econ_obj.vertex_normals.shape[1] == 3)
econ_obj.export(f"{prefix}_econ_raw.ply")

# align econ with SMPL-X
econ_obj.vertices *= np.array([1.0, -1.0, -1.0])
econ_obj.vertices /= smplx_param["scale"].cpu().numpy()
econ_obj.vertices -= smplx_param["transl"].cpu().numpy()

for key in smplx_param.keys():
    smplx_param[key] = smplx_param[key].cpu().view(1, -1)

smpl_model = smplx.create(
    smplx_container.model_dir,
    model_type="smplx",
    gender="neutral",
    age="adult",
    use_face_contour=False,
    use_pca=False,
    num_betas=200,
    num_expression_coeffs=50,
    ext='pkl'
)

smpl_out_lst = []

# obtain the pose params of T-pose, DA-pose, and the original pose
for pose_type in ["a-pose", "t-pose", "da-pose", "pose"]:
    smpl_out_lst.append(
        smpl_model(
            body_pose=smplx_param["body_pose"],
            global_orient=smplx_param["global_orient"],
            betas=smplx_param["betas"],
            expression=smplx_param["expression"],
            jaw_pose=smplx_param["jaw_pose"],
            left_hand_pose=smplx_param["left_hand_pose"],
            right_hand_pose=smplx_param["right_hand_pose"],
            return_verts=True,
            return_full_pose=True,
            return_joint_transformation=True,
            return_vertex_transformation=True,
            pose_type=pose_type
        )
    )

# -------------------------- align econ and SMPL-X in DA-pose space ------------------------- #
# 1. find the vertex-correspondence between SMPL-X and econ
# 2. ECON + SMPL-X: posed space --> T-pose space --> DA-pose space
# 3. ECON (w/o hands & over-streched faces) + SMPL-X (w/ hands & registered inpainting parts)
# ------------------------------------------------------------------------------------------- #

smpl_verts = smpl_out_lst[3].vertices.detach()[0]
smpl_tree = cKDTree(smpl_verts.cpu().numpy())
dist, idx = smpl_tree.query(econ_obj.vertices, k=5)

if not osp.exists(f"{prefix}_econ_da.obj") or not osp.exists(f"{prefix}_smpl_da.obj"):

    # t-pose for ECON
    econ_verts = torch.tensor(econ_obj.vertices).float()
    rot_mat_t = smpl_out_lst[3].vertex_transformation.detach()[0][idx[:, 0]]
    homo_coord = torch.ones_like(econ_verts)[..., :1]
    econ_cano_verts = torch.inverse(rot_mat_t) @ torch.cat([econ_verts, homo_coord],
                                                           dim=1).unsqueeze(-1)
    econ_cano_verts = econ_cano_verts[:, :3, 0].cpu()
    econ_cano = trimesh.Trimesh(econ_cano_verts, econ_obj.faces)

    # da-pose for ECON
    rot_mat_da = smpl_out_lst[2].vertex_transformation.detach()[0][idx[:, 0]]
    econ_da_verts = rot_mat_da @ torch.cat([econ_cano_verts, homo_coord], dim=1).unsqueeze(-1)
    econ_da = trimesh.Trimesh(econ_da_verts[:, :3, 0].cpu(), econ_obj.faces)

    # da-pose for SMPL-X
    smpl_da = trimesh.Trimesh(
        smpl_out_lst[2].vertices.detach()[0], smpl_model.faces, maintain_orders=True, process=False
    )
    smpl_da.export(f"{prefix}_smpl_da.obj")

    # remove hands from ECON for next registeration
    econ_da_body = econ_da.copy()
    mano_mask = ~np.isin(idx[:, 0], smplx_container.smplx_mano_vid)
    econ_da_body.update_faces(mano_mask[econ_da.faces].all(axis=1))
    econ_da_body.remove_unreferenced_vertices()
    econ_da_body = keep_largest(econ_da_body)

    # remove SMPL-X hand and face
    register_mask = ~np.isin(
        np.arange(smpl_da.vertices.shape[0]),
        np.concatenate([smplx_container.smplx_mano_vid, smplx_container.smplx_front_flame_vid])
    )
    register_mask *= ~smplx_container.eyeball_vertex_mask.bool().numpy()
    smpl_da_body = smpl_da.copy()
    smpl_da_body.update_faces(register_mask[smpl_da.faces].all(axis=1))
    smpl_da_body.remove_unreferenced_vertices()
    smpl_da_body = keep_largest(smpl_da_body)

    # upsample the smpl_da_body and do registeration
    smpl_da_body = Meshes(
        verts=[torch.tensor(smpl_da_body.vertices).float()],
        faces=[torch.tensor(smpl_da_body.faces).long()],
    ).to(device)
    sm = SubdivideMeshes(smpl_da_body)
    smpl_da_body = register(econ_da_body, sm(smpl_da_body), device)

    # remove over-streched+hand faces from ECON
    econ_da_body = econ_da.copy()
    edge_before = np.sqrt(
        ((econ_obj.vertices[econ_cano.edges[:, 0]] -
          econ_obj.vertices[econ_cano.edges[:, 1]])**2).sum(axis=1)
    )
    edge_after = np.sqrt(
        ((econ_da.vertices[econ_cano.edges[:, 0]] -
          econ_da.vertices[econ_cano.edges[:, 1]])**2).sum(axis=1)
    )
    edge_diff = edge_after / edge_before.clip(1e-2)
    streched_mask = np.unique(econ_cano.edges[edge_diff > 6])
    mano_mask = ~np.isin(idx[:, 0], smplx_container.smplx_mano_vid)
    mano_mask[streched_mask] = False
    econ_da_body.update_faces(mano_mask[econ_cano.faces].all(axis=1))
    econ_da_body.remove_unreferenced_vertices()

    # stitch the registered SMPL-X body and floating hands to ECON
    econ_da_tree = cKDTree(econ_da.vertices)
    dist, idx = econ_da_tree.query(smpl_da_body.vertices, k=1)
    smpl_da_body.update_faces((dist > 0.02)[smpl_da_body.faces].all(axis=1))
    smpl_da_body.remove_unreferenced_vertices()

    smpl_hand = smpl_da.copy()
    smpl_hand.update_faces(
        smplx_container.smplx_mano_vertex_mask.numpy()[smpl_hand.faces].all(axis=1)
    )
    smpl_hand.remove_unreferenced_vertices()
    econ_da = sum([smpl_hand, smpl_da_body, econ_da_body])
    econ_da = poisson(econ_da, f"{prefix}_econ_da.obj", depth=10, face_count=50000)
    econ_da = remesh_laplacian(econ_da, f"{prefix}_econ_da.obj")
else:
    econ_da = trimesh.load(f"{prefix}_econ_da.obj")
    smpl_da = trimesh.load(f"{prefix}_smpl_da.obj", maintain_orders=True, process=False)

# ---------------------- SMPL-X compatible ECON ---------------------- #
# 1. Find the new vertex-correspondence between NEW ECON and SMPL-X
# 2. Build the new J_regressor, lbs_weights, posedirs
# 3. canonicalize the NEW ECON
# ------------------------------------------------------------------- #

print("Start building the SMPL-X compatible ECON model...")

smpl_tree = cKDTree(smpl_da.vertices)
dist, idx = smpl_tree.query(econ_da.vertices, k=5)
knn_weights = np.exp(-dist**2)
knn_weights /= knn_weights.sum(axis=1, keepdims=True)

econ_J_regressor = (smpl_model.J_regressor[:, idx] * knn_weights[None]).sum(dim=-1)
econ_lbs_weights = (smpl_model.lbs_weights.T[:, idx] * knn_weights[None]).sum(dim=-1).T

num_posedirs = smpl_model.posedirs.shape[0]
econ_posedirs = (
    smpl_model.posedirs.view(num_posedirs, -1, 3)[:, idx, :] * knn_weights[None, ..., None]
).sum(dim=-2).view(num_posedirs, -1).float()

econ_J_regressor /= econ_J_regressor.sum(dim=1, keepdims=True).clip(min=1e-10)
econ_lbs_weights /= econ_lbs_weights.sum(dim=1, keepdims=True)

rot_mat_da = smpl_out_lst[2].vertex_transformation.detach()[0][idx[:, 0]]
econ_da_verts = torch.tensor(econ_da.vertices).float()
econ_cano_verts = torch.inverse(rot_mat_da) @ torch.cat([
    econ_da_verts, torch.ones_like(econ_da_verts)[..., :1]
],
                                                        dim=1).unsqueeze(-1)
econ_cano_verts = econ_cano_verts[:, :3, 0].double()

# ----------------------------------------------------
# use original pose to animate ECON reconstruction
# ----------------------------------------------------

new_pose = smpl_out_lst[3].full_pose
# new_pose[:, :3] = 0.

posed_econ_verts, _ = general_lbs(
    pose=new_pose,
    v_template=econ_cano_verts.unsqueeze(0),
    posedirs=econ_posedirs,
    J_regressor=econ_J_regressor,
    parents=smpl_model.parents,
    lbs_weights=econ_lbs_weights
)
aligned_econ_verts = posed_econ_verts[0].detach().cpu().numpy()
aligned_econ_verts += smplx_param["transl"].cpu().numpy()
aligned_econ_verts *= smplx_param["scale"].cpu().numpy() * np.array([1.0, -1.0, -1.0])
econ_pose = trimesh.Trimesh(aligned_econ_verts, econ_da.faces)
assert (econ_pose.vertex_normals.shape[1] == 3)
econ_pose.export(f"{prefix}_econ_pose.ply")

# -------------------------------------------------------------------------
# Align posed ECON with original ECON, for pixel-aligned texture extraction
# -------------------------------------------------------------------------

print("Start ICP registration between posed & original ECON...")
import open3d as o3d

source = o3d.io.read_point_cloud(f"{prefix}_econ_pose.ply")
target = o3d.io.read_point_cloud(f"{prefix}_econ_raw.ply")
trans_init = o3d_ransac(source, target)
icp_criteria = o3d.pipelines.registration.ICPConvergenceCriteria(
    relative_fitness=0.000001, relative_rmse=0.000001, max_iteration=100
)

reg_p2l = o3d.pipelines.registration.registration_icp(
    source,
    target,
    0.1,
    trans_init,
    o3d.pipelines.registration.TransformationEstimationPointToPlane(),
    criteria=icp_criteria
)
econ_pose.apply_transform(reg_p2l.transformation)

cache_path = f"{prefix.replace('obj','cache')}"
os.makedirs(cache_path, exist_ok=True)

# -----------------------------------------------------------------
# create UV texture (.obj .mtl .png) from posed ECON reconstruction
# -----------------------------------------------------------------

print("Start Color mapping...")
from PIL import Image
from torchvision import transforms

from lib.common.render import query_color
from lib.common.render_utils import Pytorch3dRasterizer

if not osp.exists(f"{prefix}_econ_icp_rgb.ply"):
    masked_image = f"./results/econ/png/{args.name}_cloth.png"
    tensor_image = transforms.ToTensor()(Image.open(masked_image))[:, :, :512]
    final_colors = query_color(
        torch.tensor(econ_pose.vertices).float(),
        torch.tensor(econ_pose.faces).long(),
        ((tensor_image - 0.5) * 2.0).unsqueeze(0).to(device),
        device=device,
        paint_normal=False,
    )
    final_colors[final_colors == tensor_image[:, 0, 0] * 255.0] = 0.0
    final_colors = final_colors.detach().cpu().numpy()
    econ_pose.visual.vertex_colors = final_colors
    econ_pose.export(f"{prefix}_econ_icp_rgb.ply")
else:
    mesh = trimesh.load(f"{prefix}_econ_icp_rgb.ply")
    final_colors = mesh.visual.vertex_colors[:, :3]

print("Start UV texture generation...")

# Generate UV coords
v_np = econ_pose.vertices
f_np = econ_pose.faces

vt_cache = osp.join(cache_path, "vt.pt")
ft_cache = osp.join(cache_path, "ft.pt")

if osp.exists(vt_cache) and osp.exists(ft_cache):
    vt = torch.load(vt_cache).to(device)
    ft = torch.load(ft_cache).to(device)
else:
    import xatlas
    atlas = xatlas.Atlas()
    atlas.add_mesh(v_np, f_np)
    chart_options = xatlas.ChartOptions()
    chart_options.max_iterations = 4
    atlas.generate(chart_options=chart_options)
    vmapping, ft_np, vt_np = atlas[0]

    vt = torch.from_numpy(vt_np.astype(np.float32)).float().to(device)
    ft = torch.from_numpy(ft_np.astype(np.int64)).int().to(device)
    torch.save(vt.cpu(), vt_cache)
    torch.save(ft.cpu(), ft_cache)

# UV texture rendering
uv_rasterizer = Pytorch3dRasterizer(image_size=512, device=device)
texture_npy = uv_rasterizer.get_texture(
    torch.cat([(vt - 0.5) * 2.0, torch.ones_like(vt[:, :1])], dim=1),
    ft,
    torch.tensor(v_np).unsqueeze(0).float(),
    torch.tensor(f_np).unsqueeze(0).long(),
    torch.tensor(final_colors).unsqueeze(0).float() / 255.0,
)

gray_texture = texture_npy.copy()
gray_texture[texture_npy.sum(axis=2) == 0.0] = 0.5
Image.fromarray((gray_texture * 255.0).astype(np.uint8)).save(f"{cache_path}/texture.png")

# UV mask for TEXTure (https://readpaper.com/paper/4720151447010820097)
white_texture = texture_npy.copy()
white_texture[texture_npy.sum(axis=2) == 0.0] = 1.0
Image.fromarray((white_texture * 255.0).astype(np.uint8)).save(f"{cache_path}/mask.png")

# generate a-pose vertices
new_pose = smpl_out_lst[0].full_pose
new_pose[:, :3] = 0.

posed_econ_verts, _ = general_lbs(
    pose=new_pose,
    v_template=econ_cano_verts.unsqueeze(0),
    posedirs=econ_posedirs,
    J_regressor=econ_J_regressor,
    parents=smpl_model.parents,
    lbs_weights=econ_lbs_weights
)

# export mtl file
with open(f"{cache_path}/material.mtl", 'w') as fp:
    fp.write(f'newmtl mat0 \n')
    fp.write(f'Ka 1.000000 1.000000 1.000000 \n')
    fp.write(f'Kd 1.000000 1.000000 1.000000 \n')
    fp.write(f'Ks 0.000000 0.000000 0.000000 \n')
    fp.write(f'Tr 1.000000 \n')
    fp.write(f'illum 1 \n')
    fp.write(f'Ns 0.000000 \n')
    fp.write(f'map_Kd texture.png \n')

export_obj(posed_econ_verts[0].detach().cpu().numpy(), f_np, vt, ft, f"{cache_path}/mesh.obj")