563 lines
27 KiB
Python
563 lines
27 KiB
Python
from typing import Any, List
|
|
from omegaconf import DictConfig
|
|
import numpy as np
|
|
from pathlib import Path
|
|
|
|
import kornia
|
|
from kornia import morphology, filters
|
|
|
|
import os
|
|
import cv2
|
|
from skimage import transform
|
|
|
|
import torchvision
|
|
|
|
import torch
|
|
import torch.nn.functional as F
|
|
|
|
from pytorch_lightning import LightningModule
|
|
from torchmetrics import MeanMetric, MinMetric
|
|
import logging
|
|
|
|
from src.loss.loss_feat2face import VGGLoss
|
|
from src.loss.common import adversarial_loss
|
|
|
|
from .components.networks_mesh2face import Generator, Discriminator
|
|
from . import init_weights
|
|
|
|
class GANRenderModel(LightningModule):
|
|
|
|
def __init__(
|
|
self,
|
|
opt: DictConfig = None,
|
|
opt_loss: DictConfig = None,
|
|
opt_optim: DictConfig = None,
|
|
):
|
|
super().__init__()
|
|
logging.info(f"[__init__] self.device = {self.device}")
|
|
self.opt = opt
|
|
self.opt_loss = opt_loss
|
|
self.opt_optim = opt_optim
|
|
|
|
mapping_kwargs=dict(num_layers = opt.num_layers)
|
|
|
|
|
|
# load networks
|
|
self.netG = Generator(
|
|
z_dim =opt.z_dim, # Input latent (Z) dimensionality.
|
|
c_dim =opt.c_dim, # Conditioning label (C) dimensionality.
|
|
w_dim =opt.w_dim, # Intermediate latent (W) dimensionality.
|
|
img_resolution =opt.img_resolution, # Output resolution.
|
|
img_channels =opt.img_channels, # Number of output color channels.
|
|
mapping_kwargs = mapping_kwargs,
|
|
)
|
|
|
|
self.netD = Discriminator(
|
|
c_dim =opt.c_dim, # Conditioning label (C) dimensionality.
|
|
img_resolution =opt.img_resolution, # Input resolution.
|
|
img_channels =opt.img_channels, # Number of input color channels.
|
|
mapping_kwargs =mapping_kwargs,
|
|
)
|
|
|
|
# init by default
|
|
init_weights(self.netG, init_type='kaiming')
|
|
init_weights(self.netD, init_type='kaiming')
|
|
|
|
# load form ckp
|
|
if opt.pretrain:
|
|
logging.info(f"\n [init] load stat for netG, netD, from = {opt.pretrain_path}")
|
|
self.load_pretrain_model(opt.pretrain_path)
|
|
|
|
# use separate metric instance for train, val and test step
|
|
# to ensure a proper reduction over the epoch
|
|
self.train_best, self.valid_best = MinMetric(), MinMetric()
|
|
self.train_rec, self.valid_rec = MeanMetric(), MeanMetric()
|
|
|
|
# for logging best so far validation accuracy
|
|
self.criterionL1 = torch.nn.L1Loss()
|
|
self.criterionVGG = VGGLoss()
|
|
|
|
|
|
def load_pretrain_model(self, pretrain_path):
|
|
state_dict = torch.load(pretrain_path, map_location=self.device)["state_dict"]
|
|
|
|
# for netG
|
|
state_dict_netG = {k[5:]:v for k, v in state_dict.items() if (k[:4] == "netG" and k[5:] in self.netG.state_dict().keys())}
|
|
state_dict_netD = {k[5:]:v for k, v in state_dict.items() if (k[:4] == "netD" and k[5:] in self.netD.state_dict().keys())}
|
|
|
|
# print(f"\nself.netG state \n: {self.netG.state_dict().keys()}, \n\n state_dict_netG = {state_dict_netG.keys()}")
|
|
# print(f"\nself.netD state \n: {self.netD.state_dict().keys()}, \n\n state_dict_netD = {state_dict_netD.keys()}")
|
|
|
|
# 看看哪些参数没有初始化
|
|
diff_G = set(self.netG.state_dict().keys()).difference(set(state_dict_netG.keys())) # 在netG.keys()中,但不在state_dict_netG中
|
|
diff_D = set(self.netD.state_dict().keys()).difference(set(state_dict_netD.keys())) # 在netG.keys()中,但不在state_dict_netG中
|
|
print(f"\nself.netG, not init keys from pretrained model: \n {diff_G}")
|
|
print(f"\nself.netD, not init keys from pretrained model: \n {diff_D}")
|
|
|
|
# update
|
|
self.netG.load_state_dict(state_dict_netG, strict=False)
|
|
self.netD.load_state_dict(state_dict_netD, strict=False)
|
|
|
|
|
|
|
|
def configure_optimizers(self):
|
|
"""Choose what optimizers and learning-rate schedulers to use in your optimization.
|
|
Normally you'd need one. But in the case of GANs or similar you might have multiple.
|
|
"""
|
|
|
|
lr_G = self.opt_optim.lr_G
|
|
lr_D = self.opt_optim.lr_D
|
|
optim_G = torch.optim.Adam(self.netG.parameters(), lr=lr_G, betas=(0, 0.99), eps=1e-8)
|
|
optim_D = torch.optim.Adam(self.netD.parameters(), lr=lr_D, betas=(0, 0.99), eps=1e-8)
|
|
|
|
return [optim_D, optim_G], []
|
|
|
|
|
|
@torch.no_grad()
|
|
def set_input(self, batch:Any):
|
|
# data info
|
|
data_info = {
|
|
"vid": batch['vid'],
|
|
"path_data": batch["path_data"],
|
|
"frame_interval": batch['frame_interval'],
|
|
}
|
|
|
|
# get verties
|
|
# batch_idn = self.mean_shape.expand(B, N, -1)
|
|
# batch_lmk = data_ldmk[:, :, 0:17, :] # (B, N, 17, 2)
|
|
# dim of shape = 100, tex = 50, exp = 50, pose = 6, cam = 3, light = 27
|
|
data_deca = batch["data_coeff"] # (B, N, 236)
|
|
batch_exp = data_deca[:, :, 150:200]
|
|
batch_pos = data_deca[:, :, 200:206]
|
|
batch_cam = data_deca[:, :, 206:209]
|
|
batch_lit = data_deca[:, :, 209:236]
|
|
|
|
# batch_lmk = batch_lmk.reshape(batch_lmk.shape[0], batch_lmk.shape[1], -1) # (B, N, 34)
|
|
# coeff = torch.cat([batch_exp, batch_pos, batch_lmk], dim=2) # (B, N, nc_codit= 56+34)
|
|
coeff = torch.cat([batch_exp, batch_pos, batch_cam, batch_lit], dim=2) # (B, N, nc_codit=59)
|
|
|
|
# coeff = torch.cat([batch_exp, batch_cam, batch_pos], dim=2) # (B, N, nc_codit=59)
|
|
# logging.info(f"[set_input] cat coeff = {coeff.shape}, dtype={coeff.dtype}, device={coeff.device}")
|
|
|
|
# 0=[0,1,2,(3),4, 5, 6], 1=[1,2,3,(4), 5, 6,7], ...
|
|
coeff = coeff.unfold(dimension=1, size=7, step=1) # (B, N', nc_codit, 7)
|
|
# logging.info(f"[set_input] unfold coeff = {coeff.shape}, dtype={coeff.dtype}, device={coeff.device}")
|
|
|
|
# update N
|
|
B, N = coeff.size(0), coeff.size(1)
|
|
|
|
# get other GT & align to coeff
|
|
image_tgt = batch["data_frame"][:, 3:3+N] # (B, N, 3, 256, 256)
|
|
masks_tgt = batch["data_mask"][:, 3:3+N] # (B, N, 256, 256)
|
|
ldmks_tgt = batch["data_ldmks"][:, 3:3+N, 0:17] # (B, N, 17, 2), only get chin margin landmarks
|
|
|
|
# get a reference image
|
|
# assert B >= 2, f"the batch size(={B}) should >= 2!"
|
|
|
|
# idx_select = np.random.randint(low=0, high=N, size=B)
|
|
image_ref = batch["data_frame"][:, 0:1] # (B, 1, 3, 256, 256)
|
|
# image_ref = image_ref.roll(shifts=1, dims=0) # (B, 1, 3, 256, 256) , roll along B
|
|
image_ref = image_ref.expand(-1, N, -1, -1, -1) # (B, N, 3, 256, 256)
|
|
|
|
# reshape to input
|
|
image_tgt = image_tgt.reshape(B*N, image_tgt.size(2), image_tgt.size(3), image_tgt.size(4)) # (B*N, 3, 256, 256)
|
|
image_ref = image_ref.reshape(B*N, image_ref.size(2), image_ref.size(3), image_ref.size(4)) # (B*N, 3, 256, 256)
|
|
|
|
masks_tgt = masks_tgt.reshape(B*N, 1, masks_tgt.size(2), masks_tgt.size(3)) # (B*N, 1, 256, 256)
|
|
ldmks_tgt = ldmks_tgt.reshape(B*N, ldmks_tgt.size(2), ldmks_tgt.size(3)) # (B*N, 17, 2)
|
|
coeff = coeff.reshape(B*N, -1) # (B*N, 59*7)
|
|
|
|
# make mask
|
|
# kernel = torch.ones(3, 3).to(self.device)
|
|
# masks_tgt = morphology.erosion(masks_tgt, kernel)
|
|
# masks_tgt = filters.gaussian_blur2d(masks_tgt, (3, 3), (1.5, 1.5))
|
|
|
|
# logging.info(f"[reshape] coeff = {coeff.shape}, dtype={coeff.dtype}, device={coeff.device}")
|
|
# logging.info(f"[reshape] image_tgt = {image_tgt.shape}, dtype={image_tgt.dtype}, device={image_tgt.device}")
|
|
# logging.info(f"[reshape] masks_tgt = {masks_tgt.shape}, dtype={masks_tgt.dtype}, device={masks_tgt.device}")
|
|
|
|
return B, N, coeff, image_tgt, masks_tgt, ldmks_tgt, data_info, image_ref
|
|
|
|
|
|
def set_requires_grad(self, nets, requires_grad=False):
|
|
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
|
|
Parameters:
|
|
nets (network list) -- a list of networks
|
|
requires_grad (bool) -- whether the networks require gradients or not
|
|
"""
|
|
if not isinstance(nets, list):
|
|
nets = [nets]
|
|
|
|
for net in nets:
|
|
if net is not None:
|
|
for param in net.parameters():
|
|
param.requires_grad = requires_grad
|
|
|
|
|
|
# def forward(self, batch_z:torch.Tensor, batch_c:torch.Tensor):
|
|
# return self.netG(batch_z, batch_c)
|
|
def training_step(self, batch, batch_idx, optimizer_idx):
|
|
|
|
|
|
B, N, batch_c, image_tgt, masks_tgt, ldmks_tgt, batch_info, image_ref = self.set_input(batch)
|
|
|
|
# get noize input z
|
|
batch_z = torch.randn(B*N, self.opt.z_dim).type_as(image_tgt) # (BN, dim_latent)
|
|
# logging.info(f"[training_step] batch_c = {batch_c.shape}, dtype={batch_c.dtype}, device={batch_c.device}")
|
|
# logging.info(f"[training_step] batch_z = {batch_z.shape}, dtype={batch_z.dtype}, device={batch_z.device}")
|
|
|
|
# forward
|
|
# batch_img = torch.cat([image_ref, masks_tgt], dim=1) # (B*N, 4, 256, 256)
|
|
image_pdt = self.netG(batch_z, batch_c) # (B*N, 3, 256, 256)
|
|
# logging.info(f"[discriminator] image_pdt = {image_pdt.shape}, dtype={image_pdt.dtype}, device={image_pdt.device}")
|
|
|
|
# image_pdt_masked = image_pdt * masks_tgt # use pdt mask for masked pdt image
|
|
image_pdt_masked = image_pdt * masks_tgt # use pdt mask for masked pdt image
|
|
image_tgt_masked = image_tgt * masks_tgt # use tgt mask for masked tgt image
|
|
|
|
# return
|
|
image_pdt_weighted = kornia.enhance.add_weighted(image_pdt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_pdt, 0.6, 0.0).detach()
|
|
image_tgt_weighted = kornia.enhance.add_weighted(image_tgt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_tgt, 0.6, 0.0).detach()
|
|
|
|
|
|
##################################################
|
|
######### Optimize Discriminator #########
|
|
##################################################
|
|
if optimizer_idx == 0:
|
|
|
|
# GT label
|
|
pred_real = self.netD(image_tgt_masked, batch_c)
|
|
loss_D_real = adversarial_loss(pred_real, target_is_real=True, loss_mode="lsgan")
|
|
|
|
# PT label
|
|
pred_fake = self.netD(image_pdt_masked.detach(), batch_c)
|
|
loss_D_fake = adversarial_loss(pred_fake, target_is_real=False, loss_mode="lsgan")
|
|
|
|
# discriminator loss is the average of these
|
|
d_loss = (loss_D_real + loss_D_fake) / 2
|
|
|
|
# logging
|
|
self.log("train/D_real", loss_D_real, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("train/D_fake", loss_D_fake, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.logger.experiment[0].add_scalar("train/D_real", loss_D_real, self.global_step)
|
|
self.logger.experiment[0].add_scalar("train/D_fake", loss_D_fake, self.global_step)
|
|
|
|
return {"loss": d_loss, "image_pdt": image_pdt_weighted, "image_tgt": image_tgt_weighted }
|
|
|
|
|
|
|
|
##################################################
|
|
######### Optimize Generator #########
|
|
##################################################
|
|
if optimizer_idx == 1:
|
|
# adversarial loss for each frames
|
|
pred_fake = self.netD(image_pdt_masked, batch_c)
|
|
loss_G = adversarial_loss(pred_fake, target_is_real=True, loss_mode="lsgan")
|
|
|
|
# L1-loss
|
|
loss_rec = self.criterionL1(image_pdt_masked, image_tgt_masked)
|
|
# loss_maskL1 = self.criterionMaskL1(image_pdt, image_tgt, self.mouth_mask * self.opt.lambda_mask)
|
|
|
|
# VGG & Style loss
|
|
loss_vgg, loss_style = self.criterionVGG(image_pdt_masked, image_tgt_masked, style=True)
|
|
loss_vgg = loss_vgg.mean()
|
|
loss_style = loss_style.mean()
|
|
|
|
# # feature match loss
|
|
# pred_real = self.netD(image_tgt, batch_c)
|
|
# pred_fake = self.netD(image_pdt, batch_c)
|
|
# loss_FM = self.compute_FeatureMatching_loss(pred_fake, pred_real)
|
|
|
|
# total loss
|
|
g_loss = loss_G + loss_rec * self.opt_loss.lambda_rec \
|
|
+ loss_vgg * self.opt_loss.lambda_vgg \
|
|
+ loss_style * self.opt_loss.lambda_style \
|
|
|
|
|
|
# logging
|
|
self.log("train/G", loss_G, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("train/rec", loss_rec, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("train/vgg", loss_vgg, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("train/style", loss_style, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.logger.experiment[0].add_scalar("train/G", loss_G, self.global_step)
|
|
self.logger.experiment[0].add_scalar("train/rec", loss_rec, self.global_step)
|
|
self.logger.experiment[0].add_scalar("train/vgg", loss_vgg, self.global_step)
|
|
self.logger.experiment[0].add_scalar("train/style", loss_style, self.global_step)
|
|
|
|
# # # show metric
|
|
self.train_rec(loss_rec)
|
|
self.train_best(g_loss)
|
|
|
|
return {"loss": g_loss, "image_pdt": image_pdt_weighted, "image_tgt": image_tgt_weighted }
|
|
|
|
|
|
def on_train_batch_end(self, outputs, batch, batch_idx):
|
|
|
|
if not (self.global_step % 100 == 0 and self.global_rank == 0):
|
|
return super().on_train_batch_end(outputs, batch, batch_idx)
|
|
# print(f"outputs len={len(outputs)}, outputs = {outputs}")
|
|
|
|
image_pdt = outputs[0]["image_pdt"][:4]
|
|
image_tgt = outputs[0]["image_tgt"][:4]
|
|
grid_pdt = torchvision.utils.make_grid(image_pdt)
|
|
grid_tgt = torchvision.utils.make_grid(image_tgt)
|
|
# logging.info(f"[on] grid_pdt shape={grid_pdt.shape}, grid_tgt={grid_tgt.shape}, device={grid_tgt.device}")
|
|
# logging.info(f"[on] self.logger.experiment len ={len(self.logger.experiment)}")
|
|
# logging.info(f"[on] self.logger.experiment ={self.logger.experiment}")
|
|
self.logger.experiment[0].add_image("image_pdt", grid_pdt, self.global_step)
|
|
self.logger.experiment[0].add_image("image_tgt", grid_tgt, self.global_step)
|
|
|
|
|
|
def on_train_epoch_end(self):
|
|
|
|
metric_rec = self.train_rec.compute()
|
|
metric_best = self.train_best.compute()
|
|
|
|
self.log("metric/train/rec", metric_rec, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
|
self.log("metric/train/best", metric_best, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
|
self.logger.experiment[0].add_scalar("metric/train/rec", metric_rec, self.global_step)
|
|
self.logger.experiment[0].add_scalar("metric/train/best", metric_best, self.global_step)
|
|
|
|
|
|
def validation_step(self, batch, batch_idx):
|
|
B, N, batch_c, image_tgt, masks_tgt, ldmks_tgt, batch_info, image_ref = self.set_input(batch)
|
|
|
|
# get noize input z
|
|
batch_z = torch.randn(B*N, self.opt.z_dim).type_as(image_tgt) # (BN, dim_latent)
|
|
# logging.info(f"[training_step] batch_c = {batch_c.shape}, dtype={batch_c.dtype}, device={batch_c.device}")
|
|
# logging.info(f"[training_step] batch_z = {batch_z.shape}, dtype={batch_z.dtype}, device={batch_z.device}")
|
|
|
|
# forward
|
|
# batch_img = torch.cat([image_ref, masks_tgt], dim=1) # (B*N, 4, 256, 256)
|
|
image_pdt = self.netG(batch_z, batch_c) # (B*N, 4, 256, 256)
|
|
|
|
# add mask
|
|
image_pdt_masked = image_pdt * masks_tgt # use pdt mask for masked pdt image
|
|
image_tgt_masked = image_tgt * masks_tgt # use tgt mask for masked tgt image
|
|
|
|
|
|
# adversarial loss
|
|
pred_fake = self.netD(image_pdt_masked, batch_c)
|
|
loss_G = adversarial_loss(pred_fake, target_is_real=True)
|
|
|
|
# L1-loss
|
|
loss_rec = self.criterionL1(image_pdt_masked, image_tgt_masked)
|
|
# loss_maskL1 = self.criterionMaskL1(image_pdt, image_tgt, self.mouth_mask * self.opt.lambda_mask)
|
|
|
|
# VGG & Style loss
|
|
loss_vgg, loss_style = self.criterionVGG(image_pdt_masked, image_tgt_masked, style=True)
|
|
loss_vgg = loss_vgg.mean()
|
|
loss_style = loss_style.mean()
|
|
|
|
|
|
self.log("valid/G", loss_G, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("valid/rec", loss_rec, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("valid/vgg", loss_vgg, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("valid/style", loss_style, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
|
|
self.logger.experiment[0].add_scalar("valid/G", loss_G, self.global_step)
|
|
self.logger.experiment[0].add_scalar("valid/rec", loss_rec, self.global_step)
|
|
self.logger.experiment[0].add_scalar("valid/vgg", loss_vgg, self.global_step)
|
|
self.logger.experiment[0].add_scalar("valid/style", loss_style, self.global_step)
|
|
|
|
loss = loss_G + loss_rec * self.opt_loss.lambda_rec \
|
|
+ loss_vgg * self.opt_loss.lambda_vgg \
|
|
+ loss_style * self.opt_loss.lambda_style
|
|
|
|
# add to logger
|
|
pred_real = self.netD(image_tgt_masked, batch_c)
|
|
loss_D_real = adversarial_loss(pred_real, target_is_real=True, loss_mode="lsgan")
|
|
|
|
pred_fake = self.netD(image_pdt_masked.detach(), batch_c)
|
|
loss_D_fake = adversarial_loss(pred_fake, target_is_real=False, loss_mode="lsgan")
|
|
|
|
self.log("valid/D_real", loss_D_real, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.log("valid/D_fake", loss_D_fake, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
|
self.logger.experiment[0].add_scalar("valid/D_real", loss_D_real, self.global_step)
|
|
self.logger.experiment[0].add_scalar("valid/D_fake", loss_D_fake, self.global_step)
|
|
|
|
# # # show metric
|
|
self.valid_rec(loss_rec)
|
|
self.valid_best(loss)
|
|
|
|
return {"loss": loss }
|
|
|
|
|
|
def validation_epoch_end(self, outputs: List[Any]):
|
|
"""
|
|
`outputs` is a list of dicts returned from `validation_step()`
|
|
"""
|
|
metric_rec = self.valid_rec.compute()
|
|
metric_best = self.valid_best.compute()
|
|
|
|
self.log("metric/valid/rec", metric_rec, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
|
self.log("metric/valid/best", metric_best, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
|
self.logger.experiment[0].add_scalar("metric/valid/rec", metric_rec, self.global_step)
|
|
self.logger.experiment[0].add_scalar("metric/valid/best", metric_best, self.global_step)
|
|
|
|
|
|
def test_step(self, batch, batch_idx):
|
|
|
|
B, N, batch_c, image_tgt, masks_tgt, ldmks_tgt, batch_info, image_ref = self.set_input(batch)
|
|
|
|
assert B == 1, f"B should == 1 in this test steps"
|
|
# return {"loss": 0, "path_data":batch_info["path_data"][0]}
|
|
|
|
frame_beg = batch_info["frame_interval"][0].cpu().numpy()[0]
|
|
frame_end = batch_info["frame_interval"][1].cpu().numpy()[0]
|
|
|
|
# for windws input & cut
|
|
frame_beg = batch_info["frame_interval"][0].cpu().numpy()[0] + 3
|
|
frame_end = frame_beg + N
|
|
# frame_end = batch_info["frame_interval"][1].cpu().numpy()[0]
|
|
|
|
if frame_beg > 2000:
|
|
return {"loss": 0, "path_data":batch_info["path_data"][0]}
|
|
|
|
|
|
batch_z = torch.randn(B*N, self.opt.z_dim).type_as(image_tgt) # (BN, dim_latent)
|
|
# logging.info(f"[training_step] batch_c = {batch_c.shape}, dtype={batch_c.dtype}, device={batch_c.device}")
|
|
# logging.info(f"[training_step] batch_z = {batch_z.shape}, dtype={batch_z.dtype}, device={batch_z.device}")
|
|
|
|
# forward
|
|
batch_img = torch.cat([image_ref, masks_tgt], dim=1) # (B*N, 4, 256, 256)
|
|
image_pdt = self.netG(batch_z, batch_c, batch_img).detach() # (B*N, 3, 256, 256)
|
|
|
|
# add to logger
|
|
# save to
|
|
path_frame = Path(batch_info["path_data"][0]).joinpath("frames")
|
|
path_tfrom = Path(batch_info["path_data"][0]).joinpath("frames_crop_tform_512")
|
|
|
|
|
|
path_save_concat = Path(batch_info["path_data"][0]).joinpath(f"test_concat_epoch{self.current_epoch}")
|
|
path_save_merged = Path(batch_info["path_data"][0]).joinpath(f"test_merged_epoch{self.current_epoch}")
|
|
path_save_concat.mkdir(parents=True, exist_ok=True)
|
|
path_save_merged.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
# generate masks_tgt
|
|
dilate_size = 11
|
|
# kernel = torch.ones(dilate_size, dilate_size).to(self.device)
|
|
# masks_tgt = morphology.dilation(masks_tgt, kernel)
|
|
|
|
kernel = torch.ones(dilate_size // 2, dilate_size // 2).to(self.device)
|
|
masks_tgt = morphology.erosion(masks_tgt, kernel)
|
|
masks_tgt = filters.gaussian_blur2d(masks_tgt, (dilate_size // 2, dilate_size // 2), (1.5, 1.5))
|
|
|
|
|
|
# concate tgt & pdt
|
|
# image_masked = masks_tgt * image_pdt + (1-masks_tgt) * image_tgt # (B, 3, 256, 256)
|
|
image_masked = masks_tgt * image_pdt + (1-masks_tgt) * image_tgt # (B, 3, 256, 256)
|
|
image_pdt_weighted = kornia.enhance.add_weighted(image_pdt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_pdt, 0.6, 0.0)
|
|
image_tgt_weighted = kornia.enhance.add_weighted(image_tgt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_tgt, 0.6, 0.0)
|
|
|
|
image_concat = torch.cat([image_pdt_weighted, image_masked, image_tgt_weighted], dim=3).cpu().numpy() # (B, 3, 256, 256*3)
|
|
image_masked = image_masked.cpu().numpy() # (B, 3, 256, 256)
|
|
|
|
logging.info(f'frame_beg {frame_beg}, {frame_end}, {image_concat.shape}, {image_concat.dtype}, mean={image_concat.mean()}')
|
|
for i, idx in enumerate(range(frame_beg, frame_end)):
|
|
if i > 1999: continue
|
|
|
|
jpath_save_concat = path_save_concat.joinpath(f"frame-{idx:06d}.jpg")
|
|
# jpath_save_masked = path_save_masked.joinpath(f"frame-{idx:06d}.jpg")
|
|
jpath_save_merged = path_save_merged.joinpath(f"frame-{idx:06d}.jpg")
|
|
|
|
jpath_image = path_frame.joinpath(f"frame-{idx:06d}.jpg")
|
|
jpath_tform = path_tfrom.joinpath(f"frame-{idx:06d}.npy")
|
|
|
|
#
|
|
jimage_concat = self.tensor2image(image_concat[i]) # (256, 256, 3)
|
|
jimage_masked = self.tensor2image(image_masked[i]) # (256, 256, 3)
|
|
|
|
# load image
|
|
image = cv2.imread(str(jpath_image)) # (H=1080, W=1920, 3)
|
|
tform_param = np.load(str(jpath_tform)) # (3,3)
|
|
# print(f"orignal image shape = {image.shape}, tform_param = {tform_param.shape}")
|
|
|
|
# get bbox
|
|
tform = transform.SimilarityTransform(tform_param)
|
|
DST_PTS = np.array([[0, 0], [0, 512 - 1], [512 - 1, 0]])
|
|
src_pts = tform.inverse(DST_PTS)
|
|
left, right = int(src_pts[0][0]), int(src_pts[2][0])
|
|
top, bottom = int(src_pts[0][1]), int(src_pts[1][1])
|
|
osize = min(right-left, bottom-top)
|
|
# print(f"(left,top)=({left},{top}), (right, bottom)=({right},{bottom}), osize= {osize}")
|
|
|
|
# resize to osize
|
|
iimage_masked_resize = cv2.resize(jimage_masked, dsize=(osize, osize), interpolation=cv2.INTER_LINEAR)
|
|
|
|
# paseter to orignial data
|
|
image[top:top+osize, left:left+osize, :] = iimage_masked_resize
|
|
|
|
# save to image
|
|
cv2.imwrite(str(jpath_save_concat), jimage_concat)
|
|
# cv2.imwrite(str(jpath_save_masked), jimage_masked)
|
|
cv2.imwrite(str(jpath_save_merged), image)
|
|
|
|
return {"loss": 0, "path_data":batch_info["path_data"][0]}
|
|
|
|
|
|
def test_epoch_end(self, outputs: List[Any]):
|
|
"""
|
|
`outputs` is a list of dicts returned from `test_step()`
|
|
"""
|
|
|
|
# concate video and add audio
|
|
path_data = Path(outputs[0]["path_data"])
|
|
logging.info(f"[test_epoch_end] path_data={path_data}")
|
|
|
|
path_save_concat = path_data.joinpath(f"test_concat_epoch{self.current_epoch}")
|
|
path_save_merged = path_data.joinpath(f"test_merged_epoch{self.current_epoch}")
|
|
|
|
# save merged video
|
|
ipath_frames = f"{str(path_save_merged)}/frame-%06d.jpg"
|
|
ipath_audios = f"{str(path_data)}/audio/audio_trim.wav"
|
|
ipath_output = f"{str(path_data)}/video/test_merged_epoch{self.current_epoch}.mp4"
|
|
cmd = f"ffmpeg -y -r 50 -f image2 -i {ipath_frames} -i {ipath_audios} -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest {ipath_output}"
|
|
logging.info(f"RUN: cmd")
|
|
os.system(cmd)
|
|
|
|
# save concat video
|
|
ipath_frames = f"{str(path_save_concat)}/frame-%06d.jpg"
|
|
ipath_audios = f"{str(path_data)}/audio/audio_trim.wav"
|
|
ipath_output = f"{str(path_data)}/video/test_concat_epoch{self.current_epoch}.mp4"
|
|
cmd = f"ffmpeg -y -r 50 -f image2 -i {ipath_frames} -i {ipath_audios} -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest {ipath_output}"
|
|
logging.info(f"RUN: cmd")
|
|
os.system(cmd)
|
|
|
|
# cmd = "ffmpeg -y -r 50 -f image2 -i test_merged_epoch22/frame-%06d.jpg -i audio/audio_trim.wav -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest test_merged_epoch22.mp4"
|
|
# cmd = "ffmpeg -y -r 50 -f image2 -i test_concat_epoch22/frame-%06d.jpg -i audio/audio_trim.wav -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest test_concat_epoch22.mp4"
|
|
|
|
# ffmpeg -i gan_model_epoch22.mp4 -i audio/audio_trim.wav -map 0:v -map 1:a -c:v copy -shortest gan_model_epoch22_audio.mp4
|
|
|
|
# cmd = "ffmpeg -y -r 50 -f image2 -i test_gan_model_epoch23/frame-%06d.jpg -vcodec libx264 -pix_fmt yuv420p gan_model_concat_epoch22.mp4"
|
|
# ffmpeg -i gan_model_concat_epoch22.mp4 -i audio/audio_trim.wav -map 0:v -map 1:a -c:v copy -shortest gan_model_concat_epoch22_audio.mp4
|
|
|
|
|
|
def on_epoch_end(self):
|
|
# reset metrics at the end of every epoch
|
|
self.train_rec.reset()
|
|
self.valid_rec.reset()
|
|
|
|
|
|
def get_progress_bar_dict(self):
|
|
# don't show the version number
|
|
items = super().get_progress_bar_dict() # "v_num", "loss"
|
|
items.pop("v_num", None)
|
|
# logging.info(items)
|
|
# items["loss"] = '{:0.4f}'.format(float(items["loss"]))
|
|
|
|
return items
|
|
|
|
|
|
def tensor2image(self, image):
|
|
# image = tensor.detach().cpu().numpy()
|
|
# image = tensor.numpy()
|
|
|
|
image = image*255.
|
|
image = np.maximum(np.minimum(image, 255), 0)
|
|
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
|
|
|
return image.astype(np.uint8).copy()
|
|
|