This commit is contained in:
2023-07-12 16:01:33 +02:00
parent 1b219e4162
commit 1de0234861
9 changed files with 1107 additions and 160 deletions
+51 -122
View File
@@ -12,7 +12,7 @@ args = vars(parser.parse_args())
if args['debug']:
from configs.iccvw.cvae_norm_1 import config
from configs.iccvw.cvae_norm_5 import config
else:
config_module = importlib.import_module(args['config'])
config = config_module.config
@@ -28,6 +28,7 @@ import wandb
import tqdm
import random
import numpy as np
import kaleido
import plotly.graph_objects as go
import plotly.express as ex
from PIL import Image
@@ -93,7 +94,7 @@ def train_step(batch):
kl = kl_loss(mean, logvar)
reconstr_loss = l2_loss + l2_mesh_loss + (1 - ms_ssim)
loss = reconstr_loss + g_balancing_coeff * kl
loss: torch.Tensor = reconstr_loss + g_balancing_coeff * kl
optimizer.zero_grad()
loss.backward()
@@ -164,125 +165,6 @@ def plot_everything(batch: dict, type: str):
return { **{ type + '/images': imgs, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } }
def sample(folder):
# run = wandb.init(project='vae_plots', name=folder.split('/')[-1])
load_model(model,folder)
count = 0
for batch in dataset_train:
batch = static_dataset_train.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
uv_normals = tf.one_hot(batch['uv_normals'], 7)
nr_of_samples=2
pred = model.sample_single(batch['uv_static'][0], batch['uv_body_posed'][0], uv_normals[0], batch['uv_mask'][0], nr_of_samples=nr_of_samples)
pose, shape = batch['pose_shape'][0, :72], batch['pose_shape'][0, 72:]
pose, shape = tf.tile(pose[tf.newaxis,:], [nr_of_samples,1]), tf.tile(shape[tf.newaxis,:], [nr_of_samples,1])
mesh_pred = uv2mesh(pred)
mesh_posed = smpl.run_garment(pose, shape, mesh_pred).numpy()
mesh_orig = batch['mesh_posed'][0].numpy()
mesh_orig_reposed = smpl.run_garment(pose[:1], shape[:1], batch['mesh_unposed'][:1]).numpy()[0]
body = batch['mesh_body_posed'][0].numpy()
body_color = np.ones_like(body, dtype=np.int32)*100
F = np.load("custom_utils/smpl_faces.npy")
mask = batch['mesh_mask'].numpy().astype(bool)[0]
_, faces = _maskFaces(np.ones((config['smpl_res'], 3)), F, mask)
pred_zero = model.sample_single(batch['uv_static'][0], batch['uv_body_posed'][0], uv_normals[0], batch['uv_mask'][0], nr_of_samples=nr_of_samples, zero_latent=True)
mesh_pred_zero = uv2mesh(pred_zero)
mesh_posed_zero = smpl.run_garment(pose, shape, mesh_pred_zero).numpy()
meshes = []
meshes.append(go.Mesh3d(
# 8 vertices of a cube
x=mesh_orig_reposed[mask,0],
y=mesh_orig_reposed[mask,2],
z=mesh_orig_reposed[mask,1],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2]
))
for i in range(nr_of_samples):
x = mesh_posed[i][mask, :].copy()
# x[:, 2] += 1 * (i + 1)
x[:, 2] += 1
meshes.append(go.Mesh3d(
# 8 vertices of a cube
x=x[:,0],
y=x[:,2],
z=x[:,1],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2]
))
for i in range(nr_of_samples):
x = mesh_posed_zero[i][mask, :].copy()
# x[:, 2] += 1 * (i + 1)
x[:, 2] += 2
meshes.append(go.Mesh3d(
# 8 vertices of a cube
x=x[:,0],
y=x[:,2],
z=x[:,1],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2]
))
# for i in range(5):
# x = body.copy()
# x[:, 2] += 1 * i
# meshes.append(go.Mesh3d(
# # 8 vertices of a cube
# x=x[:,0],
# y=x[:,2],
# z=x[:,1],
# # i, j and k give the vertices of triangles
# i = F[:,0],
# j = F[:,1],
# k = F[:,2],
# vertexcolor=body_color
# ))
fig = go.Figure(data=meshes)
fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=2, z=1))
# fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=nr_of_samples-1, z=1))
fig.update_layout(
scene = dict(
xaxis = dict(nticks=4, range=[-1,1],),
# yaxis = dict(nticks=4, range=[-1,nr_of_samples+1],),
yaxis = dict(nticks=4, range=[-1,3],),
zaxis = dict(nticks=4, range=[-1,1],),)
)
# wandb.log({'plot_' + str(count): fig})
fig.show()
pred = pred.numpy()
frames = [Image.fromarray(((pred[i] + 1) * 128).astype(np.int8), mode='RGB') for i in range(pred.shape[0])]
frames[0].save("temp/garment_1.gif", format="GIF", append_images=frames[1:],
save_all=True, duration=500, loop=0)
if count > 10:
break
print(count)
count += 1
print()
def train():
global g_balancing_coeff
@@ -314,7 +196,7 @@ def train():
print(step)
if train_loss['train/euclid_error'] < config['balancing_activation_limit']:
g_balancing_coeff += 1 / 10000
g_balancing_coeff += 1 / 2000
if step % 20000 == 0:
ckpt_saver(model, step, optimizer, None)
@@ -322,6 +204,49 @@ def train():
step += 1
def sample():
model.eval()
load_model(model, f'checkpoints/iccvw/{config["name"]}')
count = 0
for batch in train_dataloader:
uv_static = batch['uv_static']
uv_body_posed = batch['uv_body_posed']
uv_mask = batch['uv_mask']
batch_size = uv_static.size(0)
for i in range(batch_size):
uv_static_tiled = uv_static[i][None,:,:,:].repeat(4, 1, 1, 1)
uv_body_posed_tiled = uv_body_posed[i][None,:,:,:].repeat(4, 1, 1, 1)
uv_mask_tiled = uv_mask[i][None,:,:].repeat(4, 1, 1)
with torch.inference_mode():
pred = model.sample(uv_static_tiled, uv_body_posed_tiled, uv_mask_tiled)
pred = pred * 1.4
pred = pred.cpu().numpy().transpose(0, 2, 3, 1)
pred = (pred + 1.4) / 2.8
pred = pred * uv_mask_tiled[:,:,:,None].cpu().numpy()
gt = (batch['uv_normals'][i].cpu().numpy().transpose(1, 2, 0) + 1.4) / 2.8 * uv_mask_tiled[0,:,:,None].cpu().numpy()
img = np.concatenate(pred, axis=1)
img = np.concatenate([gt, img], axis=1)
# flip image along its shorter edge
img = img[::-1,:,:]
fig = ex.imshow(img)
fig.update_layout(margin=dict(l=0, r=0, b=0, t=0, pad=0), width=img.shape[1], height=img.shape[0])
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
fig.write_image(f'temp/normals/{batch["id"][i]}_{batch["frame_nr"][i].cpu().numpy()}_{batch["garment"][i]}.png')
count += 1
if count > 100:
break
if __name__ == '__main__':
if not args['debug']:
init_wandb()
@@ -338,6 +263,10 @@ if __name__ == '__main__':
model = CVAENorm(config)
sample()
exit()
optimizer = optim.Adam(model.parameters(), lr=config['lr'])
_MSSSIM = MS_SSIM(data_range=2, size_average=True, channel=3)
g_balancing_coeff = config['starting_balancing_coeff']