initial commit
This commit is contained in:
commit
c7175dd7ff
127 files changed
+13949
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
experiments
|
||||||
|
|
||||||
|
**/__pycache__
|
||||||
|
**/*.pyc
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Audio2Expression
|
||||||
|
|
||||||
|
|
||||||
|
### Setup
|
||||||
|
- python 3
|
||||||
|
- pytorch
|
||||||
|
- opencv-python
|
||||||
|
- libsora
|
||||||
|
|
||||||
|
|
||||||
|
### Train
|
||||||
|
```
|
||||||
|
python train.py --opt experiments/train-atc-GRID-with-auto-regression-geo-weight.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
- set model
|
||||||
|
- MODEL.name = "audio2exp" # audio2exp_model.py
|
||||||
|
- MODEL.name_netAE = "ATC_REC" # ATC network with autoregression
|
||||||
|
- dim_input: 0 # 68*2
|
||||||
|
- dim_output: 79 # 68*2
|
||||||
|
- dim_latent: 32
|
||||||
|
|
||||||
|
- set pretrain
|
||||||
|
- MODEL.pretrain = True
|
||||||
|
- MODEL.path_pretrained: "/mnt/data/CODE/Audio2Expression/experiments/ATC/GRID/train-atc-GRID-with-auto-regression-geo-weight/20201211-16H02M39S"
|
||||||
|
- MODEL.load_epoch = 3000
|
||||||
|
|
||||||
|
- set resume:
|
||||||
|
- MODEL.resume = True
|
||||||
|
- MODEL.epoch_begin = 0
|
||||||
|
- MODEL.epoch_end = 10000
|
||||||
|
|
||||||
|
- set loss
|
||||||
|
- lambda_rec: 10
|
||||||
|
- lambda_geo: 1
|
||||||
|
- lambda_smooth_rec: 0
|
||||||
|
- lambda_smooth_geo: 0
|
||||||
|
|
||||||
|
|
||||||
|
### Test
|
||||||
|
```
|
||||||
|
# processing data
|
||||||
|
python scripts/Test/run-10-processing.py
|
||||||
|
|
||||||
|
# infer coeff
|
||||||
|
python infer.py --opt experiments/infer-atc-GRID-with-auto-regression.yaml
|
||||||
|
|
||||||
|
# render and output video
|
||||||
|
python scripts/frames-to-video.py
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Evaluation
|
||||||
|
```
|
||||||
|
python infer_paper2.py --opt experiments/MotionGlow/train_MotionWavaFlow22.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Whitespace-only changes.
@@ -0,0 +1,234 @@
|
|||||||
|
import moviepy.editor as mpy
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
|
||||||
|
from common.landmark import landmark_to_images
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation(data_motion, path_save, suffix, w=128*5, h=72*5, dpi=80):
|
||||||
|
""" convert data_motion to .mp4 animation
|
||||||
|
data_motion, shape [B, N, 136, ...]
|
||||||
|
"""
|
||||||
|
# no need invert
|
||||||
|
# anim_clips = inv_standardize(data_motion[:self.nseq_test, :, :], self.motion_scaler)
|
||||||
|
fps = 30
|
||||||
|
B, *_ = data_motion.shape
|
||||||
|
|
||||||
|
for i in range(B):
|
||||||
|
idata_pt = data_motion[i, :, :].reshape(-1, 68, 2)
|
||||||
|
images_pt = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex="PT")
|
||||||
|
|
||||||
|
duration = idata_pt.shape[0] / fps
|
||||||
|
# animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) - 1,...], duration= duration )
|
||||||
|
animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5),...], duration= duration )
|
||||||
|
|
||||||
|
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||||
|
animation.write_videofile(str(ipath_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation_ws_audio(data_motion, path_save, path_audio=None, start_time=None, end_time=None, fps=30, w=256, h=256, dpi=150):
|
||||||
|
""" convert data_motion to .mp4 animation
|
||||||
|
data_motion, shape [nsteps, 136]
|
||||||
|
"""
|
||||||
|
|
||||||
|
# fps = 30
|
||||||
|
nsteps = data_motion.shape[0]
|
||||||
|
|
||||||
|
data_motion = data_motion.copy().reshape(nsteps, 68, 2) # nsteps x 68 x 2
|
||||||
|
image = landmark_to_images(data_motion, w=w, h=h, dpi=dpi, norm=True, prex="PT") # (nsteps, H, W, 3)
|
||||||
|
|
||||||
|
duration = nsteps / fps
|
||||||
|
animation = mpy.VideoClip(lambda t: image[int(fps * t + 0.5),...], duration= duration )
|
||||||
|
duration = animation.duration
|
||||||
|
|
||||||
|
if path_audio is not None:
|
||||||
|
audioclip = mpy.AudioFileClip(str(path_audio))
|
||||||
|
|
||||||
|
# cut-off
|
||||||
|
if (start_time is not None) and (end_time is not None):
|
||||||
|
audioclip = audioclip.subclip(start_time, end_time)
|
||||||
|
|
||||||
|
# alignment to video
|
||||||
|
audioclip = audioclip.set_duration(duration)
|
||||||
|
|
||||||
|
# add audio to animation
|
||||||
|
animation = animation.set_audio(audioclip)
|
||||||
|
animation = animation.set_duration(duration)
|
||||||
|
# save
|
||||||
|
animation.write_videofile(str(path_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation_grid(data_motion, path_save, path_audio=None, start_time=None, end_time=None, ncol=3, w=128*5, h=72*5, dpi=80):
|
||||||
|
""" convert data_motion to .mp4 animation
|
||||||
|
data_motion, shape [N, nsteps, 136]
|
||||||
|
"""
|
||||||
|
# no need invert
|
||||||
|
# anim_clips = inv_standardize(data_motion[:self.nseq_test, :, :], self.motion_scaler)
|
||||||
|
fps = 30
|
||||||
|
N, nsteps, _ = data_motion.shape
|
||||||
|
|
||||||
|
total_image = []
|
||||||
|
for i in range(N):
|
||||||
|
idata_pt = data_motion[i, :, :].reshape(-1, 68, 2) # nsteps x 68 x 2
|
||||||
|
prex = "ground-truth" if i == 0 else f"prediction-{i-0:02d}"
|
||||||
|
image = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex=prex) # (nsteps, H, W, 3)
|
||||||
|
total_image.append(image)
|
||||||
|
print(f"images shape = {image.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
total_image = np.concatenate(total_image, axis=0) # N x nsteps x H x W x 3
|
||||||
|
total_image = total_image.reshape(N//ncol, ncol, nsteps, h, w, 3)
|
||||||
|
|
||||||
|
total_image = total_image.transpose((2, 0, 3, 1, 4, 5)) # nsteps x nrow x H x ncol x W x 3
|
||||||
|
total_image = total_image.reshape(nsteps, -1, ncol*w, 3) # nsteps x nrow*H x ncol*W x 3
|
||||||
|
print(f"total images shape = {total_image.shape}")
|
||||||
|
|
||||||
|
duration = nsteps / fps
|
||||||
|
animation = mpy.VideoClip(lambda t: total_image[int(fps * t + 0.5),...], duration= duration )
|
||||||
|
# animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) ,...], duration= duration )
|
||||||
|
duration = animation.duration
|
||||||
|
|
||||||
|
if path_audio is not None:
|
||||||
|
audioclip = mpy.AudioFileClip(str(path_audio))
|
||||||
|
|
||||||
|
# cut-off
|
||||||
|
if (start_time is not None) and (end_time is not None):
|
||||||
|
audioclip = audioclip.cutout(start_time, end_time)
|
||||||
|
|
||||||
|
# alignment to video
|
||||||
|
audioclip = audioclip.set_duration(duration)
|
||||||
|
|
||||||
|
# add audio to animation
|
||||||
|
animation = animation.set_audio(audioclip)
|
||||||
|
animation = animation.set_duration(duration)
|
||||||
|
|
||||||
|
# save
|
||||||
|
animation.write_videofile(str(path_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation2(images, path_save):
|
||||||
|
fps = 30
|
||||||
|
duration = len(images) / fps
|
||||||
|
animation = mpy.VideoClip(lambda t: images[int(fps * t + 0.5) - 1], duration= duration )
|
||||||
|
animation.write_videofile(str(path_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation_with_gts(images_list, path_save):
|
||||||
|
""" convert images_pt to .mp4 animation
|
||||||
|
images_pt, shape len=N list [224, 224, 3]
|
||||||
|
images_gt, shape len=N list [224, 224, 3]
|
||||||
|
"""
|
||||||
|
# print(f"images_pt shape = {len(images_list[0])}, shape[0]={images_pt[0].shape}")
|
||||||
|
|
||||||
|
fps = 30
|
||||||
|
N = len(images_list[0])
|
||||||
|
duration = N / fps
|
||||||
|
print(f"fps = {fps}, N ={N}, duration={duration}")
|
||||||
|
|
||||||
|
# assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})"
|
||||||
|
animations = []
|
||||||
|
for images in images_list:
|
||||||
|
animations.append(mpy.VideoClip(lambda t: images[int(fps * t + 0.5) -1], duration= duration))
|
||||||
|
|
||||||
|
# mixture & save
|
||||||
|
animation = mpy.clips_array([animations])
|
||||||
|
animation.write_videofile(str(path_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
def save_images_with_audio(images, path_audio, path_save):
|
||||||
|
""" convert images_pt to .mp4 animation
|
||||||
|
images_pt, shape len=N list [224, 224, 3]
|
||||||
|
images_gt, shape len=N list [224, 224, 3]
|
||||||
|
"""
|
||||||
|
|
||||||
|
N = len(images)
|
||||||
|
|
||||||
|
# load audio
|
||||||
|
audioclip = mpy.AudioFileClip(str(path_audio))
|
||||||
|
duration = audioclip.duration
|
||||||
|
|
||||||
|
# add video
|
||||||
|
fps = N / duration
|
||||||
|
animation = mpy.VideoClip(lambda t: images[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
animation = animation.set_audio(audioclip) # add audio to animation
|
||||||
|
|
||||||
|
# save
|
||||||
|
animation.write_videofile(str(path_save), fps=fps)
|
||||||
|
print(f"fps = {fps}, N ={N}, duration={duration} -> save to = {path_save}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation_with_gt5(images_pt, images_gt, images_A, images_B, images_C, path_save):
|
||||||
|
""" convert images_pt to .mp4 animation
|
||||||
|
images_pt, shape len=N list [224, 224, 3]
|
||||||
|
images_gt, shape len=N list [224, 224, 3]
|
||||||
|
"""
|
||||||
|
# print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}")
|
||||||
|
fps = 30
|
||||||
|
N = len(images_pt)
|
||||||
|
duration = N / fps
|
||||||
|
# print(f"fps = {fps}, N ={N}, duration={duration}")
|
||||||
|
|
||||||
|
# assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})"
|
||||||
|
animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
animation_A = mpy.VideoClip(lambda t: images_A[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
animation_B = mpy.VideoClip(lambda t: images_B[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
animation_C = mpy.VideoClip(lambda t: images_C[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
|
||||||
|
# mixture & save
|
||||||
|
animation = mpy.clips_array([[animation_pt, animation_gt, animation_A, animation_B, animation_C]])
|
||||||
|
animation.write_videofile(str(path_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation_with_gt2(images_pt, images_gt, path_save):
|
||||||
|
""" convert images_pt to .mp4 animation
|
||||||
|
images_pt, shape len= N list [224, 224, 3]
|
||||||
|
images_gt, shape len= N list [224, 224, 3]
|
||||||
|
"""
|
||||||
|
# print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}")
|
||||||
|
|
||||||
|
fps = 30
|
||||||
|
N = len(images_pt)
|
||||||
|
duration = N / fps
|
||||||
|
# print(f"fps = {fps}, N ={N}, duration={duration}")
|
||||||
|
|
||||||
|
# assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})"
|
||||||
|
animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5) -1], duration= duration)
|
||||||
|
|
||||||
|
# mixture & save
|
||||||
|
animation = mpy.clips_array([[animation_pt, animation_gt]])
|
||||||
|
animation.write_videofile(str(path_save), fps=fps)
|
||||||
|
|
||||||
|
|
||||||
|
def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3):
|
||||||
|
""" convert data_motion to .mp4 animation
|
||||||
|
data_motion, shape [B, N, 68, 2]
|
||||||
|
data_motion_gt, shape [B, N, 68, 2]
|
||||||
|
"""
|
||||||
|
fps = 30
|
||||||
|
B, *_ = data_motion.shape
|
||||||
|
B = min(B, maxsave)
|
||||||
|
|
||||||
|
for i in range(B):
|
||||||
|
idata_pt = data_motion[i].reshape(-1, 68, 2)
|
||||||
|
idata_gt = data_motion_gt[i].reshape(-1, 68, 2)
|
||||||
|
|
||||||
|
images_pt = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex="PT")
|
||||||
|
images_gt = landmark_to_images(idata_gt, w=w, h=h, dpi=dpi, norm=True, prex="GT")
|
||||||
|
|
||||||
|
duration = idata_pt.shape[0] / fps
|
||||||
|
# animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) - 1,...], duration= duration )
|
||||||
|
animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5),...], duration= duration)
|
||||||
|
animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5),...], duration= duration)
|
||||||
|
|
||||||
|
# mixture
|
||||||
|
animation = mpy.clips_array([[animation_pt, animation_gt]])
|
||||||
|
|
||||||
|
|
||||||
|
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||||
|
animation.write_videofile(str(ipath_save), fps=fps, logger=None)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
|
||||||
|
def debug(opt, msg, verbose=False):
|
||||||
|
if opt.DEBUG or verbose:
|
||||||
|
print(msg)
|
||||||
|
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""
|
||||||
|
This utils for geometry transform and carera projection
|
||||||
|
"""
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
import render_util
|
||||||
|
|
||||||
|
def euler2rot(euler):
|
||||||
|
"""Convert euler to rotation matrix
|
||||||
|
params:
|
||||||
|
euler: torch.Tensor, (nbatch, 3)
|
||||||
|
return:
|
||||||
|
rotation matrix, torch.Tensor, (nbtach, 3, 3)
|
||||||
|
"""
|
||||||
|
batch_size = euler.shape[0]
|
||||||
|
theta = euler[:, 0].reshape(-1, 1, 1)
|
||||||
|
phi = euler[:, 1].reshape(-1, 1, 1)
|
||||||
|
psi = euler[:, 2].reshape(-1, 1, 1)
|
||||||
|
ones = torch.ones((batch_size, 1, 1), dtype=torch.float32, device=euler.device)
|
||||||
|
zero = torch.zeros((batch_size, 1, 1), dtype=torch.float32, device=euler.device)
|
||||||
|
|
||||||
|
rot_x = torch.cat(( # (nbatch, 3, 3)
|
||||||
|
torch.cat((ones, zero, zero), 1), #(nbatch, 3, 1)
|
||||||
|
torch.cat((zero, theta.cos(), theta.sin()), 1), #(nbatch, 3, 1)
|
||||||
|
torch.cat((zero, -theta.sin(), theta.cos()), 1), #(nbatch, 3, 1)
|
||||||
|
), 2)
|
||||||
|
|
||||||
|
rot_y = torch.cat((
|
||||||
|
torch.cat((phi.cos(), zero, -phi.sin()), 1),
|
||||||
|
torch.cat((zero, ones, zero), 1),
|
||||||
|
torch.cat((phi.sin(), zero, phi.cos()), 1),
|
||||||
|
), 2)
|
||||||
|
|
||||||
|
rot_z = torch.cat((
|
||||||
|
torch.cat((psi.cos(), -psi.sin(), zero), 1),
|
||||||
|
torch.cat((psi.sin(), psi.cos(), zero), 1),
|
||||||
|
torch.cat((zero, zero, ones), 1)
|
||||||
|
), 2)
|
||||||
|
|
||||||
|
rot = torch.bmm(rot_x, torch.bmm(rot_y, rot_z)) # (nbatch, 3, 3)
|
||||||
|
|
||||||
|
return rot
|
||||||
|
|
||||||
|
|
||||||
|
def geo_rotation_transfrom(geo, rot, trans=None):
|
||||||
|
""" rotation geometry and trans
|
||||||
|
params:
|
||||||
|
geo: geometry, torch.Tensor, (nbatch, N, 3)
|
||||||
|
rot: rotation matrix, torch.Tensor, (nbatch, 3, 3)
|
||||||
|
trans: transform matrix, torch.Tensor, (nbtach, 3)
|
||||||
|
return:
|
||||||
|
geometry, torch.Tensor, (nbatch, N, 3)
|
||||||
|
"""
|
||||||
|
# rotation
|
||||||
|
geo = torch.bmm(rot, geo.permute(0, 2, 1)) # (nbatch, 3, N)
|
||||||
|
|
||||||
|
# transform
|
||||||
|
if trans is not None:
|
||||||
|
geo += trans.view(-1, 3, 1)
|
||||||
|
|
||||||
|
geo = geo.permute(0, 2, 1)
|
||||||
|
return geo
|
||||||
|
|
||||||
|
|
||||||
|
def geo_projection(geo, param_camera):
|
||||||
|
"""project geo to 2D plane
|
||||||
|
params:
|
||||||
|
geo, geometry, torch.Tensor, (nbatch, N, 3)
|
||||||
|
param_camera: torch.Tensor, (nbatch, 4)
|
||||||
|
return:
|
||||||
|
geometry, torch.Tensor, (nbatch, N, 3)
|
||||||
|
"""
|
||||||
|
|
||||||
|
fx, fy = param_camera[:, 0], param_camera[:, 1] # (nbatch, )
|
||||||
|
cx, cy = param_camera[:, 2], param_camera[:, 3] # (nbatch, )
|
||||||
|
|
||||||
|
X, Y, Z = geo[:, :, 0], geo[:, :, 1], geo[:, :, 2] # (nbatch, N)
|
||||||
|
|
||||||
|
fxX = fx[:, None] * X # (nbatch, N)
|
||||||
|
fyY = fy[:, None] * Y # (nbatch, N)
|
||||||
|
|
||||||
|
proj_x = -fxX / Z + cx[:, None] # (nbatch, N)
|
||||||
|
proj_y = fyY / Z + cy[:, None]
|
||||||
|
|
||||||
|
geo_pro = torch.cat([proj_x, proj_y, Z], 2)
|
||||||
|
|
||||||
|
return geo_pro
|
||||||
|
|
||||||
|
|
||||||
|
def landmark_projection(geo, ldmk_info, ldmk_num=68):
|
||||||
|
"""Landmark Projection
|
||||||
|
|
||||||
|
params:
|
||||||
|
geo, geometry, torch.Tensor, (nbatch, N, 3)
|
||||||
|
ldmk_info, torch.Tensor, (68,)
|
||||||
|
ldmk_num, int, the number of landmarks, default=68
|
||||||
|
|
||||||
|
return:
|
||||||
|
projection landmark, (nbatch, 68, 2)
|
||||||
|
"""
|
||||||
|
n_points = geo.shape[0]
|
||||||
|
|
||||||
|
rot_tri_normal = compute_tri_normal(geo_rot, self.tris)
|
||||||
|
rot_ver_normal = torch.index_select(rot_tri_normal, 1, self.vert_tris)
|
||||||
|
|
||||||
|
|
||||||
|
is_visible = -torch.bmm(rot_ver_normal.reshape(-1, 1, 3), geo_rot.reshape(-1, 3, 1))
|
||||||
|
is_visible = is_visible.reshape(-1, n_points)
|
||||||
|
|
||||||
|
|
||||||
|
ldmk_idx = render_util.update_contour(ldmk_info, is_visible, ldmk_num)
|
||||||
|
print(f"DEBUG: landmark projection, ldmk_num={ldmk_num}, update contour, ldmk_idx len={ldmk_idx.shape}, should be (Nbatch * 68)")
|
||||||
|
|
||||||
|
ldmk_pro = torch.index_select(geo.reshape(-1, 3), 0, ldmk_idx) # (len(ldmk_idx), 3)
|
||||||
|
ldmk_pro = ldmk_pro[:, :2].reshape(-1, ldmk_num, 2) # (nbatch, ldmk_num, 2)
|
||||||
|
|
||||||
|
return ldmk_pro
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import os
|
||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
def tensor2im(input_image, imtype=np.uint8):
|
||||||
|
""""Converts a Tensor array into a numpy image array.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
input_image (tensor) -- the input image tensor array
|
||||||
|
imtype (type) -- the desired type of the converted numpy array
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(input_image, np.ndarray):
|
||||||
|
if isinstance(input_image, torch.Tensor): # get the data from a variable
|
||||||
|
image_tensor = input_image.data
|
||||||
|
else:
|
||||||
|
return input_image
|
||||||
|
|
||||||
|
image_numpy = image_tensor[0].cpu().float().numpy() # convert it into a numpy array
|
||||||
|
|
||||||
|
if image_numpy.shape[0] == 1: # grayscale to RGB
|
||||||
|
image_numpy = np.tile(image_numpy, (3, 1, 1))
|
||||||
|
|
||||||
|
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 # post-processing: tranpose and scaling
|
||||||
|
|
||||||
|
else: # if it is a numpy array, do nothing
|
||||||
|
image_numpy = input_image
|
||||||
|
|
||||||
|
return image_numpy.astype(imtype)
|
||||||
|
|
||||||
|
|
||||||
|
def save_image(image_numpy, image_path):
|
||||||
|
"""Save a numpy image to the disk
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
image_numpy (numpy array) -- input numpy array
|
||||||
|
image_path (str) -- the path of the image
|
||||||
|
"""
|
||||||
|
image_pil = Image.fromarray(image_numpy)
|
||||||
|
image_pil.save(image_path)
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
import os
|
||||||
|
import cv2
|
||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from matplotlib import pyplot as plt
|
||||||
|
plt.rcParams['axes.facecolor'] = 'black'
|
||||||
|
|
||||||
|
def landmark_normalize(ldmk):
|
||||||
|
# ldmk shape = (68, 2)
|
||||||
|
|
||||||
|
pos_mean = np.mean(ldmk, axis=0) # (2, )
|
||||||
|
pos_max = np.max(ldmk, axis=0) # (2, )
|
||||||
|
pos_min = np.min(ldmk, axis=0) # (2, )
|
||||||
|
|
||||||
|
side = int(1.5 * np.max(pos_max - pos_min)) # (1, )
|
||||||
|
# print(f"landmarks = {ldmk[::10, :]}, \n mean={pos_mean}, max={pos_max}, min={pos_min}, side={side}")
|
||||||
|
|
||||||
|
tran = pos_mean - 0.5 * side # (2, )
|
||||||
|
ldmk_tran = ldmk - tran[np.newaxis, :] # (68, 2)
|
||||||
|
ldmk_norm = ldmk_tran / side # (68, 2)
|
||||||
|
# print(f"ldmk_tran = {ldmk_tran[::10, :]}, \n ldmk_tran = {ldmk_norm[::10, :]}")
|
||||||
|
|
||||||
|
return ldmk_norm, pos_mean, side
|
||||||
|
|
||||||
|
|
||||||
|
def landmark_normalize_by_param(ldmk, params):
|
||||||
|
# ldmk shape = (B, 68, 2)
|
||||||
|
# params shape = (B, 3)
|
||||||
|
|
||||||
|
pos_mean = params[:, 0:2 ] # (B, 2)
|
||||||
|
pos_mean = pos_mean[:, np.newaxis, :] # (B, 1, 2)
|
||||||
|
side = params[:, 2:] # (B, 2)
|
||||||
|
side = side[:, np.newaxis, :] # (B, 1, 2)
|
||||||
|
|
||||||
|
tran = pos_mean - 0.5 * side # (B, 1, 2)
|
||||||
|
ldmk_norm = (ldmk - tran) / side # (B, 68, 2)
|
||||||
|
|
||||||
|
return ldmk_norm
|
||||||
|
|
||||||
|
def landmark_to_images(ldmks, w=256, h=256, dpi=100, norm=True, prex=""):
|
||||||
|
# landmarks shape = (nbatch, 68, 2)
|
||||||
|
nframe = ldmks.shape[0]
|
||||||
|
|
||||||
|
v_images = []
|
||||||
|
for i in range(nframe):
|
||||||
|
ildmk = ldmks[i, :, :]
|
||||||
|
if prex is not None:
|
||||||
|
text = f"{prex}-frame-{i:04d}"
|
||||||
|
else:
|
||||||
|
text = None
|
||||||
|
|
||||||
|
v_images.append(landmark_to_image(ildmk, w, h, dpi, norm, text))
|
||||||
|
|
||||||
|
return np.asarray(v_images)
|
||||||
|
|
||||||
|
|
||||||
|
def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None):
|
||||||
|
# landmarks shape = (68, 2)
|
||||||
|
|
||||||
|
if norm:
|
||||||
|
ildmk[:, 0] = w - ildmk[:, 0] * w
|
||||||
|
ildmk[:, 1] = h - ildmk[:, 1] * h
|
||||||
|
|
||||||
|
else:
|
||||||
|
# ildmk[:, 0] = w - ildmk[:, 0]
|
||||||
|
ildmk[:, 1] = h - ildmk[:, 1]
|
||||||
|
|
||||||
|
if isinstance(ildmk, torch.Tensor):
|
||||||
|
ildmk = ildmk.cpu().numpy()
|
||||||
|
|
||||||
|
# plot
|
||||||
|
fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi)
|
||||||
|
fig.patch.set_facecolor('w')
|
||||||
|
|
||||||
|
ax = fig.add_subplot(1,1,1)
|
||||||
|
# ax.imshow(np.zeros(shape=(w, h)))
|
||||||
|
|
||||||
|
ax.set_facecolor('m')
|
||||||
|
# plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
|
||||||
|
# ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1)
|
||||||
|
ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1)
|
||||||
|
ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1)
|
||||||
|
ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1)
|
||||||
|
ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1)
|
||||||
|
ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1)
|
||||||
|
ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1)
|
||||||
|
ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1)
|
||||||
|
|
||||||
|
#chin
|
||||||
|
ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1)
|
||||||
|
|
||||||
|
#left and right eyebrow
|
||||||
|
ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
|
||||||
|
ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
|
||||||
|
|
||||||
|
#nose
|
||||||
|
ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
|
||||||
|
ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
|
||||||
|
|
||||||
|
#left and right eye
|
||||||
|
ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
|
||||||
|
ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
|
||||||
|
#outer and inner lip
|
||||||
|
ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
|
||||||
|
|
||||||
|
ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
|
||||||
|
|
||||||
|
ax.set_xlim(0, w)
|
||||||
|
ax.set_ylim(0, h)
|
||||||
|
ax.axis('off')
|
||||||
|
|
||||||
|
if text is not None:
|
||||||
|
ax.text(2, 2, text)
|
||||||
|
|
||||||
|
fig.canvas.draw()
|
||||||
|
w, h = fig.canvas.get_width_height()
|
||||||
|
|
||||||
|
buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
||||||
|
buffer = buffer.reshape((h, w, 3))
|
||||||
|
image = np.asarray(buffer)
|
||||||
|
# print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}")
|
||||||
|
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
return image
|
||||||
|
|
||||||
|
# def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None):
|
||||||
|
# # landmarks shape = (68, 2)
|
||||||
|
|
||||||
|
# if norm:
|
||||||
|
# ildmk = w - ildmk * w
|
||||||
|
# else:
|
||||||
|
# ildmk[:, 1] = h - ildmk[:, 1]
|
||||||
|
|
||||||
|
# if isinstance(ildmk, torch.Tensor):
|
||||||
|
# ildmk = ildmk.cpu().numpy()
|
||||||
|
|
||||||
|
# # plot
|
||||||
|
# fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi)
|
||||||
|
# fig.patch.set_facecolor('w')
|
||||||
|
|
||||||
|
# ax = fig.add_subplot(1,1,1)
|
||||||
|
# # ax.imshow(np.zeros(shape=(w, h)))
|
||||||
|
|
||||||
|
# ax.set_facecolor('m')
|
||||||
|
# # plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
|
||||||
|
# # ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1)
|
||||||
|
# ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1)
|
||||||
|
# ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1)
|
||||||
|
# ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1)
|
||||||
|
# ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1)
|
||||||
|
# ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1)
|
||||||
|
# ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1)
|
||||||
|
# ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1)
|
||||||
|
|
||||||
|
# #chin
|
||||||
|
# ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# #left and right eyebrow
|
||||||
|
# ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
|
||||||
|
# ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# #nose
|
||||||
|
# ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
|
||||||
|
# ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# #left and right eye
|
||||||
|
# ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
# ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
# ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# #outer and inner lip
|
||||||
|
# ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
# ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
|
||||||
|
# ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
|
||||||
|
|
||||||
|
# ax.set_xlim(0, w)
|
||||||
|
# ax.set_ylim(0, h)
|
||||||
|
# ax.axis('off')
|
||||||
|
|
||||||
|
# if text is not None:
|
||||||
|
# ax.text(10, 10, text)
|
||||||
|
|
||||||
|
# fig.canvas.draw()
|
||||||
|
# w, h = fig.canvas.get_width_height()
|
||||||
|
|
||||||
|
# buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
||||||
|
# buffer = buffer.reshape((h, w, 3))
|
||||||
|
# image = np.asarray(buffer)
|
||||||
|
# # print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}")
|
||||||
|
|
||||||
|
# plt.close(fig)
|
||||||
|
|
||||||
|
# return image
|
||||||
|
|
||||||
|
def landmark_to_mask(ildmk, w=256, h=256, dpi=100, norm=True):
|
||||||
|
# landmarks shape = (68, 2)
|
||||||
|
# print(f"landmark data shape = {ildmk.shape}")
|
||||||
|
if norm:
|
||||||
|
ildmk = ildmk * w
|
||||||
|
|
||||||
|
# plot
|
||||||
|
fig = plt.figure(figsize=(h/dpi, w/dpi), dpi=dpi)
|
||||||
|
ax = fig.add_subplot(1,1,1)
|
||||||
|
|
||||||
|
# ax.imshow(np.ones(shape=(w, h)))
|
||||||
|
# plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
|
||||||
|
|
||||||
|
#chin
|
||||||
|
ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='green', lw=2)
|
||||||
|
#left and right eyebrow
|
||||||
|
ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='orange', lw=2)
|
||||||
|
ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='orange', lw=2)
|
||||||
|
#nose
|
||||||
|
ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2)
|
||||||
|
ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2)
|
||||||
|
#left and right eye
|
||||||
|
ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='red', lw=2)
|
||||||
|
ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='red', lw=2)
|
||||||
|
#outer and inner lip
|
||||||
|
ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='purple', lw=2)
|
||||||
|
ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='pink', lw=2)
|
||||||
|
ax.axis('off')
|
||||||
|
|
||||||
|
|
||||||
|
fig.canvas.draw()
|
||||||
|
|
||||||
|
|
||||||
|
buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
||||||
|
# buffer.shape = (w, h, 4)
|
||||||
|
|
||||||
|
image = buffer.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
||||||
|
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
LANDMARK_TARGET = 'multi_channel'
|
||||||
|
MIN_LANDMARK_CONF = 0.8
|
||||||
|
|
||||||
|
LANDMARK_OCULAR_NORM = 'outer'
|
||||||
|
PREDICT_HEATMAP = True
|
||||||
|
HEATMAP_SIZE = 128
|
||||||
|
|
||||||
|
LANDMARKS_6 = [36, 39, 42, 45, 48, 54]
|
||||||
|
LANDMARKS_9 = [30, 36, 39, 42, 45, 48, 51, 54, 57]
|
||||||
|
LANDMARKS_12 = [21, 22, 27, 30, 36, 39, 42, 45, 48, 51, 54, 57]
|
||||||
|
LANDMARKS_19 = [0, 4, 8, 12, 16, 17, 21, 22, 26, 27, 30, 36, 39, 42, 45, 48, 51, 54, 57]
|
||||||
|
LANDMARKS_22 = [0, 4, 8, 12, 16, 17, 21, 22, 26, 27, 28, 29, 30, 36, 39, 42, 45, 48, 51, 54, 57]
|
||||||
|
LANDMARKS_14 = [17, 26, 21, 22, 27, 30, 36, 39, 42, 45, 48, 51, 54, 57]
|
||||||
Whitespace-only changes.
@@ -0,0 +1,135 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
|
# target, torch.Tensor, (Bx2x16, 68, 2)
|
||||||
|
def get_mouth_width(landmark):
|
||||||
|
""" Get mouth width between L48 and L54
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
tensor, (N,)
|
||||||
|
"""
|
||||||
|
|
||||||
|
WM = (landmark[:, 48, :] - landmark[:, 54, :]) * (landmark[:, 48, :] - landmark[:, 54, :]) # (N, 2)
|
||||||
|
WM = torch.sqrt(WM[:, 0] + WM[:, 1])
|
||||||
|
|
||||||
|
return WM
|
||||||
|
|
||||||
|
def get_mouth_open_param(landmark, eps=1e-6):
|
||||||
|
""" Get mouth open distance and rate
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
two tensors: lip distance and open rate (N,), (N, )
|
||||||
|
"""
|
||||||
|
up = 0.5 * (landmark[:, 50, :] + landmark[:, 52, :])
|
||||||
|
dw = 0.5 * (landmark[:, 56, :] + landmark[:, 58, :])
|
||||||
|
|
||||||
|
distance = (up - dw) * (up -dw) # (N, 2)
|
||||||
|
distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, )
|
||||||
|
width = get_mouth_width(landmark)
|
||||||
|
rate = distance / (width + eps)
|
||||||
|
rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1
|
||||||
|
|
||||||
|
# assert torch.any(torch.isnan(rate)), f"rate have nan"
|
||||||
|
|
||||||
|
# if torch.any(torch.isnan(rate)) or torch.any(torch.isinf(rate)) :
|
||||||
|
# # print("KKKKKK,",rate)
|
||||||
|
# for i, item in enumerate(rate):
|
||||||
|
# if torch.isnan(item) or torch.isinf(item):
|
||||||
|
# print(f"error mouth nan, item = {item} distance = {distance[i]}, width={width[i]}, data = {landmark[i, [50,52,56,58]]}")
|
||||||
|
|
||||||
|
|
||||||
|
return distance, rate
|
||||||
|
|
||||||
|
|
||||||
|
def get_eye_width(landmark):
|
||||||
|
""" Get left eye width between L36 and L39, and right eye width between L42 and L45
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
two tensor of left and right eye width , (N,), (N,)
|
||||||
|
"""
|
||||||
|
return get_left_eye_width(landmark), get_right_eye_width(landmark)
|
||||||
|
|
||||||
|
def get_left_eye_width(landmark):
|
||||||
|
""" Get left eye width between L36 and L39, and right eye width between L42 and L45
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
two tensor of left and right eye width , (N,), (N,)
|
||||||
|
"""
|
||||||
|
|
||||||
|
WL = (landmark[:, 36, :] - landmark[:, 39, :]) * (landmark[:, 36, :] - landmark[:, 39, :]) # (N, 2)
|
||||||
|
WL = torch.sqrt(WL[:, 0] + WL[:, 1])
|
||||||
|
|
||||||
|
return WL
|
||||||
|
|
||||||
|
|
||||||
|
def get_right_eye_width(landmark):
|
||||||
|
""" Get left eye width between L36 and L39, and right eye width between L42 and L45
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
two tensor of left and right eye width , (N,), (N,)
|
||||||
|
"""
|
||||||
|
WR = (landmark[:, 42, :] - landmark[:, 45, :]) * (landmark[:, 42, :] - landmark[:, 45, :]) # (N, 2)
|
||||||
|
WR = torch.sqrt(WR[:, 0] + WR[:, 1])
|
||||||
|
|
||||||
|
return WR
|
||||||
|
|
||||||
|
|
||||||
|
def get_eye_open_param(landmark):
|
||||||
|
""" Get left/right eye open distance and rate
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
four tensors: left/right eye distance and open rate (N,), (N, )
|
||||||
|
"""
|
||||||
|
L_dist, L_rate = get_left_eye_open_param(landmark)
|
||||||
|
R_dist, R_rate = get_right_eye_open_param(landmark)
|
||||||
|
|
||||||
|
return L_dist, L_rate, R_dist, R_rate
|
||||||
|
|
||||||
|
def get_left_eye_open_param(landmark, eps=1e-6):
|
||||||
|
""" Get left eye open distance and rate
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
four tensors: left eye distance and open rate (N,), (N, )
|
||||||
|
"""
|
||||||
|
up = 0.5 * (landmark[:, 37, :] + landmark[:, 38, :])
|
||||||
|
dw = 0.5 * (landmark[:, 40, :] + landmark[:, 41, :])
|
||||||
|
|
||||||
|
distance = (up - dw) * (up -dw) # (N, 2)
|
||||||
|
distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, )
|
||||||
|
width = get_left_eye_width(landmark)
|
||||||
|
|
||||||
|
rate = distance / (width + eps)
|
||||||
|
rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1
|
||||||
|
|
||||||
|
# if torch.any(torch.isnan(rate)) or torch.any(torch.isinf(rate)) :
|
||||||
|
# # print("KKKKKK,",rate)
|
||||||
|
# for i, item in enumerate(rate):
|
||||||
|
# if torch.isnan(item) or torch.isinf(item):
|
||||||
|
# print(f"error eye nan, item = {item} distance = {distance[i]}, width={width[i]}, data = {landmark[i, 37:42]}")
|
||||||
|
|
||||||
|
return distance, rate
|
||||||
|
|
||||||
|
|
||||||
|
def get_right_eye_open_param(landmark, eps = 1e-6):
|
||||||
|
""" Get left eye open distance and rate
|
||||||
|
Params:
|
||||||
|
landmark: torch, (N, 68, 2)
|
||||||
|
Return:
|
||||||
|
four tensors: left eye distance and open rate (N,), (N, )
|
||||||
|
"""
|
||||||
|
up = 0.5 * (landmark[:, 43, :] + landmark[:, 44, :])
|
||||||
|
dw = 0.5 * (landmark[:, 46, :] + landmark[:, 47, :])
|
||||||
|
|
||||||
|
distance = (up - dw) * (up -dw) # (N, 2)
|
||||||
|
distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, )
|
||||||
|
rate = distance / (get_left_eye_width(landmark) + eps)
|
||||||
|
rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1
|
||||||
|
|
||||||
|
return distance, rate
|
||||||
@@ -0,0 +1,516 @@
|
|||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
import landmarks.lmconfig as lmcfg
|
||||||
|
from csl_common.utils.nn import to_numpy, to_image
|
||||||
|
from csl_common.vis import vis
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from skimage.metrics import structural_similarity as compare_ssim
|
||||||
|
import torch
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
layers = []
|
||||||
|
|
||||||
|
outline = range(0, 17)
|
||||||
|
eyebrow_l = range(17, 22)
|
||||||
|
eyebrow_r = range(22, 27)
|
||||||
|
nose = range(27, 31)
|
||||||
|
nostrils = range(31, 36)
|
||||||
|
eye_l = range(36, 42)
|
||||||
|
eye_r = range(42, 48)
|
||||||
|
mouth = range(48, 68)
|
||||||
|
|
||||||
|
components = [outline, eyebrow_l, eyebrow_r, nose, nostrils, eye_l, eye_r, mouth]
|
||||||
|
|
||||||
|
new_layers = []
|
||||||
|
for idx in range(20):
|
||||||
|
lm_ids = []
|
||||||
|
for comp in components[1:]:
|
||||||
|
if len(comp) > idx:
|
||||||
|
lm = comp[idx]
|
||||||
|
lm_ids.append(lm)
|
||||||
|
new_layers.append(lm_ids)
|
||||||
|
|
||||||
|
outline_layers = [[lm] for lm in range(17)]
|
||||||
|
|
||||||
|
layers = components + new_layers + outline_layers
|
||||||
|
|
||||||
|
hm_code_mat = np.zeros((len(layers), 68), dtype=bool)
|
||||||
|
for l, lm_ids in enumerate(layers):
|
||||||
|
hm_code_mat[l, lm_ids] = True
|
||||||
|
|
||||||
|
|
||||||
|
def generate_colors(n, r, g, b, dim):
|
||||||
|
ret = []
|
||||||
|
step = [0,0,0]
|
||||||
|
step[dim] = 256 / n
|
||||||
|
for i in range(n):
|
||||||
|
r += step[0]
|
||||||
|
g += step[1]
|
||||||
|
b += step[2]
|
||||||
|
r = int(r) % 256
|
||||||
|
g = int(g) % 256
|
||||||
|
b = int(b) % 256
|
||||||
|
ret.append((r,g,b))
|
||||||
|
return ret
|
||||||
|
|
||||||
|
_colors = generate_colors(17, 220, 0, 0, 2) + \
|
||||||
|
generate_colors(10, 0, 240, 0, 0) + \
|
||||||
|
generate_colors(9, 0, 0, 230, 1) + \
|
||||||
|
generate_colors(12, 100, 255, 0, 2) + \
|
||||||
|
generate_colors(20, 150, 0, 255, 2)
|
||||||
|
# lmcolors = np.array(_colors)
|
||||||
|
np.random.seed(0)
|
||||||
|
lmcolors = np.random.randint(0,255,size=(68,3))
|
||||||
|
lmcolors = lmcolors / lmcolors.sum(axis=1).reshape(-1,1)*255
|
||||||
|
|
||||||
|
|
||||||
|
def gaussian(x, mean, sigma):
|
||||||
|
return 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x-mean)**2 / (2 * sigma**2))
|
||||||
|
|
||||||
|
|
||||||
|
def make_landmark_template(wnd_size, sigma):
|
||||||
|
X, Y = np.mgrid[-wnd_size//2:wnd_size//2, -wnd_size//2:wnd_size//2]
|
||||||
|
Z = np.sqrt(X**2 + Y**2)
|
||||||
|
N = gaussian(Z, 0, sigma)
|
||||||
|
# return (N/N.max())**2 # square to make sharper
|
||||||
|
return N / N.max()
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_heatmap_layer(dst, lms, lm_id, lm_heatmap_window, wnd_size):
|
||||||
|
posx, posy = min(lms[lm_id,0], lmcfg.HEATMAP_SIZE-1), min(lms[lm_id,1], lmcfg.HEATMAP_SIZE-1)
|
||||||
|
|
||||||
|
img_size = lmcfg.HEATMAP_SIZE
|
||||||
|
l = int(posx - wnd_size/2)
|
||||||
|
t = int(posy - wnd_size/2)
|
||||||
|
r = l + wnd_size
|
||||||
|
b = t + wnd_size
|
||||||
|
|
||||||
|
src_l = max(0, -l)
|
||||||
|
src_t = max(0, -t)
|
||||||
|
src_r = min(wnd_size, wnd_size-(r-img_size))
|
||||||
|
src_b = min(wnd_size, wnd_size-(b-img_size))
|
||||||
|
|
||||||
|
try:
|
||||||
|
cn = lm_id
|
||||||
|
wnd = lm_heatmap_window[src_t:src_b, src_l:src_r]
|
||||||
|
weight = 1.0
|
||||||
|
dst[cn, max(0,t):min(img_size, b), max(0,l):min(img_size, r)] = np.maximum(
|
||||||
|
dst[cn, max(0,t):min(img_size, b), max(0,l):min(img_size, r)], wnd*weight)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def __get_code_mat(num_landmarks):
|
||||||
|
def to_binary(n, ndigits):
|
||||||
|
bits = np.array([bool(int(x)) for x in bin(n)[2:]])
|
||||||
|
assert len(bits) <= ndigits
|
||||||
|
zero_pad_bits = np.zeros(ndigits, dtype=bool)
|
||||||
|
zero_pad_bits[-len(bits):] = bits
|
||||||
|
return zero_pad_bits
|
||||||
|
|
||||||
|
n_enc_layers = int(np.ceil(np.log2(num_landmarks)))
|
||||||
|
|
||||||
|
# get binary code for each heatmap id
|
||||||
|
codes = [to_binary(i+1, ndigits=n_enc_layers) for i in range(num_landmarks)]
|
||||||
|
return np.vstack(codes)
|
||||||
|
|
||||||
|
|
||||||
|
def convert_to_encoded_heatmaps(hms):
|
||||||
|
|
||||||
|
def merge_layers(hms):
|
||||||
|
hms = hms.max(axis=0)
|
||||||
|
return hms/hms.max()
|
||||||
|
|
||||||
|
num_landmarks = len(hms)
|
||||||
|
n_enc_layers = len(hm_code_mat)
|
||||||
|
|
||||||
|
# create compressed heatmaps by merging layers according to transpose of binary code mat
|
||||||
|
encoded_hms = np.zeros((n_enc_layers, hms.shape[1], hms.shape[2]))
|
||||||
|
for l in range(n_enc_layers):
|
||||||
|
selected_layer_ids = hm_code_mat[l,:]
|
||||||
|
encoded_hms[l] = merge_layers(hms[selected_layer_ids].copy())
|
||||||
|
decode_heatmaps(encoded_hms)
|
||||||
|
return encoded_hms
|
||||||
|
|
||||||
|
|
||||||
|
def convert_to_hamming_encoded_heatmaps(hms):
|
||||||
|
|
||||||
|
def merge_layers(hms):
|
||||||
|
hms = hms.max(axis=0)
|
||||||
|
return hms/hms.max()
|
||||||
|
|
||||||
|
num_landmarks = len(hms)
|
||||||
|
n_enc_layers = int(np.ceil(np.log2(num_landmarks)))
|
||||||
|
code_mat = __get_code_mat(num_landmarks)
|
||||||
|
|
||||||
|
# create compressed heatmaps by merging layers according to transpose of binary code mat
|
||||||
|
encoded_hms = np.zeros((n_enc_layers, hms.shape[1], hms.shape[2]))
|
||||||
|
for l in range(n_enc_layers):
|
||||||
|
selected_layer_ids = code_mat[:, l]
|
||||||
|
encoded_hms[l] = merge_layers(hms[selected_layer_ids].copy())
|
||||||
|
# decode_heatmaps(encoded_hms)
|
||||||
|
return encoded_hms
|
||||||
|
|
||||||
|
|
||||||
|
def decode_heatmaps(hms):
|
||||||
|
import cv2
|
||||||
|
def get_decoded_heatmaps_for_layer(hms, lm):
|
||||||
|
show = False
|
||||||
|
enc_layer_ids = code_mat[:, lm]
|
||||||
|
heatmap = np.ones_like(hms[0])
|
||||||
|
for i in range(len(enc_layer_ids)):
|
||||||
|
pos = enc_layer_ids[i]
|
||||||
|
layer = hms[i]
|
||||||
|
if pos:
|
||||||
|
if show:
|
||||||
|
fig, ax = plt.subplots(1,4)
|
||||||
|
print(i, pos)
|
||||||
|
ax[0].imshow(heatmap, vmin=0, vmax=1)
|
||||||
|
ax[1].imshow(layer, vmin=0, vmax=1)
|
||||||
|
# mask = layer.copy()
|
||||||
|
# mask[mask < 0.1] = 0
|
||||||
|
# heatmap *= mask
|
||||||
|
heatmap *= layer
|
||||||
|
if show:
|
||||||
|
# ax[2].imshow(mask, vmin=0, vmax=1)
|
||||||
|
ax[3].imshow(heatmap, vmin=0, vmax=1)
|
||||||
|
|
||||||
|
return heatmap
|
||||||
|
|
||||||
|
num_landmarks = 68
|
||||||
|
|
||||||
|
# get binary code for each heatmap id
|
||||||
|
code_mat = hm_code_mat
|
||||||
|
|
||||||
|
decoded_hms = np.zeros((num_landmarks, hms.shape[1], hms.shape[1]))
|
||||||
|
|
||||||
|
show = False
|
||||||
|
if show:
|
||||||
|
fig, ax = plt.subplots(1)
|
||||||
|
ax.imshow(code_mat)
|
||||||
|
fig_dec, ax_dec = plt.subplots(7, 10)
|
||||||
|
fig, ax = plt.subplots(5,9)
|
||||||
|
for i in range(len(hms)):
|
||||||
|
ax[i//9, i%9].imshow(hms[i])
|
||||||
|
|
||||||
|
lms = np.zeros((68,2), dtype=int)
|
||||||
|
# lmid_to_show = 16
|
||||||
|
|
||||||
|
for lm in range(0,68):
|
||||||
|
|
||||||
|
heatmap = get_decoded_heatmaps_for_layer(hms, lm)
|
||||||
|
|
||||||
|
decoded_hms[lm] = heatmap
|
||||||
|
heatmap = cv2.blur(heatmap, (5, 5))
|
||||||
|
lms[lm, :] = np.unravel_index(np.argmax(heatmap, axis=None), heatmap.shape)[::-1]
|
||||||
|
|
||||||
|
if show:
|
||||||
|
ax_dec[lm//10, lm%10].imshow(heatmap)
|
||||||
|
|
||||||
|
if show:
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
return decoded_hms, lms
|
||||||
|
|
||||||
|
|
||||||
|
def create_landmark_heatmaps(lms, sigma, landmarks_to_use, heatmap_size):
|
||||||
|
lm_wnd_size = int(sigma * 5)
|
||||||
|
lm_heatmap_window = make_landmark_template(lm_wnd_size, sigma)
|
||||||
|
nchannels = len(landmarks_to_use)
|
||||||
|
|
||||||
|
hms = np.zeros((nchannels, heatmap_size, heatmap_size))
|
||||||
|
for l in landmarks_to_use:
|
||||||
|
wnd = lm_heatmap_window
|
||||||
|
_fill_heatmap_layer(hms, lms, l, wnd, lm_wnd_size)
|
||||||
|
|
||||||
|
if lmcfg.LANDMARK_TARGET == 'single_channel':
|
||||||
|
hms = hms.max(axis=0)
|
||||||
|
hms /= hms.max()
|
||||||
|
return hms.astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_nme_per_img(gt_lms, pred_lms, ocular_norm='pupil', landmarks_to_eval=None, image_size=None):
|
||||||
|
norm_dists = calc_landmark_nme(gt_lms, pred_lms, ocular_norm, image_size=image_size)
|
||||||
|
if landmarks_to_eval is None:
|
||||||
|
landmarks_to_eval = range(norm_dists.shape[1])
|
||||||
|
return np.mean(np.array([norm_dists[:,l] for l in landmarks_to_eval]).T, axis=1)
|
||||||
|
|
||||||
|
|
||||||
|
def get_pupil_dists(lms):
|
||||||
|
assert lms.shape[2] == 68
|
||||||
|
ocular_dists_inner = np.sqrt(np.sum((lms[:, 42] - lms[:, 39])**2, axis=1))
|
||||||
|
ocular_dists_outer = np.sqrt(np.sum((lms[:, 45] - lms[:, 36])**2, axis=1))
|
||||||
|
return np.vstack((ocular_dists_inner, ocular_dists_outer)).mean(axis=0)
|
||||||
|
|
||||||
|
|
||||||
|
def get_landmark_confs(X_lm_hm):
|
||||||
|
return np.clip(to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2), a_min=0, a_max=1)
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_nme(gt_lms, pred_lms, ocular_norm='pupil', image_size=None):
|
||||||
|
def reformat(lms):
|
||||||
|
lms = to_numpy(lms)
|
||||||
|
if len(lms.shape) == 2:
|
||||||
|
lms = lms.reshape((1,-1,2))
|
||||||
|
return lms
|
||||||
|
gt = reformat(gt_lms)
|
||||||
|
pred = reformat(pred_lms)
|
||||||
|
assert(len(gt.shape) == 3)
|
||||||
|
assert(len(pred.shape) == 3)
|
||||||
|
if gt.shape[1] == 5: # VGGFace2
|
||||||
|
ocular_dists = np.sqrt(np.sum((gt[:, 1] - gt[:, 0])**2, axis=1))
|
||||||
|
elif gt.shape[1] == 19: # AFLW
|
||||||
|
assert image_size is not None
|
||||||
|
ocular_dists = np.ones(gt.shape[0], dtype=np.float32) * image_size
|
||||||
|
elif gt.shape[1] == 98: # WFLW
|
||||||
|
ocular_dists = np.sqrt(np.sum((gt[:, 72] - gt[:, 60])**2, axis=1))
|
||||||
|
elif gt.shape[1] == 68: # 300-W
|
||||||
|
if ocular_norm == 'pupil':
|
||||||
|
ocular_dists = get_pupil_dists(gt)
|
||||||
|
elif ocular_norm == 'outer':
|
||||||
|
ocular_dists = np.sqrt(np.sum((gt[:, 45] - gt[:, 36])**2, axis=1))
|
||||||
|
elif ocular_norm is None or ocular_norm == 'none':
|
||||||
|
ocular_dists = np.ones((len(gt),1)) * 100.0
|
||||||
|
else:
|
||||||
|
raise ValueError("Ocular norm {} not defined!".format(ocular_norm))
|
||||||
|
else:
|
||||||
|
assert image_size is not None
|
||||||
|
ocular_dists = np.ones(gt.shape[0], dtype=np.float32) * image_size
|
||||||
|
norm_dists = np.sqrt(np.sum((gt - pred)**2, axis=2)) / ocular_dists.reshape(len(gt), 1)
|
||||||
|
return norm_dists * 100
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_failure_rate(nmes, th=10.0):
|
||||||
|
img_nmes = nmes.mean(axis=1)
|
||||||
|
assert len(img_nmes) == len(nmes)
|
||||||
|
return np.count_nonzero(img_nmes > th) / len(img_nmes.ravel())
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_ncc(X, X_recon, lms):
|
||||||
|
input_images = vis.to_disp_images(X, denorm=True)
|
||||||
|
recon_images = vis.to_disp_images(X_recon, denorm=True)
|
||||||
|
nimgs = len(input_images)
|
||||||
|
nlms = len(lms[0])
|
||||||
|
wnd_size = (X_recon.shape[-1] // 16) - 1
|
||||||
|
nccs = np.zeros((nimgs, nlms), dtype=np.float32)
|
||||||
|
img_shape = input_images[0].shape
|
||||||
|
for i in range(nimgs):
|
||||||
|
for lid in range(nlms):
|
||||||
|
x = int(lms[i, lid, 0])
|
||||||
|
y = int(lms[i, lid, 1])
|
||||||
|
t = max(0, y-wnd_size//2)
|
||||||
|
b = min(img_shape[0]-1, y+wnd_size//2)
|
||||||
|
l = max(0, x-wnd_size//2)
|
||||||
|
r = min(img_shape[1]-1, x+wnd_size//2)
|
||||||
|
wnd1 = input_images[i][t:b, l:r]
|
||||||
|
wnd2 = recon_images[i][t:b, l:r]
|
||||||
|
ncc = ((wnd1-wnd1.mean()) * (wnd2-wnd2.mean())).mean() / (wnd1.std() * wnd2.std())
|
||||||
|
nccs[i, lid] = ncc
|
||||||
|
return np.clip(np.nan_to_num(nccs), a_min=-1, a_max=1)
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_ssim_score(X, X_recon, lms, wnd_size=None):
|
||||||
|
if wnd_size is None:
|
||||||
|
wnd_size = (X_recon.shape[-1] // 16) - 1
|
||||||
|
input_images = vis.to_disp_images(X, denorm=True)
|
||||||
|
recon_images = vis.to_disp_images(X_recon, denorm=True)
|
||||||
|
data_range = 255.0 if input_images[0].dtype == np.uint8 else 1.0
|
||||||
|
nimgs = len(input_images)
|
||||||
|
nlms = len(lms[0])
|
||||||
|
scores = np.zeros((nimgs, nlms), dtype=np.float32)
|
||||||
|
for i in range(nimgs):
|
||||||
|
S = compare_ssim(input_images[i], recon_images[i], data_range=data_range, multichannel=True, full=True)[1]
|
||||||
|
S = S.mean(axis=2)
|
||||||
|
for lid in range(nlms):
|
||||||
|
x = int(lms[i, lid, 0])
|
||||||
|
y = int(lms[i, lid, 1])
|
||||||
|
t = max(0, y-wnd_size//2)
|
||||||
|
b = min(S.shape[0]-1, y+wnd_size//2)
|
||||||
|
l = max(0, x-wnd_size//2)
|
||||||
|
r = min(S.shape[1]-1, x+wnd_size//2)
|
||||||
|
wnd = S[t:b, l:r]
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("ignore", category=RuntimeWarning)
|
||||||
|
scores[i, lid] = wnd.mean()
|
||||||
|
return np.nan_to_num(scores)
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_cs_error(X, X_recon, lms, torch_ssim, training=False, wnd_size=None):
|
||||||
|
if wnd_size is None:
|
||||||
|
wnd_size = (X_recon.shape[-1] // 16) - 1
|
||||||
|
nimgs = len(X)
|
||||||
|
nlms = len(lms[0])
|
||||||
|
input_size = X.shape[-1]
|
||||||
|
errs = torch.zeros((nimgs, nlms), requires_grad=training).cuda()
|
||||||
|
for i in range(len(X)):
|
||||||
|
torch_ssim(X[i].unsqueeze(0), X_recon[i].unsqueeze(0))
|
||||||
|
cs_map = torch_ssim.cs_map[0].mean(dim=0)
|
||||||
|
map_size = cs_map.shape[0]
|
||||||
|
margin = (input_size - map_size) // 2
|
||||||
|
S = torch.zeros((input_size, input_size), requires_grad=training).cuda()
|
||||||
|
S[margin:-margin, margin:-margin] = cs_map
|
||||||
|
for lid in range(nlms):
|
||||||
|
x = int(lms[i, lid, 0])
|
||||||
|
y = int(lms[i, lid, 1])
|
||||||
|
t = max(0, y-wnd_size//2)
|
||||||
|
b = min(S.shape[0]-1, y+wnd_size//2)
|
||||||
|
l = max(0, x-wnd_size//2)
|
||||||
|
r = min(S.shape[1]-1, x+wnd_size//2)
|
||||||
|
wnd = S[t:b, l:r]
|
||||||
|
errs[i, lid] = 1 - wnd.mean()
|
||||||
|
return errs
|
||||||
|
|
||||||
|
|
||||||
|
def calc_landmark_recon_error(X, X_recon, lms, return_maps=False, reduction='mean'):
|
||||||
|
assert len(X.shape) == 4
|
||||||
|
assert reduction in ['mean', 'none']
|
||||||
|
X = to_numpy(X)
|
||||||
|
X_recon = to_numpy(X_recon)
|
||||||
|
mask = np.zeros((X.shape[0], X.shape[2], X.shape[3]), dtype=np.float32)
|
||||||
|
input_size = X.shape[-1]
|
||||||
|
radius = input_size * 0.05
|
||||||
|
for img_id in range(len(mask)):
|
||||||
|
for lm in lms[img_id]:
|
||||||
|
cv2.circle(mask[img_id], (int(lm[0]), int(lm[1])), radius=int(radius), color=1, thickness=-1)
|
||||||
|
err_maps = np.abs(X - X_recon).mean(axis=1) * 255.0
|
||||||
|
masked_err_maps = err_maps * mask
|
||||||
|
|
||||||
|
debug = False
|
||||||
|
if debug:
|
||||||
|
fig, ax = plt.subplots(1,3)
|
||||||
|
ax[0].imshow(vis.to_disp_image((X * mask[:,np.newaxis,:,:].repeat(3, axis=1))[0], denorm=True))
|
||||||
|
ax[1].imshow(vis.to_disp_image((X_recon * mask[:,np.newaxis,:,:].repeat(3, axis=1))[0], denorm=True))
|
||||||
|
ax[2].imshow(masked_err_maps[0])
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
if reduction == 'mean':
|
||||||
|
err = masked_err_maps.sum() / (mask.sum() * 3)
|
||||||
|
else:
|
||||||
|
# err = masked_err_maps.mean(axis=2).mean(axis=1)
|
||||||
|
err = masked_err_maps.sum(axis=2).sum(axis=1) / (mask.reshape(len(mask), -1).sum(axis=1) * 3)
|
||||||
|
|
||||||
|
if return_maps:
|
||||||
|
return err, masked_err_maps
|
||||||
|
else:
|
||||||
|
return err
|
||||||
|
|
||||||
|
|
||||||
|
def to_single_channel_heatmap(lm_heatmaps):
|
||||||
|
if lmcfg.LANDMARK_TARGET == 'colored':
|
||||||
|
mc = [to_image(lm_heatmaps[0])]
|
||||||
|
elif lmcfg.LANDMARK_TARGET == 'single_channel':
|
||||||
|
mc = [to_image(lm_heatmaps[0, 0])]
|
||||||
|
else:
|
||||||
|
mc = to_image(lm_heatmaps.max(axis=1))
|
||||||
|
return mc
|
||||||
|
|
||||||
|
|
||||||
|
LM68_TO_LM96 = 1
|
||||||
|
LM98_TO_LM68 = 2
|
||||||
|
LM68_TO_LM5 = 3
|
||||||
|
|
||||||
|
def convert_landmarks(lms, code):
|
||||||
|
cvt_func = {
|
||||||
|
LM98_TO_LM68: lm98_to_lm68,
|
||||||
|
LM68_TO_LM5: lm68_to_lm5,
|
||||||
|
}
|
||||||
|
if len(lms.shape) == 3:
|
||||||
|
# new_lms = []
|
||||||
|
new_lms = torch.zeros((len(lms), 5, 2), requires_grad=True, dtype=torch.float32).cuda()
|
||||||
|
for i in range(len(lms)):
|
||||||
|
# new_lms.append(cvt_func[code](lms[i]))
|
||||||
|
# new_lms[i] += cvt_func[code](lms[i])
|
||||||
|
cvt_func[code](lms[i], new_lms[i])
|
||||||
|
# new_lms = torch.stack(new_lms)
|
||||||
|
# new_lms = np.array(new_lms)
|
||||||
|
return new_lms
|
||||||
|
elif len(lms.shape) == 2:
|
||||||
|
return cvt_func[code](lms)
|
||||||
|
else:
|
||||||
|
raise ValueError
|
||||||
|
|
||||||
|
|
||||||
|
def lm68_to_lm5(lm68, lm5):
|
||||||
|
# lm5 = np.zeros((len(lm68), 5, 2), dtype=np.float32)
|
||||||
|
# lm5 = torch.zeros((5, 2), requires_grad=True, dtype=torch.float32)
|
||||||
|
lm5[0] += (lm68[36] + lm68[39]) / 2
|
||||||
|
lm5[1] += (lm68[42] + lm68[45]) / 2
|
||||||
|
lm5[2] += lm68[30]
|
||||||
|
lm5[3] += lm68[48]
|
||||||
|
lm5[4] += lm68[54]
|
||||||
|
# return lm5
|
||||||
|
|
||||||
|
|
||||||
|
def lm98_to_lm68(lm98):
|
||||||
|
def copy_lms(offset68, offset98, n):
|
||||||
|
lm68[range(offset68, offset68+n)] = lm98[range(offset98, offset98+n)]
|
||||||
|
|
||||||
|
assert len(lm98) == 98, "Cannot convert landmarks to 68 points!"
|
||||||
|
lm68 = np.zeros((68,2), dtype=np.float32)
|
||||||
|
|
||||||
|
# outline
|
||||||
|
lm68[range(17)] = lm98[range(0,33,2)]
|
||||||
|
|
||||||
|
# left eyebrow
|
||||||
|
copy_lms(17, 33, 5)
|
||||||
|
# right eyebrow
|
||||||
|
copy_lms(22, 42, 5)
|
||||||
|
# nose
|
||||||
|
copy_lms(27, 51, 9)
|
||||||
|
|
||||||
|
# eye left
|
||||||
|
lm68[36] = lm98[60]
|
||||||
|
lm68[37] = lm98[61]
|
||||||
|
lm68[38] = lm98[63]
|
||||||
|
lm68[39] = lm98[64]
|
||||||
|
lm68[40] = lm98[65]
|
||||||
|
lm68[41] = lm98[67]
|
||||||
|
|
||||||
|
# eye right
|
||||||
|
lm68[36+6] = lm98[60+8]
|
||||||
|
lm68[37+6] = lm98[61+8]
|
||||||
|
lm68[38+6] = lm98[63+8]
|
||||||
|
lm68[39+6] = lm98[64+8]
|
||||||
|
lm68[40+6] = lm98[65+8]
|
||||||
|
lm68[41+6] = lm98[67+8]
|
||||||
|
|
||||||
|
copy_lms(48, 76, 20)
|
||||||
|
|
||||||
|
return lm68
|
||||||
|
|
||||||
|
|
||||||
|
def is_good_landmark(confs, rec_errs=None):
|
||||||
|
if rec_errs is not None:
|
||||||
|
low_errors = rec_errs < 0.25
|
||||||
|
confs *= np.array(low_errors).astype(int)
|
||||||
|
return confs > 0.8
|
||||||
|
|
||||||
|
|
||||||
|
def smooth_heatmaps(hms):
|
||||||
|
assert(len(hms.shape) == 4)
|
||||||
|
hms = to_numpy(hms)
|
||||||
|
for i in range(hms.shape[0]):
|
||||||
|
for l in range(hms.shape[1]):
|
||||||
|
hms[i,l] = cv2.blur(hms[i,l], (9,9), borderType=cv2.BORDER_CONSTANT)
|
||||||
|
# hms[i,l] = cv2.GaussianBlur(hms[i,l], (9,9), sigmaX=9, borderType=cv2.BORDER_CONSTANT)
|
||||||
|
return hms
|
||||||
|
|
||||||
|
|
||||||
|
def heatmaps_to_landmarks(hms, target_size):
|
||||||
|
def landmark_id_to_heatmap_id(lm_id):
|
||||||
|
return {lm: i for i,lm in enumerate(range(num_landmarks))}[lm_id]
|
||||||
|
|
||||||
|
assert len(hms.shape) == 4
|
||||||
|
num_images = hms.shape[0]
|
||||||
|
num_landmarks = hms.shape[1]
|
||||||
|
heatmap_size = hms.shape[-1]
|
||||||
|
lms = np.zeros((num_images, num_landmarks, 2), dtype=int)
|
||||||
|
if hms.shape[1] > 3:
|
||||||
|
# print(hms.max())
|
||||||
|
for i in range(len(hms)):
|
||||||
|
heatmaps = to_numpy(hms[i])
|
||||||
|
for l in range(len(heatmaps)):
|
||||||
|
hm = heatmaps[landmark_id_to_heatmap_id(l)]
|
||||||
|
lms[i, l, :] = np.unravel_index(np.argmax(hm, axis=None), hm.shape)[::-1]
|
||||||
|
lm_scale = heatmap_size / target_size
|
||||||
|
return lms / lm_scale
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from matplotlib import pyplot as plt
|
||||||
|
from skimage.metrics import structural_similarity as compare_ssim
|
||||||
|
|
||||||
|
from common.utils import nn as nn
|
||||||
|
from common.utils.nn import to_numpy
|
||||||
|
from common import vis
|
||||||
|
from landmarks.lmutils import calc_landmark_nme, calc_landmark_ssim_score, to_single_channel_heatmap, \
|
||||||
|
calc_landmark_nme_per_img, smooth_heatmaps
|
||||||
|
|
||||||
|
|
||||||
|
def show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1.0):
|
||||||
|
vmax = 1.0
|
||||||
|
rows_heatmaps = []
|
||||||
|
if gt_heatmaps is not None:
|
||||||
|
vmax = gt_heatmaps.max()
|
||||||
|
if len(gt_heatmaps[0].shape) == 2:
|
||||||
|
gt_heatmaps = [vis.color_map(hm, vmin=0, vmax=vmax, cmap=plt.cm.jet) for hm in gt_heatmaps]
|
||||||
|
nCols = 1 if len(gt_heatmaps) == 1 else nimgs
|
||||||
|
rows_heatmaps.append(cv2.resize(vis.make_grid(gt_heatmaps, nCols=nCols, padval=0), None, fx=f, fy=f))
|
||||||
|
|
||||||
|
disp_pred_heatmaps = pred_heatmaps
|
||||||
|
if len(pred_heatmaps[0].shape) == 2:
|
||||||
|
disp_pred_heatmaps = [vis.color_map(hm, vmin=0, vmax=vmax, cmap=plt.cm.jet) for hm in pred_heatmaps]
|
||||||
|
nCols = 1 if len(pred_heatmaps) == 1 else nimgs
|
||||||
|
rows_heatmaps.append(cv2.resize(vis.make_grid(disp_pred_heatmaps, nCols=nCols, padval=0), None, fx=f, fy=f))
|
||||||
|
|
||||||
|
cv2.imshow('Landmark heatmaps', cv2.cvtColor(np.vstack(rows_heatmaps), cv2.COLOR_RGB2BGR))
|
||||||
|
|
||||||
|
|
||||||
|
def visualize_batch(images, landmarks, X_recon, X_lm_hm, lm_preds_max,
|
||||||
|
lm_heatmaps=None, target_images=None, lm_preds_cnn=None, ds=None, wait=0, ssim_maps=None,
|
||||||
|
landmarks_to_draw=None, ocular_norm='outer', horizontal=False, f=1.0,
|
||||||
|
overlay_heatmaps_input=False, overlay_heatmaps_recon=False, clean=False,
|
||||||
|
landmarks_only_outline=range(17), landmarks_no_outline=range(17,68)):
|
||||||
|
|
||||||
|
gt_color = (0,255,0)
|
||||||
|
pred_color = (0,0,255)
|
||||||
|
image_size = images.shape[3]
|
||||||
|
assert image_size in [128, 256]
|
||||||
|
|
||||||
|
nimgs = min(10, len(images))
|
||||||
|
images = nn.atleast4d(images)[:nimgs]
|
||||||
|
num_landmarks = lm_preds_max.shape[1]
|
||||||
|
|
||||||
|
if landmarks_to_draw is None:
|
||||||
|
landmarks_to_draw = range(num_landmarks)
|
||||||
|
|
||||||
|
nme_per_lm = None
|
||||||
|
if landmarks is None:
|
||||||
|
# print('num landmarks', lmcfg.NUM_LANDMARKS)
|
||||||
|
lm_gt = np.zeros((nimgs, num_landmarks, 2))
|
||||||
|
else:
|
||||||
|
lm_gt = nn.atleast3d(to_numpy(landmarks))[:nimgs]
|
||||||
|
nme_per_lm = calc_landmark_nme(lm_gt, lm_preds_max[:nimgs], ocular_norm=ocular_norm, image_size=image_size)
|
||||||
|
lm_ssim_errs = 1 - calc_landmark_ssim_score(images, X_recon[:nimgs], lm_gt)
|
||||||
|
|
||||||
|
lm_confs = None
|
||||||
|
# show landmark heatmaps
|
||||||
|
pred_heatmaps = None
|
||||||
|
if X_lm_hm is not None:
|
||||||
|
pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm[:nimgs]))
|
||||||
|
pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in pred_heatmaps]
|
||||||
|
gt_heatmaps = None
|
||||||
|
if lm_heatmaps is not None:
|
||||||
|
gt_heatmaps = to_single_channel_heatmap(to_numpy(lm_heatmaps[:nimgs]))
|
||||||
|
gt_heatmaps = np.array([cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in gt_heatmaps])
|
||||||
|
show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1)
|
||||||
|
lm_confs = to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2)
|
||||||
|
|
||||||
|
# resize images for display and scale landmarks accordingly
|
||||||
|
lm_preds_max = lm_preds_max[:nimgs] * f
|
||||||
|
if lm_preds_cnn is not None:
|
||||||
|
lm_preds_cnn = lm_preds_cnn[:nimgs] * f
|
||||||
|
lm_gt *= f
|
||||||
|
|
||||||
|
input_images = vis.to_disp_images(images[:nimgs], denorm=True)
|
||||||
|
if target_images is not None:
|
||||||
|
disp_images = vis.to_disp_images(target_images[:nimgs], denorm=True)
|
||||||
|
else:
|
||||||
|
disp_images = vis.to_disp_images(images[:nimgs], denorm=True)
|
||||||
|
disp_images = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images]
|
||||||
|
|
||||||
|
recon_images = vis.to_disp_images(X_recon[:nimgs], denorm=True)
|
||||||
|
disp_X_recon = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
|
||||||
|
|
||||||
|
# overlay landmarks on input images
|
||||||
|
if pred_heatmaps is not None and overlay_heatmaps_input:
|
||||||
|
disp_images = [vis.overlay_heatmap(disp_images[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))]
|
||||||
|
if pred_heatmaps is not None and overlay_heatmaps_recon:
|
||||||
|
disp_X_recon = [vis.overlay_heatmap(disp_X_recon[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))]
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Show input images
|
||||||
|
#
|
||||||
|
disp_images = vis.add_landmarks_to_images(disp_images, lm_gt[:nimgs], color=gt_color)
|
||||||
|
disp_images = vis.add_landmarks_to_images(disp_images, lm_preds_max[:nimgs], lm_errs=nme_per_lm,
|
||||||
|
color=pred_color, draw_wireframe=False, gt_landmarks=lm_gt,
|
||||||
|
draw_gt_offsets=True)
|
||||||
|
|
||||||
|
# disp_images = vis.add_landmarks_to_images(disp_images, lm_gt[:nimgs], color=(1,1,1), radius=1,
|
||||||
|
# draw_dots=True, draw_wireframe=True, landmarks_to_draw=landmarks_to_draw)
|
||||||
|
# disp_images = vis.add_landmarks_to_images(disp_images, lm_preds_max[:nimgs], lm_errs=nme_per_lm,
|
||||||
|
# color=(1.0, 0.0, 0.0),
|
||||||
|
# draw_dots=True, draw_wireframe=True, radius=1,
|
||||||
|
# gt_landmarks=lm_gt, draw_gt_offsets=False,
|
||||||
|
# landmarks_to_draw=landmarks_to_draw)
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Show reconstructions
|
||||||
|
#
|
||||||
|
X_recon_errs = 255.0 * torch.abs(images - X_recon[:nimgs]).reshape(len(images), -1).mean(dim=1)
|
||||||
|
if not clean:
|
||||||
|
disp_X_recon = vis.add_error_to_images(disp_X_recon[:nimgs], errors=X_recon_errs, format_string='{:>4.1f}')
|
||||||
|
|
||||||
|
# modes of heatmaps
|
||||||
|
# disp_X_recon = [overlay_heatmap(disp_X_recon[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))]
|
||||||
|
if not clean:
|
||||||
|
lm_errs_max = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm,
|
||||||
|
landmarks_no_outline, image_size=image_size)
|
||||||
|
lm_errs_max_outline = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm,
|
||||||
|
landmarks_only_outline, image_size=image_size)
|
||||||
|
lm_errs_max_all = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm,
|
||||||
|
list(landmarks_only_outline)+list(landmarks_no_outline),
|
||||||
|
image_size=image_size)
|
||||||
|
disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max, loc='br-2', format_string='{:>5.2f}', vmax=15)
|
||||||
|
disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max_outline, loc='br-1', format_string='{:>5.2f}', vmax=15)
|
||||||
|
disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max_all, loc='br', format_string='{:>5.2f}', vmax=15)
|
||||||
|
disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_gt, color=gt_color, draw_wireframe=True)
|
||||||
|
|
||||||
|
# disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_preds_max[:nimgs],
|
||||||
|
# color=pred_color, draw_wireframe=False,
|
||||||
|
# lm_errs=nme_per_lm, lm_confs=lm_confs,
|
||||||
|
# lm_rec_errs=lm_ssim_errs, gt_landmarks=lm_gt,
|
||||||
|
# draw_gt_offsets=True, draw_dots=True)
|
||||||
|
|
||||||
|
disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_preds_max[:nimgs],
|
||||||
|
color=pred_color, draw_wireframe=True,
|
||||||
|
gt_landmarks=lm_gt, draw_gt_offsets=True, lm_errs=nme_per_lm,
|
||||||
|
draw_dots=True, radius=2)
|
||||||
|
|
||||||
|
def add_confidences(disp_X_recon, lmids, loc):
|
||||||
|
means = lm_confs[:,lmids].mean(axis=1)
|
||||||
|
colors = vis.color_map(to_numpy(1-means), cmap=plt.cm.jet, vmin=0.0, vmax=0.4)
|
||||||
|
return vis.add_error_to_images(disp_X_recon, means, loc=loc, format_string='{:>4.2f}', colors=colors)
|
||||||
|
|
||||||
|
# disp_X_recon = add_confidences(disp_X_recon, lmcfg.LANDMARKS_NO_OUTLINE, 'bm-2')
|
||||||
|
# disp_X_recon = add_confidences(disp_X_recon, lmcfg.LANDMARKS_ONLY_OUTLINE, 'bm-1')
|
||||||
|
# disp_X_recon = add_confidences(disp_X_recon, lmcfg.ALL_LANDMARKS, 'bm')
|
||||||
|
|
||||||
|
# print ssim errors
|
||||||
|
ssim = np.zeros(nimgs)
|
||||||
|
for i in range(nimgs):
|
||||||
|
ssim[i] = compare_ssim(input_images[i], recon_images[i], data_range=1.0, multichannel=True)
|
||||||
|
if not clean:
|
||||||
|
disp_X_recon = vis.add_error_to_images(disp_X_recon, 1 - ssim, loc='bl-1', format_string='{:>4.2f}',
|
||||||
|
vmax=0.8, vmin=0.2)
|
||||||
|
# print ssim torch errors
|
||||||
|
if ssim_maps is not None and not clean:
|
||||||
|
disp_X_recon = vis.add_error_to_images(disp_X_recon, ssim_maps.reshape(len(ssim_maps), -1).mean(axis=1),
|
||||||
|
loc='bl-2', format_string='{:>4.2f}', vmin=0.0, vmax=0.4)
|
||||||
|
|
||||||
|
rows = [vis.make_grid(disp_images, nCols=nimgs, normalize=False)]
|
||||||
|
rows.append(vis.make_grid(disp_X_recon, nCols=nimgs))
|
||||||
|
|
||||||
|
if ssim_maps is not None:
|
||||||
|
disp_ssim_maps = to_numpy(nn.denormalized(ssim_maps)[:nimgs].transpose(0, 2, 3, 1))
|
||||||
|
for i in range(len(disp_ssim_maps)):
|
||||||
|
disp_ssim_maps[i] = vis.color_map(disp_ssim_maps[i].mean(axis=2), vmin=0.0, vmax=2.0)
|
||||||
|
grid_ssim_maps = vis.make_grid(disp_ssim_maps, nCols=nimgs, fx=f, fy=f)
|
||||||
|
cv2.imshow('ssim errors', cv2.cvtColor(grid_ssim_maps, cv2.COLOR_RGB2BGR))
|
||||||
|
|
||||||
|
if horizontal:
|
||||||
|
assert(nimgs == 1)
|
||||||
|
disp_rows = vis.make_grid(rows, nCols=2)
|
||||||
|
else:
|
||||||
|
disp_rows = vis.make_grid(rows, nCols=1)
|
||||||
|
wnd_title = 'Predicted Landmarks '
|
||||||
|
if ds is not None:
|
||||||
|
wnd_title += ds.__class__.__name__
|
||||||
|
cv2.imshow(wnd_title, cv2.cvtColor(disp_rows, cv2.COLOR_RGB2BGR))
|
||||||
|
cv2.waitKey(wait)
|
||||||
|
|
||||||
|
|
||||||
|
def visualize_images(X, X_lm_hm, landmarks=None, show_recon=True, show_landmarks=True, show_heatmaps=False,
|
||||||
|
draw_wireframe=False, smoothing_level=2, heatmap_opacity=0.8, f=1):
|
||||||
|
|
||||||
|
if show_recon:
|
||||||
|
disp_X = vis.to_disp_images(X, denorm=True)
|
||||||
|
else:
|
||||||
|
disp_X = vis.to_disp_images(torch.zeros_like(X), denorm=False)
|
||||||
|
heatmap_opacity = 1
|
||||||
|
|
||||||
|
if X_lm_hm is not None:
|
||||||
|
if smoothing_level > 0:
|
||||||
|
X_lm_hm = smooth_heatmaps(X_lm_hm)
|
||||||
|
if smoothing_level > 1:
|
||||||
|
X_lm_hm = smooth_heatmaps(X_lm_hm)
|
||||||
|
|
||||||
|
if show_heatmaps:
|
||||||
|
pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm))
|
||||||
|
pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_CUBIC) for im in pred_heatmaps]
|
||||||
|
disp_X = [vis.overlay_heatmap(disp_X[i], pred_heatmaps[i], heatmap_opacity) for i in range(len(pred_heatmaps))]
|
||||||
|
|
||||||
|
if show_landmarks and landmarks is not None:
|
||||||
|
pred_color = (0,255,255)
|
||||||
|
disp_X = vis.add_landmarks_to_images(disp_X, landmarks, color=pred_color, draw_wireframe=draw_wireframe)
|
||||||
|
|
||||||
|
return disp_X
|
||||||
|
|
||||||
|
|
||||||
|
def generate_images(net, z_random, **kwargs):
|
||||||
|
with torch.no_grad():
|
||||||
|
X_gen_vis = net.P(z_random)[:, :3]
|
||||||
|
X_lm_hm = net.LMH(net.P)
|
||||||
|
return visualize_images(X_gen_vis, X_lm_hm, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def visualize_random_faces(net, nimgs=10, wait=10, f=1.0):
|
||||||
|
z_random = torch.randn(nimgs, net.z_dim).cuda()
|
||||||
|
disp_X_gen = generate_images(net, z_random)
|
||||||
|
grid_img = vis.make_grid(disp_X_gen, nCols=nimgs//2)
|
||||||
|
cv2.imshow("random faces", cv2.cvtColor(grid_img, cv2.COLOR_RGB2BGR))
|
||||||
|
cv2.waitKey(wait)
|
||||||
|
|
||||||
|
|
||||||
|
def visualize_batch_CVPR(images, landmarks, X_recon, X_lm_hm, lm_preds, show_recon=True,
|
||||||
|
lm_heatmaps=None, ds=None, wait=0, horizontal=False, f=1.0, radius=2,
|
||||||
|
draw_wireframes=False):
|
||||||
|
|
||||||
|
gt_color = (0,255,0)
|
||||||
|
pred_color = (0,255,255)
|
||||||
|
# pred_color = (255,0,0)
|
||||||
|
|
||||||
|
nimgs = min(10, len(images))
|
||||||
|
images = nn.atleast4d(images)[:nimgs]
|
||||||
|
num_landmarks = lm_preds.shape[1]
|
||||||
|
|
||||||
|
# if landmarks is None:
|
||||||
|
# print('num landmarks', num_landmarks)
|
||||||
|
# lm_gt = np.zeros((nimgs, num_landmarks, 2))
|
||||||
|
# else:
|
||||||
|
|
||||||
|
# show landmark heatmaps
|
||||||
|
pred_heatmaps = None
|
||||||
|
if X_lm_hm is not None:
|
||||||
|
pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm[:nimgs]))
|
||||||
|
pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in pred_heatmaps]
|
||||||
|
gt_heatmaps = None
|
||||||
|
if lm_heatmaps is not None:
|
||||||
|
gt_heatmaps = to_single_channel_heatmap(to_numpy(lm_heatmaps[:nimgs]))
|
||||||
|
gt_heatmaps = np.array([cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in gt_heatmaps])
|
||||||
|
show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1)
|
||||||
|
lm_confs = to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2)
|
||||||
|
|
||||||
|
# resize images for display and scale landmarks accordingly
|
||||||
|
lm_preds = lm_preds[:nimgs] * f
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
|
||||||
|
disp_images = vis.to_disp_images(images[:nimgs], denorm=True)
|
||||||
|
disp_images = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images]
|
||||||
|
rows.append(vis.make_grid(disp_images, nCols=nimgs, normalize=False))
|
||||||
|
|
||||||
|
heatmap_opacity = 1.0
|
||||||
|
if show_recon:
|
||||||
|
recon_images = vis.to_disp_images(X_recon[:nimgs], denorm=True)
|
||||||
|
else:
|
||||||
|
recon_images = vis.to_disp_images(torch.ones_like(X_recon[:nimgs]), denorm=False)
|
||||||
|
heatmap_opacity = 1
|
||||||
|
|
||||||
|
disp_X_recon = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
|
||||||
|
rows.append(vis.make_grid(disp_X_recon, nCols=nimgs))
|
||||||
|
|
||||||
|
# overlay landmarks on images
|
||||||
|
disp_X_recon_hm = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
|
||||||
|
disp_X_recon_hm = [vis.overlay_heatmap(disp_X_recon_hm[i], pred_heatmaps[i], heatmap_opacity) for i in range(len(pred_heatmaps))]
|
||||||
|
rows.append(vis.make_grid(disp_X_recon_hm, nCols=nimgs))
|
||||||
|
|
||||||
|
# reconstructions with prediction
|
||||||
|
disp_X_recon_pred = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
|
||||||
|
disp_X_recon_pred = vis.add_landmarks_to_images(disp_X_recon_pred, lm_preds, color=pred_color,radius=radius)
|
||||||
|
rows.append(vis.make_grid(disp_X_recon_pred, nCols=nimgs))
|
||||||
|
|
||||||
|
# reconstructions with ground truth (if gt available)
|
||||||
|
if landmarks is not None:
|
||||||
|
lm_gt = nn.atleast3d(to_numpy(landmarks))[:nimgs] * f
|
||||||
|
disp_X_recon_gt = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
|
||||||
|
disp_X_recon_gt = vis.add_landmarks_to_images(disp_X_recon_gt, lm_gt, color=gt_color, radius=radius)
|
||||||
|
rows.append(vis.make_grid(disp_X_recon_gt, nCols=nimgs))
|
||||||
|
|
||||||
|
# input images with prediction (and ground truth)
|
||||||
|
disp_images_pred = vis.to_disp_images(images[:nimgs], denorm=True)
|
||||||
|
disp_images_pred = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images_pred]
|
||||||
|
# disp_images_pred = vis.add_landmarks_to_images(disp_images_pred, lm_gt, color=gt_color, radius=radius)
|
||||||
|
disp_images_pred = vis.add_landmarks_to_images(disp_images_pred, lm_preds, color=pred_color, radius=radius,
|
||||||
|
draw_wireframe=draw_wireframes)
|
||||||
|
rows.append(vis.make_grid(disp_images_pred, nCols=nimgs))
|
||||||
|
|
||||||
|
if horizontal:
|
||||||
|
assert(nimgs == 1)
|
||||||
|
disp_rows = vis.make_grid(rows, nCols=len(rows))
|
||||||
|
else:
|
||||||
|
disp_rows = vis.make_grid(rows, nCols=1)
|
||||||
|
wnd_title = 'recon errors '
|
||||||
|
if ds is not None:
|
||||||
|
wnd_title += ds.__class__.__name__
|
||||||
|
cv2.imshow(wnd_title, cv2.cvtColor(disp_rows, cv2.COLOR_RGB2BGR))
|
||||||
|
cv2.waitKey(wait)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import shutil
|
||||||
|
import logging
|
||||||
|
from logging import INFO, ERROR, DEBUG, CRITICAL, FATAL, WARNING, WARN, NOTSET
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
|
||||||
|
|
||||||
|
#The background is set with 40 plus the number of the color, and the foreground with 30
|
||||||
|
|
||||||
|
#These are the sequences need to get colored ouput
|
||||||
|
RESET_SEQ = "\033[0m"
|
||||||
|
COLOR_SEQ = "\033[1;%dm"
|
||||||
|
BOLD_SEQ = "\033[1m"
|
||||||
|
|
||||||
|
COLORS = {
|
||||||
|
'WARNING': YELLOW,
|
||||||
|
'INFO': WHITE,
|
||||||
|
'DEBUG': BLUE,
|
||||||
|
'CRITICAL': RED,
|
||||||
|
'ERROR': RED
|
||||||
|
}
|
||||||
|
|
||||||
|
class Logger(logging.Logger):
|
||||||
|
def __init__(self, path_output, path_config=None, postfix=None, level=logging.NOTSET ):
|
||||||
|
logging.Logger.__init__(self, '', level)
|
||||||
|
|
||||||
|
|
||||||
|
# make dir
|
||||||
|
basename = path_config.name.split(".")[0] if path_config is not None else "log"
|
||||||
|
if postfix is None:
|
||||||
|
postfix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}"
|
||||||
|
|
||||||
|
self.path_output = Path(path_output).joinpath(basename, postfix)
|
||||||
|
self.path_output.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# copy config
|
||||||
|
dst = self.path_output.joinpath(path_config.name)
|
||||||
|
shutil.copyfile(src=path_config, dst=dst)
|
||||||
|
|
||||||
|
# add file hander
|
||||||
|
filename = self.path_output.joinpath(f"logger.log")
|
||||||
|
fHander = logging.FileHandler(filename)
|
||||||
|
fFormat = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
|
||||||
|
fHander.setFormatter(fFormat)
|
||||||
|
self.addHandler(fHander)
|
||||||
|
|
||||||
|
# add console hander
|
||||||
|
cHander = logging.StreamHandler(sys.stdout)
|
||||||
|
cFormat = ColoredFormatter( RESET_SEQ+"[%(asctime)s] %(message)s"+RESET_SEQ )
|
||||||
|
cHander.setFormatter(cFormat)
|
||||||
|
self.addHandler(cHander)
|
||||||
|
def setContext(self, key, value):
|
||||||
|
self.context[key] = value
|
||||||
|
|
||||||
|
def log(self, msg, level, *args, **kwargs):
|
||||||
|
extra = kwargs
|
||||||
|
extra.update(self.context)
|
||||||
|
# super(Logger, self).info(msg)
|
||||||
|
|
||||||
|
def error(self, msg, *args, **kwargs):
|
||||||
|
super(Logger, self).error(msg, *args, **kwargs)
|
||||||
|
|
||||||
|
def exception(self, *args, **kwargs):
|
||||||
|
e = sys.exc_info()
|
||||||
|
extra = kwargs
|
||||||
|
extra.update(self.context)
|
||||||
|
super(Logger, self).error(e[1].message)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class ColoredFormatter(logging.Formatter):
|
||||||
|
def __init__(self, msg, use_color = True):
|
||||||
|
logging.Formatter.__init__(self, msg, datefmt='%Y-%m-%d %H:%M:%S')
|
||||||
|
self.use_color = use_color
|
||||||
|
|
||||||
|
def format(self, record):
|
||||||
|
levelname = record.levelname
|
||||||
|
if self.use_color and levelname in COLORS:
|
||||||
|
levelname_color = COLOR_SEQ % (30+COLORS[levelname]) + levelname + RESET_SEQ
|
||||||
|
record.levelname = levelname_color
|
||||||
|
return logging.Formatter.format(self, record)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
from collections import OrderedDict
|
||||||
|
|
||||||
|
class MultiLossManager(nn.Module):
|
||||||
|
"""Managment Multiple-Loss
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, opt, autoWeight=False):
|
||||||
|
super(MultiLossManager, self).__init__()
|
||||||
|
|
||||||
|
self.opt = opt
|
||||||
|
self.autoWeight = autoWeight
|
||||||
|
|
||||||
|
self.weight = {}
|
||||||
|
self.weigth_name = []
|
||||||
|
|
||||||
|
for iname in opt.LOSS.names:
|
||||||
|
ifull = f"lambda_{iname}"
|
||||||
|
if ifull in opt.LOSS.keys() and opt.LOSS[ifull] > 0:
|
||||||
|
self.weight[ "loss_"+iname ] = opt.LOSS[ifull]
|
||||||
|
self.weigth_name.append("loss_" + iname )
|
||||||
|
n_weight = len(self.weight)
|
||||||
|
|
||||||
|
print(f"WEIGHT of LOSS (n={n_weight}) = {self.weight}")
|
||||||
|
|
||||||
|
if autoWeight:
|
||||||
|
self.weight = torch.ones(n_weight, requires_grad=True)
|
||||||
|
self.weight = torch.nn.Parameter(self.weight)
|
||||||
|
|
||||||
|
|
||||||
|
def forward(self, dict_loss):
|
||||||
|
assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict"
|
||||||
|
|
||||||
|
loss_sum = 0
|
||||||
|
i = 0
|
||||||
|
for name in dict_loss.keys():
|
||||||
|
if name not in self.weigth_name: continue
|
||||||
|
|
||||||
|
if self.autoWeight:
|
||||||
|
loss_sum += 0.5 / (self.weight[i] ** 2) * dict_loss[name] + torch.log(1 + self.weight[i] ** 2)
|
||||||
|
else:
|
||||||
|
loss_sum += (self.weight[name] * dict_loss[name])
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
# print(f"update WEIGHT of LOSS {self.weight}")
|
||||||
|
|
||||||
|
return loss_sum
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class AutomaticWeightedLoss(nn.Module):
|
||||||
|
"""automatically weighted multi-task loss
|
||||||
|
Params:
|
||||||
|
num: int,the number of loss
|
||||||
|
x: multi-task loss
|
||||||
|
Examples:
|
||||||
|
loss1=1
|
||||||
|
loss2=2
|
||||||
|
awl = AutomaticWeightedLoss(2)
|
||||||
|
loss_sum = awl(loss1, loss2)
|
||||||
|
"""
|
||||||
|
def __init__(self, num=2):
|
||||||
|
super(AutomaticWeightedLoss, self).__init__()
|
||||||
|
params = torch.ones(num, requires_grad=True)
|
||||||
|
self.params = torch.nn.Parameter(params)
|
||||||
|
|
||||||
|
|
||||||
|
def forward(self, dict_loss):
|
||||||
|
|
||||||
|
assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict"
|
||||||
|
|
||||||
|
loss_sum = 0
|
||||||
|
for i, name in enumerate(dict_loss.keys()):
|
||||||
|
|
||||||
|
loss_sum += 0.5 / (self.params[i] ** 2) * dict_loss[name] + torch.log(1 + self.params[i] ** 2)
|
||||||
|
|
||||||
|
return loss_sum
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
awl = AutomaticWeightedLoss(2)
|
||||||
|
print(awl.parameters())
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from .wing import WingLoss
|
||||||
|
from .smooth_l1_loss import SmoothL1Loss, L1Loss
|
||||||
|
from .landmarkloss import LandmarkPolygonLoss, LandmarkFocalLoss
|
||||||
|
"""
|
||||||
|
Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/__init__.py
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"WingLoss", "AdaptiveWingLoss", "LandmarkPolygonLoss", "LandmarkFocalLoss"
|
||||||
|
]
|
||||||
|
|
||||||
Whitespace-only changes.
@@ -0,0 +1,34 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
|
||||||
|
# https://github.com/Jarvisgivemeasuit/DPANet-Pytorch/blob/master/utils/utils.py
|
||||||
|
class FocalLoss(nn.Module):
|
||||||
|
def __init__(self, alpha=1, gamma=2, eps=1e-7, reducation='mean'):
|
||||||
|
super().__init__()
|
||||||
|
self.alpha = Variable(torch.tensor(alpha))
|
||||||
|
self.gamma = gamma
|
||||||
|
self.eps = eps
|
||||||
|
self.reducation = reducation
|
||||||
|
|
||||||
|
def forward(self, pred, target):
|
||||||
|
N = pred.shape[0]
|
||||||
|
C = pred.shape[1]
|
||||||
|
num_pixels = pred.shape[2] * pred.shape[3]
|
||||||
|
|
||||||
|
target_index = target.view(target.shape[0], target.shape[1], target.shape[2], 1)
|
||||||
|
class_mask = torch.zeros([N, pred.shape[2], pred.shape[3], C]).cuda()
|
||||||
|
class_mask = class_mask.scatter_(3, target_index, 1.)
|
||||||
|
class_mask = class_mask.transpose(1, 3)
|
||||||
|
class_mask = class_mask.view(pred.shape)
|
||||||
|
|
||||||
|
logsoft_pred = F.log_softmax(pred, dim=1)
|
||||||
|
soft_pred = F.softmax(pred, dim=1)
|
||||||
|
|
||||||
|
loss = -self.alpha * ((1 - soft_pred)) ** self.gamma * logsoft_pred
|
||||||
|
loss = loss * class_mask
|
||||||
|
loss = loss.sum(1)
|
||||||
|
|
||||||
|
if self.reducation == 'mean':
|
||||||
|
return loss.sum() / (class_mask.sum() + self.eps)
|
||||||
|
else:
|
||||||
|
return loss.sum()
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
# from shapely.geometry import Polygon
|
||||||
|
|
||||||
|
|
||||||
|
class LandmarkPolygonLoss(nn.Module):
|
||||||
|
def __init__(self, opt):
|
||||||
|
super(LandmarkPolygonLoss, self).__init__()
|
||||||
|
|
||||||
|
self.opt = opt
|
||||||
|
self.lmdk_indx = {
|
||||||
|
"chin": list(range(0,17)),
|
||||||
|
"eyebrow_lt": [17, 18, 19, 20, 21],
|
||||||
|
"eyebrow_rt": [22, 23, 24, 25, 26],
|
||||||
|
"nose": [27, 31, 32, 33, 34, 35],
|
||||||
|
"eye_lt": [36, 37, 38, 39, 40, 41],
|
||||||
|
"eye_rt": [42, 43, 44, 45, 46, 47],
|
||||||
|
"mouth_out": list(range(48, 60)),
|
||||||
|
"mouth_inn": list(range(60, 68)),
|
||||||
|
}
|
||||||
|
|
||||||
|
def forward(self, pred, target):
|
||||||
|
# predit, (nbatch, 68*2)
|
||||||
|
# target, (nbatch, 68*2)
|
||||||
|
|
||||||
|
#print(f"pred shape = {predit.shape}, target shape = {target.shape}")
|
||||||
|
pred = pred.reshape(-1, 68, 2) * 128
|
||||||
|
target = target.reshape(-1, 68, 2) * 128
|
||||||
|
|
||||||
|
loss_chin = self.area_diff(pred, target, "chin")
|
||||||
|
loss_nose = self.area_diff(pred, target, "nose")
|
||||||
|
loss_eyebrow = self.area_diff(pred, target, "eyebrow_lt") \
|
||||||
|
+ self.area_diff(pred, target, "eyebrow_rt")
|
||||||
|
loss_eye = self.area_diff(pred, target, "eye_lt") \
|
||||||
|
+ self.area_diff(pred, target, "eye_rt")
|
||||||
|
loss_mouth = self.area_diff(pred, target, "mouth_out") \
|
||||||
|
+ self.area_diff(pred, target, "mouth_inn")
|
||||||
|
|
||||||
|
loss = loss_chin + loss_nose + loss_eyebrow + loss_eye # + loss_mouth
|
||||||
|
loss = torch.mean(loss)
|
||||||
|
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def area_diff(self, pred, target, part):
|
||||||
|
indx = self.lmdk_indx[part]
|
||||||
|
|
||||||
|
area_pt = self.PolygonArea(pred, indx)
|
||||||
|
area_gt = self.PolygonArea(target, indx)
|
||||||
|
|
||||||
|
diff = torch.abs(area_pt - area_gt)
|
||||||
|
return diff
|
||||||
|
|
||||||
|
|
||||||
|
def PolygonArea(self, corners, indx):
|
||||||
|
"""PolygonArea Function.
|
||||||
|
Args:
|
||||||
|
corners (torch.Tensor): the keypoints of corners, (nbatch, 68, 2)
|
||||||
|
indx (list, int): the polygon index from the keypoints
|
||||||
|
Return:
|
||||||
|
area (torch.Tensor): (nbatch, )
|
||||||
|
|
||||||
|
"""
|
||||||
|
area, n = 0, len(indx)
|
||||||
|
for i in range(n):
|
||||||
|
j = (i + 1) % n
|
||||||
|
area += corners[:, i, 0] * corners[:, j, 1]
|
||||||
|
area -= corners[:, j, 0] * corners[:, i, 1]
|
||||||
|
|
||||||
|
area = torch.abs(area) / 2.0
|
||||||
|
return area
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class LandmarkFocalLoss(nn.Module):
|
||||||
|
def __init__(self, opt):
|
||||||
|
super(LandmarkFocalLoss, self).__init__()
|
||||||
|
self.opt = opt
|
||||||
|
|
||||||
|
|
||||||
|
def forward(self, predit, target):
|
||||||
|
|
||||||
|
# predit, (nbatch, 68*2)
|
||||||
|
# target, (nbatch, 68*2)
|
||||||
|
|
||||||
|
#print(f"pred shape = {predit.shape}, target shape = {target.shape}")
|
||||||
|
predit = predit.reshape(-1, 68, 2)
|
||||||
|
target = target.reshape(-1, 68, 2)
|
||||||
|
|
||||||
|
x = torch.abs(predit - target) # (nbatch, 68, 2)
|
||||||
|
x = torch.sqrt(x[:,:,0] * x[:,:,0] + x[:,:,1] * x[:,:,1]) # (nbatch, 68)
|
||||||
|
|
||||||
|
#print(f"xsqrt = {x[0, :]}")
|
||||||
|
|
||||||
|
x = torch.torch.pow(1 + 1000*x, x) - 1 # (nbatch, 68)
|
||||||
|
x = torch.clamp_max_(x, 10)
|
||||||
|
|
||||||
|
#print(f"xpow = {x[0, :]}")
|
||||||
|
weight = torch.ones((68,), dtype=x.dtype, device=x.device)
|
||||||
|
weight[48:68] = 10
|
||||||
|
|
||||||
|
|
||||||
|
x = torch.mean(x, dim=0) # (68, )
|
||||||
|
x = torch.mean(x * weight) # (1, )
|
||||||
|
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
|
||||||
|
from .utils import weighted_loss
|
||||||
|
|
||||||
|
@weighted_loss
|
||||||
|
def pfld_loss(pred, target, euler_pt, euler_gt, attribute_gt):
|
||||||
|
"""PFLD loss.
|
||||||
|
Args:
|
||||||
|
pred (torch.Tensor): The prediction landmark. (nbatch, 68*2)
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
|
||||||
|
from .utils import weighted_loss
|
||||||
|
|
||||||
|
@weighted_loss
|
||||||
|
def l1_loss(pred, target):
|
||||||
|
""" L1 loss.
|
||||||
|
Args:
|
||||||
|
pred (torch.Tensor): The prediction.
|
||||||
|
target(torch.Tensor): The ground truth of the prediction
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
torch.Tensor: loss
|
||||||
|
"""
|
||||||
|
|
||||||
|
assert pred.size() == target.size() and target.numel() > 0
|
||||||
|
|
||||||
|
loss = torch.abs(pred - target)
|
||||||
|
|
||||||
|
return loss
|
||||||
|
|
||||||
|
@weighted_loss
|
||||||
|
def smooth_l1_loss(pred, target, beta=1.0):
|
||||||
|
"""Smooth L1 Loss.
|
||||||
|
Args:
|
||||||
|
pred (torch.Tensor): The prediction
|
||||||
|
target (torch.Tensor): The GT of the prediction
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
torch.Tensor: loss
|
||||||
|
"""
|
||||||
|
|
||||||
|
assert beta > 0
|
||||||
|
assert pred.size() == target.size() and target.numel() > 0
|
||||||
|
|
||||||
|
diff = torch.abs(pred - target)
|
||||||
|
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta)
|
||||||
|
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class L1Loss(nn.Module):
|
||||||
|
"""L1 Loss
|
||||||
|
Args:
|
||||||
|
reduction (str, optional): The method to reduce the loss, Options are `none|mean|sum`
|
||||||
|
loss_weight (float, optional): The weight of loss.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, reduction='mean', loss_weight=1.0):
|
||||||
|
super(L1Loss, self).__init__()
|
||||||
|
|
||||||
|
self.reduction = reduction
|
||||||
|
self.loss_weight = loss_weight
|
||||||
|
|
||||||
|
|
||||||
|
def forward(self, pred, target, weight=None, avg_factor=None):
|
||||||
|
"""Forward function.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
pred (troch.Tensor): The prediction
|
||||||
|
target (torch.Tensor): The GT of the prediction.
|
||||||
|
weight (torch.Tensor, optional): The weight of loss for each prediction.
|
||||||
|
avg_factor(int, optional): Average factor that is used to average the loss.
|
||||||
|
"""
|
||||||
|
|
||||||
|
loss = l1_loss(pred, target, weight=weight, reduction=self.reduction, avg_factor=avg_factor)
|
||||||
|
loss = self.loss_weight * loss
|
||||||
|
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
class SmoothL1Loss(nn.Module):
|
||||||
|
"""Smooth L1 Loss.
|
||||||
|
Args:
|
||||||
|
beta (float, optional): The threshold in the piecewise function. Default 1.0
|
||||||
|
reduction (str, optional): The reduce loss method, options are `none|mean|sum`
|
||||||
|
loss_weight (float, optional): The weight of loss
|
||||||
|
Return:
|
||||||
|
torch.Tensor: Loss
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, beta=1.0, reduction="mean", loss_weight=1.0):
|
||||||
|
super(SmoothL1Loss, self).__init__()
|
||||||
|
self.beta = beta
|
||||||
|
self.reduction = reduction
|
||||||
|
self.loss_weight = loss_weight
|
||||||
|
|
||||||
|
def forward(self, pred, target, weight=None, avg_factor=None):
|
||||||
|
"""Forward function.
|
||||||
|
Args:
|
||||||
|
pred (torch.Tensor): The prediction.
|
||||||
|
target (torch.Tensor): The GT of the prediction
|
||||||
|
weight (torch.Tensor, optional): The weigth of loss for each prediction. Default to None
|
||||||
|
avg_factor (int, optional): Average factor that is used to average the loss.
|
||||||
|
"""
|
||||||
|
|
||||||
|
loss = smooth_l1_loss(pred, target, beta=self.beta, weight=weight, avg_factor=avg_factor)
|
||||||
|
loss = self.loss_weight * loss
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
class SoftCrossEntropyLoss(nn.Module):
|
||||||
|
|
||||||
|
def __init__(self, ignore_index=-1, times=1, eps=1e-7, weight=None):
|
||||||
|
super().__init__()
|
||||||
|
self.ignore_index = ignore_index
|
||||||
|
self.times = times
|
||||||
|
self.eps = eps
|
||||||
|
if weight is None:
|
||||||
|
self.weight = weight
|
||||||
|
else:
|
||||||
|
self.weight = weight.cuda()
|
||||||
|
|
||||||
|
def forward(self, pred, target):
|
||||||
|
mask = target != self.ignore_index
|
||||||
|
pred = F.log_softmax(pred, dim=-1)
|
||||||
|
loss = -pred * target
|
||||||
|
loss = loss * mask.float()
|
||||||
|
# print(loss, pred, target, mask)
|
||||||
|
if self.weight is None:
|
||||||
|
return self.times * loss.sum() / (mask.sum() + self.eps)
|
||||||
|
else:
|
||||||
|
return self.times * (self.weight * loss).sum() / (mask.sum() + self.eps)
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import functools
|
||||||
|
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
"""
|
||||||
|
Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/utils.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def reduce_loss(loss, reduction):
|
||||||
|
"""Reduce loss as specified.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
loss (Tensor): Elementwise loss tensor.
|
||||||
|
reduction (str): Options are "none", "mean" and "sum".
|
||||||
|
|
||||||
|
Return:
|
||||||
|
Tensor: Reduced loss tensor.
|
||||||
|
"""
|
||||||
|
reduction_enum = F._Reduction.get_enum(reduction)
|
||||||
|
# none: 0, elementwise_mean:1, sum: 2
|
||||||
|
if reduction_enum == 0:
|
||||||
|
return loss
|
||||||
|
elif reduction_enum == 1:
|
||||||
|
return loss.mean()
|
||||||
|
elif reduction_enum == 2:
|
||||||
|
return loss.sum()
|
||||||
|
|
||||||
|
|
||||||
|
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
|
||||||
|
"""Apply element-wise weight and reduce loss.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
loss (Tensor): Element-wise loss.
|
||||||
|
weight (Tensor): Element-wise weights.
|
||||||
|
reduction (str): Same as built-in losses of PyTorch.
|
||||||
|
avg_factor (float): Avarage factor when computing the mean of losses.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tensor: Processed loss values.
|
||||||
|
"""
|
||||||
|
# if weight is specified, apply element-wise weight
|
||||||
|
if weight is not None:
|
||||||
|
loss = loss * weight
|
||||||
|
|
||||||
|
# if avg_factor is not specified, just reduce the loss
|
||||||
|
if avg_factor is None:
|
||||||
|
loss = reduce_loss(loss, reduction)
|
||||||
|
else:
|
||||||
|
# if reduction is mean, then average the loss by avg_factor
|
||||||
|
if reduction == 'mean':
|
||||||
|
loss = loss.sum() / avg_factor
|
||||||
|
# if reduction is 'none', then do nothing, otherwise raise an error
|
||||||
|
elif reduction != 'none':
|
||||||
|
raise ValueError('avg_factor can not be used with reduction="sum"')
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
def weighted_loss(loss_func):
|
||||||
|
"""Create a weighted version of a given loss function.
|
||||||
|
|
||||||
|
To use this decorator, the loss function must have the signature like
|
||||||
|
`loss_func(pred, target, **kwargs)`. The function only needs to compute
|
||||||
|
element-wise loss without any reduction. This decorator will add weight
|
||||||
|
and reduction arguments to the function. The decorated function will have
|
||||||
|
the signature like `loss_func(pred, target, weight=None, reduction='mean',
|
||||||
|
avg_factor=None, **kwargs)`.
|
||||||
|
|
||||||
|
:Example:
|
||||||
|
|
||||||
|
>>> import torch
|
||||||
|
>>> @weighted_loss
|
||||||
|
>>> def l1_loss(pred, target):
|
||||||
|
>>> return (pred - target).abs()
|
||||||
|
|
||||||
|
>>> pred = torch.Tensor([0, 2, 3])
|
||||||
|
>>> target = torch.Tensor([1, 1, 1])
|
||||||
|
>>> weight = torch.Tensor([1, 0, 1])
|
||||||
|
|
||||||
|
>>> l1_loss(pred, target)
|
||||||
|
tensor(1.3333)
|
||||||
|
>>> l1_loss(pred, target, weight)
|
||||||
|
tensor(1.)
|
||||||
|
>>> l1_loss(pred, target, reduction='none')
|
||||||
|
tensor([1., 1., 2.])
|
||||||
|
>>> l1_loss(pred, target, weight, avg_factor=2)
|
||||||
|
tensor(1.5000)
|
||||||
|
"""
|
||||||
|
|
||||||
|
@functools.wraps(loss_func)
|
||||||
|
def wrapper(pred,
|
||||||
|
target,
|
||||||
|
weight=None,
|
||||||
|
reduction='mean',
|
||||||
|
avg_factor=None,
|
||||||
|
**kwargs):
|
||||||
|
|
||||||
|
# get element-wise loss
|
||||||
|
loss = loss_func(pred, target, **kwargs)
|
||||||
|
|
||||||
|
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
|
||||||
|
return loss
|
||||||
|
|
||||||
|
return wrapper
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import math
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
|
||||||
|
from .utils import weighted_loss
|
||||||
|
|
||||||
|
"""
|
||||||
|
The Wing loss:
|
||||||
|
|
||||||
|
It has been proposed in `Wing Loss for Roubst Facial Landmark Localisation with
|
||||||
|
Convolutional Neural Networks`. https://arxiv.org/abs/1711.06753
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@weighted_loss
|
||||||
|
def wing_loss(pred, target, w=5, epsilon=0.5):
|
||||||
|
"""
|
||||||
|
Source: https://github.com/BloodAxe/pytorch-toolbelt/blob/develop/pytorch_toolbelt/losses/functional.py
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
diff = torch.abs(pred - target)
|
||||||
|
C = w - w * math.log(1 + w / epsilon)
|
||||||
|
loss = torch.where(diff < w, w * torch.log(1 + diff / epsilon), diff - C)
|
||||||
|
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class WingLoss(nn.Module):
|
||||||
|
|
||||||
|
def __init__(self, w=10, epsilon=0.5, reduction='mean', loss_weight=1.0):
|
||||||
|
super(WingLoss,self).__init__()
|
||||||
|
|
||||||
|
self.w = w
|
||||||
|
self.epsilon = epsilon
|
||||||
|
self.reduction = reduction
|
||||||
|
self.loss_weight = loss_weight
|
||||||
|
|
||||||
|
def forward(self, pred, target, weight=None, avg_factor=None):
|
||||||
|
"""Forward function.
|
||||||
|
Args:
|
||||||
|
pred (torch.Tensor, Bx68*2): The prediction
|
||||||
|
target (torch.Tensor, Bx68*2): The GT of prediction
|
||||||
|
weight (torch.Tensor, optional): The weight of each loss, default None
|
||||||
|
avg_factor(int, optional): The average of the reduction loss
|
||||||
|
"""
|
||||||
|
|
||||||
|
loss = wing_loss(pred, target, w=self.w, epsilon=self.epsilon, weight=weight, avg_factor=avg_factor)
|
||||||
|
loss = self.loss_weight * loss
|
||||||
|
|
||||||
|
return loss
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
crieation = WingLoss()
|
||||||
|
|
||||||
|
GT = torch.zeros((2, 68, 64, 64))
|
||||||
|
PT = torch.ones((2, 68, 64, 64))
|
||||||
|
PT.requires_grad_(True)
|
||||||
|
|
||||||
|
loss = crieation(PT, GT)
|
||||||
|
loss.backward()
|
||||||
|
|
||||||
|
print(loss)
|
||||||
|
|
||||||
|
|
||||||
Whitespace-only changes.
@@ -0,0 +1,258 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
|
||||||
|
|
||||||
|
The FID metric calculates the distance between two distributions of images.
|
||||||
|
Typically, we have summary statistics (mean & covariance matrix) of one
|
||||||
|
of these distributions, while the 2nd distribution is given by a GAN.
|
||||||
|
|
||||||
|
When run as a stand-alone program, it compares the distribution of
|
||||||
|
images that are stored as PNG/JPEG at a specified location with a
|
||||||
|
distribution given by summary statistics (in pickle format).
|
||||||
|
|
||||||
|
The FID is calculated by assuming that X_1 and X_2 are the activations of
|
||||||
|
the pool_3 layer of the inception net for generated samples and real world
|
||||||
|
samples respectively.
|
||||||
|
|
||||||
|
See --help to see further details.
|
||||||
|
|
||||||
|
Code apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead
|
||||||
|
of Tensorflow
|
||||||
|
|
||||||
|
Copyright 2018 Institute of Bioinformatics, JKU Linz
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
from scipy.misc import imread
|
||||||
|
from scipy import linalg
|
||||||
|
from torch.autograd import Variable
|
||||||
|
from torch.nn.functional import adaptive_avg_pool2d
|
||||||
|
|
||||||
|
from metrics.inception import InceptionV3
|
||||||
|
|
||||||
|
|
||||||
|
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
|
||||||
|
parser.add_argument('path', type=str, nargs=2,
|
||||||
|
help=('Path to the generated images or '
|
||||||
|
'to .npz statistic files'))
|
||||||
|
parser.add_argument('--batch-size', type=int, default=64,
|
||||||
|
help='Batch size to use')
|
||||||
|
parser.add_argument('--dims', type=int, default=2048,
|
||||||
|
choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),
|
||||||
|
help=('Dimensionality of Inception features to use. '
|
||||||
|
'By default, uses pool3 features'))
|
||||||
|
parser.add_argument('-c', '--gpu', default='', type=str,
|
||||||
|
help='GPU to use (leave blank for CPU only)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_activations(images, model, batch_size=64, dims=2048,
|
||||||
|
cuda=False, verbose=False):
|
||||||
|
"""Calculates the activations of the pool_3 layer for all images.
|
||||||
|
|
||||||
|
Params:
|
||||||
|
-- images : Numpy array of dimension (n_images, 3, hi, wi). The values
|
||||||
|
must lie between 0 and 1.
|
||||||
|
-- model : Instance of inception model
|
||||||
|
-- batch_size : the images numpy array is split into batches with
|
||||||
|
batch size batch_size. A reasonable batch size depends
|
||||||
|
on the hardware.
|
||||||
|
-- dims : Dimensionality of features returned by Inception
|
||||||
|
-- cuda : If set to True, use GPU
|
||||||
|
-- verbose : If set to True and parameter out_step is given, the number
|
||||||
|
of calculated batches is reported.
|
||||||
|
Returns:
|
||||||
|
-- A numpy array of dimension (num images, dims) that contains the
|
||||||
|
activations of the given tensor when feeding inception with the
|
||||||
|
query tensor.
|
||||||
|
"""
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
d0 = images.shape[0]
|
||||||
|
if batch_size > d0:
|
||||||
|
print(('Warning: batch size is bigger than the data size. '
|
||||||
|
'Setting batch size to data size'))
|
||||||
|
batch_size = d0
|
||||||
|
|
||||||
|
n_batches = d0 // batch_size
|
||||||
|
n_used_imgs = n_batches * batch_size
|
||||||
|
|
||||||
|
pred_arr = np.empty((n_used_imgs, dims))
|
||||||
|
for i in range(n_batches):
|
||||||
|
if verbose:
|
||||||
|
print('\rPropagating batch %d/%d' % (i + 1, n_batches),
|
||||||
|
end='', flush=True)
|
||||||
|
start = i * batch_size
|
||||||
|
end = start + batch_size
|
||||||
|
|
||||||
|
batch = torch.from_numpy(images[start:end]).type(torch.FloatTensor)
|
||||||
|
batch = Variable(batch)
|
||||||
|
if cuda:
|
||||||
|
batch = batch.cuda()
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
pred = model(batch)[0]
|
||||||
|
|
||||||
|
# If model output is not scalar, apply global spatial average pooling.
|
||||||
|
# This happens if you choose a dimensionality not equal 2048.
|
||||||
|
if pred.shape[2] != 1 or pred.shape[3] != 1:
|
||||||
|
pred = adaptive_avg_pool2d(pred, output_size=(1, 1))
|
||||||
|
|
||||||
|
pred_arr[start:end] = pred.cpu().data.numpy().reshape(batch_size, -1)
|
||||||
|
|
||||||
|
if verbose:
|
||||||
|
print(' done')
|
||||||
|
|
||||||
|
return pred_arr
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
|
||||||
|
"""Numpy implementation of the Frechet Distance.
|
||||||
|
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
|
||||||
|
and X_2 ~ N(mu_2, C_2) is
|
||||||
|
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
|
||||||
|
|
||||||
|
Stable version by Dougal J. Sutherland.
|
||||||
|
|
||||||
|
Params:
|
||||||
|
-- mu1 : Numpy array containing the activations of a layer of the
|
||||||
|
inception net (like returned by the function 'get_predictions')
|
||||||
|
for generated samples.
|
||||||
|
-- mu2 : The sample mean over activations, precalculated on an
|
||||||
|
representative data set.
|
||||||
|
-- sigma1: The covariance matrix over activations for generated samples.
|
||||||
|
-- sigma2: The covariance matrix over activations, precalculated on an
|
||||||
|
representative data set.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
-- : The Frechet Distance.
|
||||||
|
"""
|
||||||
|
|
||||||
|
mu1 = np.atleast_1d(mu1)
|
||||||
|
mu2 = np.atleast_1d(mu2)
|
||||||
|
|
||||||
|
sigma1 = np.atleast_2d(sigma1)
|
||||||
|
sigma2 = np.atleast_2d(sigma2)
|
||||||
|
|
||||||
|
assert mu1.shape == mu2.shape, \
|
||||||
|
'Training and test mean vectors have different lengths'
|
||||||
|
assert sigma1.shape == sigma2.shape, \
|
||||||
|
'Training and test covariances have different dimensions'
|
||||||
|
|
||||||
|
diff = mu1 - mu2
|
||||||
|
|
||||||
|
# Product might be almost singular
|
||||||
|
covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
|
||||||
|
if not np.isfinite(covmean).all():
|
||||||
|
msg = ('fid calculation produces singular product; '
|
||||||
|
'adding %s to diagonal of cov estimates') % eps
|
||||||
|
print(msg)
|
||||||
|
offset = np.eye(sigma1.shape[0]) * eps
|
||||||
|
covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
|
||||||
|
|
||||||
|
# Numerical error might give slight imaginary component
|
||||||
|
if np.iscomplexobj(covmean):
|
||||||
|
if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
|
||||||
|
m = np.max(np.abs(covmean.imag))
|
||||||
|
raise ValueError('Imaginary component {}'.format(m))
|
||||||
|
covmean = covmean.real
|
||||||
|
|
||||||
|
tr_covmean = np.trace(covmean)
|
||||||
|
|
||||||
|
return (diff.dot(diff) + np.trace(sigma1) +
|
||||||
|
np.trace(sigma2) - 2 * tr_covmean)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_activation_statistics(images, model, batch_size=64,
|
||||||
|
dims=2048, cuda=False, verbose=False):
|
||||||
|
"""Calculation of the statistics used by the FID.
|
||||||
|
Params:
|
||||||
|
-- images : Numpy array of dimension (n_images, 3, hi, wi). The values
|
||||||
|
must lie between 0 and 1.
|
||||||
|
-- model : Instance of inception model
|
||||||
|
-- batch_size : The images numpy array is split into batches with
|
||||||
|
batch size batch_size. A reasonable batch size
|
||||||
|
depends on the hardware.
|
||||||
|
-- dims : Dimensionality of features returned by Inception
|
||||||
|
-- cuda : If set to True, use GPU
|
||||||
|
-- verbose : If set to True and parameter out_step is given, the
|
||||||
|
number of calculated batches is reported.
|
||||||
|
Returns:
|
||||||
|
-- mu : The mean over samples of the activations of the pool_3 layer of
|
||||||
|
the inception model.
|
||||||
|
-- sigma : The covariance matrix of the activations of the pool_3 layer of
|
||||||
|
the inception model.
|
||||||
|
"""
|
||||||
|
act = get_activations(images, model, batch_size, dims, cuda, verbose)
|
||||||
|
mu = np.mean(act, axis=0)
|
||||||
|
sigma = np.cov(act, rowvar=False)
|
||||||
|
return mu, sigma
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_statistics_of_path(path, model, batch_size, dims, cuda):
|
||||||
|
if path.endswith('.npz'):
|
||||||
|
f = np.load(path)
|
||||||
|
m, s = f['mu'][:], f['sigma'][:]
|
||||||
|
f.close()
|
||||||
|
else:
|
||||||
|
path = pathlib.Path(path)
|
||||||
|
files = list(path.glob('*.jpg')) + list(path.glob('*.png'))
|
||||||
|
|
||||||
|
imgs = np.array([imread(str(fn)).astype(np.float32) for fn in files])
|
||||||
|
|
||||||
|
# Bring images to shape (B, 3, H, W)
|
||||||
|
imgs = imgs.transpose((0, 3, 1, 2))
|
||||||
|
|
||||||
|
# Rescale images to be between 0 and 1
|
||||||
|
imgs /= 255
|
||||||
|
|
||||||
|
m, s = calculate_activation_statistics(imgs, model, batch_size,
|
||||||
|
dims, cuda)
|
||||||
|
|
||||||
|
return m, s
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_fid_given_paths(paths, batch_size, cuda, dims):
|
||||||
|
"""Calculates the FID of two paths"""
|
||||||
|
for p in paths:
|
||||||
|
if not os.path.exists(p):
|
||||||
|
raise RuntimeError('Invalid path: %s' % p)
|
||||||
|
|
||||||
|
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
|
||||||
|
|
||||||
|
model = InceptionV3([block_idx])
|
||||||
|
if cuda:
|
||||||
|
model.cuda()
|
||||||
|
|
||||||
|
m1, s1 = _compute_statistics_of_path(paths[0], model, batch_size,
|
||||||
|
dims, cuda)
|
||||||
|
m2, s2 = _compute_statistics_of_path(paths[1], model, batch_size,
|
||||||
|
dims, cuda)
|
||||||
|
fid_value = calculate_frechet_distance(m1, s1, m2, s2)
|
||||||
|
|
||||||
|
return fid_value
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
args = parser.parse_args()
|
||||||
|
# os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
|
||||||
|
|
||||||
|
fid_value = calculate_fid_given_paths(args.path,
|
||||||
|
args.batch_size,
|
||||||
|
args.gpu != '',
|
||||||
|
args.dims)
|
||||||
|
print('FID: ', fid_value)
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.metrics import f1_score as fs
|
||||||
|
# https://github.com/Jarvisgivemeasuit/DPANet-Pytorch/blob/master/utils/utils.py
|
||||||
|
|
||||||
|
class PixelAccuracy:
|
||||||
|
def __init__(self, ignore_index=-1, eps=1e-7):
|
||||||
|
self.num_correct = 0
|
||||||
|
self.num_instance = 0
|
||||||
|
self.ignore_index = ignore_index
|
||||||
|
self.eps = eps
|
||||||
|
|
||||||
|
def update(self, pred, target):
|
||||||
|
ignore_mask = target != self.ignore_index
|
||||||
|
if pred.size(1) == 1:
|
||||||
|
pred = torch.sigmoid(pred)
|
||||||
|
pred = pred > 0.5
|
||||||
|
else:
|
||||||
|
pred = torch.argmax(pred, dim=1)
|
||||||
|
|
||||||
|
self.num_correct += ((pred.long() == target.long()) * ignore_mask).sum().item()
|
||||||
|
self.num_instance += ignore_mask.sum().item()
|
||||||
|
|
||||||
|
def get(self):
|
||||||
|
return self.num_correct / (self.num_instance + self.eps)
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.num_correct = 0
|
||||||
|
self.num_instance = 0
|
||||||
|
|
||||||
|
|
||||||
|
class MeanIoU:
|
||||||
|
def __init__(self, num_classes, eps=1e-7):
|
||||||
|
if num_classes == 1:
|
||||||
|
self.num_classes = num_classes + 1
|
||||||
|
else:
|
||||||
|
self.num_classes = num_classes
|
||||||
|
self.num_intersection = np.zeros(self.num_classes)
|
||||||
|
self.num_union = np.zeros(self.num_classes)
|
||||||
|
self.eps = eps
|
||||||
|
|
||||||
|
def update(self, pred, target):
|
||||||
|
if pred.size(1) == 1:
|
||||||
|
pred = torch.sigmoid(pred)
|
||||||
|
pred = pred > 0.5
|
||||||
|
else:
|
||||||
|
pred = torch.argmax(pred, dim=1)
|
||||||
|
|
||||||
|
for cur_cls in range(self.num_classes):
|
||||||
|
pred_mask = (pred == cur_cls).byte()
|
||||||
|
target_mask = (target == cur_cls).byte()
|
||||||
|
|
||||||
|
intersection = (pred_mask & target_mask).float().sum()
|
||||||
|
union = (pred_mask | target_mask).float().sum()
|
||||||
|
|
||||||
|
self.num_intersection[cur_cls] += intersection.item()
|
||||||
|
self.num_union[cur_cls] += union.item()
|
||||||
|
|
||||||
|
def get(self, ignore_background=False):
|
||||||
|
if ignore_background:
|
||||||
|
iou_list = (self.num_intersection[:-1] / (self.num_union[:-1] + self.eps))
|
||||||
|
return iou_list.mean(), iou_list.max(), np.where(iou_list == iou_list.max()), iou_list.min(), np.where(iou_list == iou_list.min())
|
||||||
|
else:
|
||||||
|
iou_list = (self.num_intersection / (self.num_union + self.eps))
|
||||||
|
return iou_list.mean(), iou_list.max(), np.where(iou_list == iou_list.max()), iou_list.min(), np.where(iou_list == iou_list.min())
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.num_intersection = np.zeros(self.num_classes)
|
||||||
|
self.num_union = np.zeros(self.num_classes)
|
||||||
|
|
||||||
|
def get_all(self):
|
||||||
|
return (self.num_intersection / (self.num_union + self.eps))
|
||||||
|
|
||||||
|
class Kappa:
|
||||||
|
def __init__(self, num_classes):
|
||||||
|
self.pre_vec = np.zeros(num_classes)
|
||||||
|
self.cor_vec = np.zeros(num_classes)
|
||||||
|
self.tar_vec = np.zeros(num_classes)
|
||||||
|
self.num = num_classes
|
||||||
|
|
||||||
|
def update(self, output, target):
|
||||||
|
pre_array = torch.argmax(output, dim=1)
|
||||||
|
|
||||||
|
for i in range(self.num):
|
||||||
|
pre_mask = (pre_array == i).byte()
|
||||||
|
tar_mask = (target == i).byte()
|
||||||
|
self.cor_vec[i] = (pre_mask & tar_mask).sum().item()
|
||||||
|
self.pre_vec[i] = pre_mask.sum().item()
|
||||||
|
self.tar_vec[i] = tar_mask.sum().item()
|
||||||
|
|
||||||
|
def get(self):
|
||||||
|
assert len(self.pre_vec) == len(self.tar_vec) == len(self.pre_vec)
|
||||||
|
tmp = 0.0
|
||||||
|
for i in range(len(self.tar_vec)):
|
||||||
|
tmp += self.pre_vec[i] * self.tar_vec[i]
|
||||||
|
pe = tmp / (sum(self.tar_vec) ** 2 + 1e-8)
|
||||||
|
p0 = sum(self.cor_vec) / (sum(self.tar_vec) + 1e-8)
|
||||||
|
cohens_coefficient = (p0 - pe) / (1 - pe)
|
||||||
|
return cohens_coefficient
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.pre_vec = np.zeros(self.num)
|
||||||
|
self.cor_vec = np.zeros(self.num)
|
||||||
|
self.tar_vec = np.zeros(self.num)
|
||||||
|
|
||||||
|
|
||||||
|
class F1:
|
||||||
|
def __init__(self):
|
||||||
|
self.score = 0
|
||||||
|
self.num = 0
|
||||||
|
self.all = np.zeros(16)
|
||||||
|
self.map = None
|
||||||
|
self.map_tar = None
|
||||||
|
|
||||||
|
def update(self, output, target):
|
||||||
|
output = torch.argmax(output, dim=1).reshape(-1).cpu()
|
||||||
|
target = target.reshape(-1).cpu()
|
||||||
|
# output = list(output)
|
||||||
|
# target = list(target)
|
||||||
|
self.score += fs(output, target, average='macro')
|
||||||
|
self.num += 1
|
||||||
|
if self.map == None:
|
||||||
|
self.map = output
|
||||||
|
else:
|
||||||
|
self.map = torch.cat([self.map, output])
|
||||||
|
if self.map_tar == None:
|
||||||
|
self.map_tar = target
|
||||||
|
else:
|
||||||
|
self.map_tar = torch.cat([self.map_tar, target])
|
||||||
|
|
||||||
|
def get(self):
|
||||||
|
return self.score / self.num
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.score = 0
|
||||||
|
self.num = 0
|
||||||
|
|
||||||
|
def get_all(self):
|
||||||
|
return fs(self.map, self.map_tar, average=None)
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import numpy as np
|
||||||
|
from sklearn.model_selection import KFold
|
||||||
|
import math
|
||||||
|
from scipy import interpolate
|
||||||
|
|
||||||
|
|
||||||
|
def distance(embeddings1, embeddings2, distance_metric=0):
|
||||||
|
if distance_metric == 0:
|
||||||
|
# Euclidian distance
|
||||||
|
diff = np.subtract(embeddings1, embeddings2)
|
||||||
|
dist = np.sum(np.square(diff), 1)
|
||||||
|
elif distance_metric == 1:
|
||||||
|
# Distance based on cosine similarity
|
||||||
|
dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1)
|
||||||
|
norm = np.linalg.norm(embeddings1, axis=1) * np.linalg.norm(embeddings2, axis=1)
|
||||||
|
similarity = dot / norm
|
||||||
|
dist = np.arccos(similarity) / math.pi
|
||||||
|
else:
|
||||||
|
raise 'Undefined distance metric %d' % distance_metric
|
||||||
|
return dist
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10, distance_metric=0,
|
||||||
|
subtract_mean=False):
|
||||||
|
assert (embeddings1.shape[0] == embeddings2.shape[0])
|
||||||
|
assert (embeddings1.shape[1] == embeddings2.shape[1])
|
||||||
|
nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
|
||||||
|
nrof_thresholds = len(thresholds)
|
||||||
|
k_fold = KFold(n_splits=nrof_folds, shuffle=False)
|
||||||
|
|
||||||
|
tprs = np.zeros((nrof_folds, nrof_thresholds))
|
||||||
|
fprs = np.zeros((nrof_folds, nrof_thresholds))
|
||||||
|
accuracy = np.zeros((nrof_folds))
|
||||||
|
|
||||||
|
indices = np.arange(nrof_pairs)
|
||||||
|
|
||||||
|
for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
|
||||||
|
if subtract_mean:
|
||||||
|
mean = np.mean(np.concatenate([embeddings1[train_set], embeddings2[train_set]]), axis=0)
|
||||||
|
else:
|
||||||
|
mean = 0.0
|
||||||
|
dist = distance(embeddings1 - mean, embeddings2 - mean, distance_metric)
|
||||||
|
|
||||||
|
# Find the best threshold for the fold
|
||||||
|
acc_train = np.zeros((nrof_thresholds))
|
||||||
|
for threshold_idx, threshold in enumerate(thresholds):
|
||||||
|
_, _, acc_train[threshold_idx] = calculate_accuracy(threshold, dist[train_set], actual_issame[train_set])
|
||||||
|
best_threshold_index = np.argmax(acc_train)
|
||||||
|
for threshold_idx, threshold in enumerate(thresholds):
|
||||||
|
tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = calculate_accuracy(threshold,
|
||||||
|
dist[test_set],
|
||||||
|
actual_issame[
|
||||||
|
test_set])
|
||||||
|
best_threshold = thresholds[best_threshold_index]
|
||||||
|
_, _, accuracy[fold_idx] = calculate_accuracy(best_threshold, dist[test_set], actual_issame[test_set])
|
||||||
|
# print('Best threshold: {}'.format(best_threshold))
|
||||||
|
tpr = np.mean(tprs, 0)
|
||||||
|
fpr = np.mean(fprs, 0)
|
||||||
|
return tpr, fpr, accuracy
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_accuracy(threshold, dist, actual_issame):
|
||||||
|
predict_issame = np.less(dist, threshold)
|
||||||
|
tp = np.sum(np.logical_and(predict_issame, actual_issame))
|
||||||
|
fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
|
||||||
|
tn = np.sum(np.logical_and(np.logical_not(predict_issame), np.logical_not(actual_issame)))
|
||||||
|
fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame))
|
||||||
|
|
||||||
|
tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn)
|
||||||
|
fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn)
|
||||||
|
acc = float(tp + tn) / dist.size
|
||||||
|
return tpr, fpr, acc
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10, distance_metric=0,
|
||||||
|
subtract_mean=False):
|
||||||
|
assert (embeddings1.shape[0] == embeddings2.shape[0])
|
||||||
|
assert (embeddings1.shape[1] == embeddings2.shape[1])
|
||||||
|
nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
|
||||||
|
nrof_thresholds = len(thresholds)
|
||||||
|
k_fold = KFold(n_splits=nrof_folds, shuffle=False)
|
||||||
|
|
||||||
|
val = np.zeros(nrof_folds)
|
||||||
|
far = np.zeros(nrof_folds)
|
||||||
|
|
||||||
|
indices = np.arange(nrof_pairs)
|
||||||
|
|
||||||
|
for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
|
||||||
|
if subtract_mean:
|
||||||
|
mean = np.mean(np.concatenate([embeddings1[train_set], embeddings2[train_set]]), axis=0)
|
||||||
|
else:
|
||||||
|
mean = 0.0
|
||||||
|
dist = distance(embeddings1 - mean, embeddings2 - mean, distance_metric)
|
||||||
|
|
||||||
|
# Find the threshold that gives FAR = far_target
|
||||||
|
far_train = np.zeros(nrof_thresholds)
|
||||||
|
for threshold_idx, threshold in enumerate(thresholds):
|
||||||
|
_, far_train[threshold_idx] = calculate_val_far(threshold, dist[train_set], actual_issame[train_set])
|
||||||
|
if np.max(far_train) >= far_target:
|
||||||
|
f = interpolate.interp1d(far_train, thresholds, kind='slinear')
|
||||||
|
threshold = f(far_target)
|
||||||
|
else:
|
||||||
|
threshold = 0.0
|
||||||
|
|
||||||
|
val[fold_idx], far[fold_idx] = calculate_val_far(threshold, dist[test_set], actual_issame[test_set])
|
||||||
|
|
||||||
|
val_mean = np.mean(val)
|
||||||
|
far_mean = np.mean(far)
|
||||||
|
val_std = np.std(val)
|
||||||
|
|
||||||
|
|
||||||
|
return val_mean, val_std, far_mean
|
||||||
|
|
||||||
|
def calculate_val_far(threshold, dist, actual_issame):
|
||||||
|
predict_issame = np.less(dist, threshold)
|
||||||
|
true_accept = np.sum(np.logical_and(predict_issame, actual_issame))
|
||||||
|
false_accept = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
|
||||||
|
n_same = np.sum(actual_issame)
|
||||||
|
n_diff = np.sum(np.logical_not(actual_issame))
|
||||||
|
val = float(true_accept) / float(n_same)
|
||||||
|
far = float(false_accept) / float(n_diff)
|
||||||
|
return val, far
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from math import exp
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
# Classes to re-use window
|
||||||
|
class SSIM(torch.nn.Module):
|
||||||
|
def __init__(self, window_size=11, size_average=True, val_range=None):
|
||||||
|
super(SSIM, self).__init__()
|
||||||
|
self.window_size = window_size
|
||||||
|
self.size_average = size_average
|
||||||
|
self.val_range = val_range
|
||||||
|
|
||||||
|
# Assume 1 channel for SSIM
|
||||||
|
self.channel = 1
|
||||||
|
self.window = create_window(window_size)
|
||||||
|
self.cs_map = None
|
||||||
|
|
||||||
|
def forward(self, img1, img2):
|
||||||
|
(_, channel, _, _) = img1.size()
|
||||||
|
|
||||||
|
if channel == self.channel and self.window.dtype == img1.dtype:
|
||||||
|
window = self.window
|
||||||
|
else:
|
||||||
|
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
|
||||||
|
self.window = window
|
||||||
|
self.channel = channel
|
||||||
|
|
||||||
|
cs, self.cs_map = ssim(img1, img2, -1, window, size_average=self.size_average, full=True)
|
||||||
|
return cs
|
||||||
|
|
||||||
|
|
||||||
|
class MSSSIM(torch.nn.Module):
|
||||||
|
def __init__(self, window_size=11, size_average=True):
|
||||||
|
super(MSSSIM, self).__init__()
|
||||||
|
self.window_size = window_size
|
||||||
|
self.size_average = size_average
|
||||||
|
self.channel = None
|
||||||
|
self.window = None
|
||||||
|
|
||||||
|
def forward(self, img1, img2):
|
||||||
|
(_, channel, _, _) = img1.size()
|
||||||
|
|
||||||
|
if self.window is not None and channel == self.channel and self.window.dtype == img1.dtype:
|
||||||
|
window = self.window
|
||||||
|
else:
|
||||||
|
print("MSSIM: Creating window...")
|
||||||
|
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
|
||||||
|
self.window = window
|
||||||
|
self.channel = channel
|
||||||
|
# return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average, window=window)
|
||||||
|
return msssim_simple(img1, img2, window_size=self.window_size, size_average=self.size_average, window=window)
|
||||||
|
|
||||||
|
|
||||||
|
#############################################
|
||||||
|
# Function
|
||||||
|
|
||||||
|
def gaussian(window_size, sigma):
|
||||||
|
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
|
||||||
|
return gauss/gauss.sum()
|
||||||
|
|
||||||
|
|
||||||
|
def create_window(window_size, channel=1):
|
||||||
|
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
|
||||||
|
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
|
||||||
|
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
|
||||||
|
return window
|
||||||
|
|
||||||
|
|
||||||
|
def structsim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
|
||||||
|
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
|
||||||
|
if val_range is None:
|
||||||
|
if torch.max(img1) > 128:
|
||||||
|
max_val = 255
|
||||||
|
else:
|
||||||
|
max_val = 1
|
||||||
|
|
||||||
|
if torch.min(img1) < -0.5:
|
||||||
|
min_val = -1
|
||||||
|
else:
|
||||||
|
min_val = 0
|
||||||
|
L = max_val - min_val
|
||||||
|
else:
|
||||||
|
L = val_range
|
||||||
|
|
||||||
|
# padd = 10
|
||||||
|
padd = 0
|
||||||
|
(_, channel, height, width) = img1.size()
|
||||||
|
if window is None:
|
||||||
|
real_size = min(window_size, height, width)
|
||||||
|
window = create_window(real_size, channel=channel).to(img1.device)
|
||||||
|
|
||||||
|
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
||||||
|
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
||||||
|
|
||||||
|
mu1_sq = mu1.pow(2)
|
||||||
|
mu2_sq = mu2.pow(2)
|
||||||
|
mu1_mu2 = mu1 * mu2
|
||||||
|
|
||||||
|
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
|
||||||
|
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
|
||||||
|
sigma1 = sigma1_sq.clamp(min=0)**0.5
|
||||||
|
sigma2 = sigma2_sq.clamp(min=0)**0.5
|
||||||
|
# sigma1_test = F.conv2d((img1 - mu1)**2, window, padding=padd, groups=channel)
|
||||||
|
# sigma1_sq_test = sigma1_test.pow(2)
|
||||||
|
|
||||||
|
|
||||||
|
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
|
||||||
|
|
||||||
|
C1 = (0.01 * L) ** 2
|
||||||
|
C2 = (0.03 * L) ** 2
|
||||||
|
|
||||||
|
# v1 = 2.0 * sigma12 + C2
|
||||||
|
# v2 = sigma1_sq + sigma2_sq + C2
|
||||||
|
# cs = torch.mean(v1 / v2) # contrast sensitivity
|
||||||
|
|
||||||
|
l = (2 * mu1_mu2 + C1) / (mu1_sq + mu2_sq + C1)
|
||||||
|
c = (2 * sigma1 * sigma2 + C2) / (sigma1_sq + sigma2_sq + C2)
|
||||||
|
s = (sigma12 + (C2/2.0)) / (sigma1 * sigma2 + (C2/2.0))
|
||||||
|
|
||||||
|
# cs_mean = (c * s).mean()
|
||||||
|
# cs_mean_prod = c.mean() * s.mean()
|
||||||
|
|
||||||
|
return l.mean(), c.mean(), s.mean()
|
||||||
|
|
||||||
|
|
||||||
|
# from datasets.ds_utils import denormalized
|
||||||
|
def ssim(img1, img2, window_size=-1, window=None, size_average=True, full=False, val_range=None):
|
||||||
|
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
|
||||||
|
# img1 = denormalized(img1).clamp(min=0)
|
||||||
|
# img2 = denormalized(img2).clamp(min=0)
|
||||||
|
|
||||||
|
if val_range is None:
|
||||||
|
if torch.max(img1) > 128:
|
||||||
|
max_val = 255
|
||||||
|
else:
|
||||||
|
max_val = 1
|
||||||
|
|
||||||
|
if torch.min(img1) < -0.5:
|
||||||
|
min_val = -1
|
||||||
|
else:
|
||||||
|
min_val = 0
|
||||||
|
L = max_val - min_val
|
||||||
|
else:
|
||||||
|
L = val_range
|
||||||
|
|
||||||
|
padd = 0
|
||||||
|
(_, channel, height, width) = img1.size()
|
||||||
|
if window is None:
|
||||||
|
if window_size > 0:
|
||||||
|
real_size = min(window_size, height, width)
|
||||||
|
window = create_window(real_size, channel=channel).to(img1.device)
|
||||||
|
else:
|
||||||
|
raise ValueError("If window not supplied, window_size must be non negative.")
|
||||||
|
|
||||||
|
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
||||||
|
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
||||||
|
|
||||||
|
mu1_sq = mu1.pow(2)
|
||||||
|
mu2_sq = mu2.pow(2)
|
||||||
|
mu1_mu2 = mu1 * mu2
|
||||||
|
|
||||||
|
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
|
||||||
|
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
|
||||||
|
# sigma1_sq = sigma1_sq.clamp(min=0)**0.5
|
||||||
|
# sigma2_sq = sigma2_sq.clamp(min=0)**0.5
|
||||||
|
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
|
||||||
|
|
||||||
|
# C1 = (0.01 * L) ** 2
|
||||||
|
C2 = (0.03 * L) ** 2
|
||||||
|
|
||||||
|
v1 = 2.0 * sigma12 + C2
|
||||||
|
v2 = sigma1_sq + sigma2_sq + C2
|
||||||
|
cs_map = v1 / v2 # contrast sensitivity
|
||||||
|
cs = torch.mean(cs_map) # contrast sensitivity
|
||||||
|
|
||||||
|
# sigma1 = sigma1_sq.clamp(min=0)**0.5
|
||||||
|
# sigma2 = sigma2_sq.clamp(min=0)**0.5
|
||||||
|
# c = (2 * sigma1 * sigma2 + C2) / (sigma1_sq + sigma2_sq + C2)
|
||||||
|
|
||||||
|
# ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
|
||||||
|
|
||||||
|
if full:
|
||||||
|
return cs, cs_map
|
||||||
|
return cs
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def msssim(img1, img2, window_size=11, size_average=True, val_range=None, normalize=False, window=None):
|
||||||
|
device = img1.device
|
||||||
|
# weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(device)
|
||||||
|
weights = torch.FloatTensor([0.0448, 0.2856, 0.3001]).to(device)
|
||||||
|
levels = weights.size()[0]
|
||||||
|
# mssim = []
|
||||||
|
mcs = []
|
||||||
|
for _ in range(levels):
|
||||||
|
cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=False, val_range=val_range, window=window)
|
||||||
|
# mssim.append(sim)
|
||||||
|
mcs.append(cs)
|
||||||
|
|
||||||
|
img1 = F.avg_pool2d(img1, (2, 2))
|
||||||
|
img2 = F.avg_pool2d(img2, (2, 2))
|
||||||
|
|
||||||
|
# mssim = torch.stack(mssim)
|
||||||
|
mcs = torch.stack(mcs)
|
||||||
|
|
||||||
|
# Normalize (to avoid NaNs during training unstable models, not compliant with original definition)
|
||||||
|
if normalize:
|
||||||
|
# mssim = (mssim + 1) / 2
|
||||||
|
mcs = (mcs + 1) / 2
|
||||||
|
|
||||||
|
# pow1 = mcs ** weights
|
||||||
|
# pow2 = mssim ** weights
|
||||||
|
# From Matlab implementation https://ece.uwaterloo.ca/~z70wang/research/iwssim/
|
||||||
|
# output = torch.prod(pow1[:-1]) * pow2[-1]
|
||||||
|
output = mcs[1]
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def msssim_simple(img1, img2, window_size=11, size_average=True, val_range=None, normalize=False, window=None):
|
||||||
|
k = (2,2)
|
||||||
|
img1 = F.avg_pool2d(img1, k)
|
||||||
|
img2 = F.avg_pool2d(img2, k)
|
||||||
|
cs = ssim(img1, img2, window_size=window_size, size_average=size_average, val_range=val_range, window=window)
|
||||||
|
return cs
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
## Tripelet Loss
|
||||||
|
## Core Idea:
|
||||||
|
## The distance of Anchor and Positive should greater than the distance of Achore and Negative.
|
||||||
|
## L(A, P, N) = max(||f(A) - f(P)||^2 - ||f(A) - f(N)||^2 + a, 0)
|
||||||
|
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
class AverageMeter:
|
||||||
|
def __init__(self):
|
||||||
|
self.count = 0
|
||||||
|
self.sum = 0
|
||||||
|
self.avg = 0
|
||||||
|
self.val = 0
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.count = 0
|
||||||
|
self.sum = 0
|
||||||
|
self.avg = 0
|
||||||
|
self.val = 0
|
||||||
|
|
||||||
|
def update(self, val, n=1):
|
||||||
|
self.val = val
|
||||||
|
self.sum += val * n
|
||||||
|
self.count += n
|
||||||
|
self.avg = self.sum / self.count
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class AverageMeterDict:
|
||||||
|
def __init__(self):
|
||||||
|
self.count = 0
|
||||||
|
|
||||||
|
self.sum_dict = {}
|
||||||
|
self.avg_dict = {}
|
||||||
|
self.val_dict = {}
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.count = 0
|
||||||
|
self.sum_dict = {}
|
||||||
|
self.avg_dict = {}
|
||||||
|
self.val_dict = {}
|
||||||
|
|
||||||
|
def update(self, adict, n=1):
|
||||||
|
|
||||||
|
self.count += n
|
||||||
|
|
||||||
|
# first init
|
||||||
|
if len(self.val_dict) == 0 :
|
||||||
|
self.val_dict = adict.copy()
|
||||||
|
self.sum_dict = adict.copy()
|
||||||
|
self.avg_dict = adict.copy()
|
||||||
|
|
||||||
|
else:
|
||||||
|
for key, item in adict.items():
|
||||||
|
self.val_dict[key] = item
|
||||||
|
self.sum_dict[key] += item * n
|
||||||
|
self.avg_dict[key] = (self.sum_dict[key] / self.count)
|
||||||
|
|
||||||
|
|
||||||
|
def print_msg(self, debug="avg", split=""):
|
||||||
|
msg = ""
|
||||||
|
|
||||||
|
if debug == "sum":
|
||||||
|
tmp_dict = self.avg_dict
|
||||||
|
elif debug == "val":
|
||||||
|
tmp_dict = self.val_dict
|
||||||
|
else:
|
||||||
|
tmp_dict = self.avg_dict
|
||||||
|
|
||||||
|
for (key, item) in tmp_dict.items():
|
||||||
|
msg += f"{key}={item:0.6f} {split}"
|
||||||
|
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
def print_numpy(x, val=True, shp=False):
|
||||||
|
"""Print the mean, min, max, median, std, and size of a numpy array
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
val (bool) -- if print the values of the numpy array
|
||||||
|
shp (bool) -- if print the shape of the numpy array
|
||||||
|
"""
|
||||||
|
x = x.astype(np.float64)
|
||||||
|
if shp:
|
||||||
|
print('shape,', x.shape)
|
||||||
|
if val:
|
||||||
|
x = x.flatten()
|
||||||
|
print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (
|
||||||
|
np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
|
||||||
|
|
||||||
|
|
||||||
|
def mkdirs(paths):
|
||||||
|
"""create empty directories if they don't exist
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
paths (str list) -- a list of directory paths
|
||||||
|
"""
|
||||||
|
if isinstance(paths, list) and not isinstance(paths, str):
|
||||||
|
for path in paths:
|
||||||
|
mkdir(path)
|
||||||
|
else:
|
||||||
|
mkdir(paths)
|
||||||
|
|
||||||
|
|
||||||
|
def mkdir(path):
|
||||||
|
"""create a single empty directory if it didn't exist
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
path (str) -- a single directory path
|
||||||
|
"""
|
||||||
|
if not os.path.exists(path):
|
||||||
|
os.makedirs(path)
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import dominate
|
||||||
|
import ntpath
|
||||||
|
from dominate.tags import meta, h3, table, tr, td, p, a, img, br
|
||||||
|
import os
|
||||||
|
from subprocess import Popen, PIPE
|
||||||
|
from skimage.transform import resize
|
||||||
|
from pathlib import Path
|
||||||
|
import math
|
||||||
|
|
||||||
|
from common import utils
|
||||||
|
from common.image import save_image
|
||||||
|
|
||||||
|
class HTML():
|
||||||
|
"""This HTML class allows us to save images and write texts into a single HTML file.
|
||||||
|
|
||||||
|
It consists of functions such as <add_header> (add a text header to the HTML file),
|
||||||
|
<add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk).
|
||||||
|
It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, web_dir, title, opt, refresh=0):
|
||||||
|
"""Initialize the HTML classes
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/
|
||||||
|
title (str) -- the webpage name
|
||||||
|
refresh (int) -- how often the website refresh itself; if 0; no refreshing
|
||||||
|
"""
|
||||||
|
self.opt = opt
|
||||||
|
|
||||||
|
self.title = title
|
||||||
|
self.web_dir = Path(web_dir)
|
||||||
|
self.img_dir = self.web_dir.joinpath("images")
|
||||||
|
self.img_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
self.doc = dominate.document(title=title)
|
||||||
|
|
||||||
|
if refresh > 0:
|
||||||
|
with self.doc.head:
|
||||||
|
meta(http_equiv="refresh", content=str(refresh))
|
||||||
|
|
||||||
|
def get_image_dir(self):
|
||||||
|
"""Return the directory that stores images"""
|
||||||
|
return self.img_dir
|
||||||
|
|
||||||
|
def add_header(self, text):
|
||||||
|
"""Insert a header to the HTML file
|
||||||
|
Parameters:
|
||||||
|
text (str) -- the header text
|
||||||
|
"""
|
||||||
|
with self.doc:
|
||||||
|
h3(text)
|
||||||
|
|
||||||
|
def add_images(self, ims, txts, links, width=400):
|
||||||
|
"""add images to the HTML file
|
||||||
|
Parameters:
|
||||||
|
ims (str list) -- a list of image paths
|
||||||
|
txts (str list) -- a list of image names shown on the website
|
||||||
|
links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page
|
||||||
|
"""
|
||||||
|
|
||||||
|
ncol = 6
|
||||||
|
nrow = math.ceil( len(ims) / ncol )
|
||||||
|
|
||||||
|
for irow in range(nrow):
|
||||||
|
|
||||||
|
itable = table(border=1, style="table-layout: fixed;") # Insert a table
|
||||||
|
self.doc.add(itable)
|
||||||
|
|
||||||
|
with itable:
|
||||||
|
with tr():
|
||||||
|
|
||||||
|
# for im, txt, link in zip(ims, txts, links):
|
||||||
|
for icol in range(ncol):
|
||||||
|
idx = ncol * irow + icol
|
||||||
|
if idx >= len(ims): break
|
||||||
|
|
||||||
|
with td(style="word-wrap: break-word;", halign="center", valign="top"):
|
||||||
|
with p():
|
||||||
|
with a(href=links[idx]):
|
||||||
|
img(style="width:%dpx" % width, src=ims[idx])
|
||||||
|
br()
|
||||||
|
p(txts[idx])
|
||||||
|
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
"""save the current content to the HMTL file"""
|
||||||
|
|
||||||
|
path_html = self.web_dir.joinpath("index.html")
|
||||||
|
|
||||||
|
with open(str(path_html), 'wt') as f:
|
||||||
|
f.write(self.doc.render())
|
||||||
|
|
||||||
|
|
||||||
|
def save_images(self, visuals, image_path, aspect_ratio=1.0, width=256):
|
||||||
|
"""Save images to the disk.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
|
||||||
|
visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs
|
||||||
|
image_path (str) -- the string is used to create image paths
|
||||||
|
aspect_ratio (float) -- the aspect ratio of saved images
|
||||||
|
width (int) -- the images will be resized to width x width
|
||||||
|
|
||||||
|
This function will save images stored in 'visuals' to the HTML file specified by 'webpage'.
|
||||||
|
"""
|
||||||
|
image_dir = self.get_image_dir()
|
||||||
|
short_path = ntpath.basename(image_path[0])
|
||||||
|
short_path1 = ntpath.basename(ntpath.dirname(image_path[0]))
|
||||||
|
short_path = short_path1 + '-' + short_path
|
||||||
|
name = os.path.splitext(short_path)[0]
|
||||||
|
|
||||||
|
print(f"image_dir={image_dir}, short_path={short_path}, name={name}")
|
||||||
|
|
||||||
|
self.add_header(name)
|
||||||
|
ims, txts, links = [], [], []
|
||||||
|
|
||||||
|
for label, im_data in visuals.items():
|
||||||
|
im = utils.tensor2im(im_data)
|
||||||
|
image_name = '%s_%s.png' % (name, label)
|
||||||
|
save_path = os.path.join(image_dir, image_name)
|
||||||
|
h, w, _ = im.shape
|
||||||
|
if aspect_ratio > 1.0:
|
||||||
|
#im = imresize(im, (h, int(w * aspect_ratio)), interp='bicubic')
|
||||||
|
im = resize(im, (h, int(w * aspect_ratio)))
|
||||||
|
if aspect_ratio < 1.0:
|
||||||
|
#im = imresize(im, (int(h / aspect_ratio), w), interp='bicubic')
|
||||||
|
im = resize(im, (int(h / aspect_ratio), w))
|
||||||
|
|
||||||
|
save_image(im, save_path)
|
||||||
|
|
||||||
|
ims.append(image_name)
|
||||||
|
txts.append(label)
|
||||||
|
links.append(image_name)
|
||||||
|
self.add_images(ims, txts, links, width=width)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': # we show an example usage here.
|
||||||
|
html = HTML('web/', 'test_html', opt=None)
|
||||||
|
html.add_header('hello world')
|
||||||
|
|
||||||
|
ims, txts, links = [], [], []
|
||||||
|
for n in range(4):
|
||||||
|
ims.append('image_%d.png' % n)
|
||||||
|
txts.append('text_%d' % n)
|
||||||
|
links.append('image_%d.png' % n)
|
||||||
|
html.add_images(ims, txts, links)
|
||||||
|
html.save()
|
||||||
@@ -0,0 +1,413 @@
|
|||||||
|
import cv2
|
||||||
|
from matplotlib import pyplot as plt
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
import seaborn as sns
|
||||||
|
from csl_common.utils.nn import to_numpy
|
||||||
|
|
||||||
|
|
||||||
|
def denormalize(tensor):
|
||||||
|
if tensor.shape[1] == 3:
|
||||||
|
tensor[:, 0] += 0.518
|
||||||
|
tensor[:, 1] += 0.418
|
||||||
|
tensor[:, 2] += 0.361
|
||||||
|
elif tensor.shape[-1] == 3:
|
||||||
|
tensor[..., 0] += 0.518
|
||||||
|
tensor[..., 1] += 0.418
|
||||||
|
tensor[..., 2] += 0.361
|
||||||
|
|
||||||
|
def denormalized(tensor):
|
||||||
|
if isinstance(tensor, np.ndarray):
|
||||||
|
t = tensor.copy()
|
||||||
|
else:
|
||||||
|
t = tensor.clone()
|
||||||
|
denormalize(t)
|
||||||
|
return t
|
||||||
|
|
||||||
|
def color_map(data, vmin=None, vmax=None, cmap=plt.cm.viridis):
|
||||||
|
if vmin is None:
|
||||||
|
vmin = data.min()
|
||||||
|
if vmax is None:
|
||||||
|
vmax = data.max()
|
||||||
|
val = np.maximum(vmin, np.minimum(vmax, data))
|
||||||
|
norm = (val-vmin)/(vmax-vmin)
|
||||||
|
cm = cmap(norm)
|
||||||
|
if isinstance(cm, tuple):
|
||||||
|
return cm[:3]
|
||||||
|
if len(cm.shape) > 2:
|
||||||
|
cm = cm[:,:,:3]
|
||||||
|
return cm
|
||||||
|
|
||||||
|
|
||||||
|
# take an array of shape (n, height, width) or (n, height, width, channels)
|
||||||
|
# and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)
|
||||||
|
def make_grid(data, padsize=2, padval=255, nCols=10, dsize=None, fx=None, fy=None, normalize=False):
|
||||||
|
# if not isinstance(data, np.ndarray):
|
||||||
|
data = np.array(data)
|
||||||
|
if data.shape[0] == 0:
|
||||||
|
return
|
||||||
|
if data.shape[1] == 3:
|
||||||
|
data = data.transpose((0,2,3,1))
|
||||||
|
if data.dtype == np.float64:
|
||||||
|
data = data.astype(np.float32)
|
||||||
|
if normalize:
|
||||||
|
data -= data.min()
|
||||||
|
data /= data.max()
|
||||||
|
else:
|
||||||
|
data[data < 0] = 0
|
||||||
|
# data[data > 1] = 1
|
||||||
|
|
||||||
|
# force the number of filters to be square
|
||||||
|
# n = int(np.ceil(np.sqrt(data.shape[0])))
|
||||||
|
c = nCols
|
||||||
|
r = int(np.ceil(data.shape[0]/float(c)))
|
||||||
|
|
||||||
|
padding = ((0, r*c - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
|
||||||
|
data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
|
||||||
|
|
||||||
|
# tile the filters into an image
|
||||||
|
data = data.reshape((r, c) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
|
||||||
|
data = data.reshape((r * data.shape[1], c * data.shape[3]) + data.shape[4:])
|
||||||
|
|
||||||
|
if dsize is not None or fx is not None or fy is not None:
|
||||||
|
data = cv2.resize(data, dsize=dsize, fx=fx, fy=fy, interpolation=cv2.INTER_LANCZOS4)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def vis_square(data, padsize=1, padval=0, wait=0, nCols=10, title='results', dsize=None, fx=None, fy=None, normalize=False):
|
||||||
|
img = make_grid(data, padsize=padsize, padval=padval, nCols=nCols, dsize=dsize, fx=fx, fy=fy, normalize=normalize)
|
||||||
|
cv2.imshow(title, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
|
||||||
|
cv2.waitKey(wait)
|
||||||
|
|
||||||
|
|
||||||
|
def cvt32FtoU8(img):
|
||||||
|
return (img * 255.0).astype(np.uint8)
|
||||||
|
|
||||||
|
|
||||||
|
def to_disp_image(img, denorm=False, output_dtype=np.uint8):
|
||||||
|
if not isinstance(img, np.ndarray):
|
||||||
|
img = img.detach().cpu().numpy()
|
||||||
|
img = img.astype(np.float32).copy()
|
||||||
|
if img.shape[0] == 3:
|
||||||
|
img = img.transpose((1, 2, 0)).copy()
|
||||||
|
if denorm:
|
||||||
|
img = denormalized(img)
|
||||||
|
if img.max() > 2.00:
|
||||||
|
if isinstance(img, np.ndarray):
|
||||||
|
img /= 255.0
|
||||||
|
else:
|
||||||
|
raise ValueError("Image data in wrong value range (min/max={:.2f}/{:.2f}).".format(img.min(), img.max()))
|
||||||
|
img = np.clip(img, a_min=0, a_max=1)
|
||||||
|
if output_dtype == np.uint8:
|
||||||
|
img = cvt32FtoU8(img)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def to_disp_images(images, denorm=False):
|
||||||
|
return [to_disp_image(i, denorm) for i in images]
|
||||||
|
|
||||||
|
|
||||||
|
def add_frames_to_images(images, labels, label_colors, gt_labels=None):
|
||||||
|
import collections
|
||||||
|
if not isinstance(labels, (collections.Sequence, np.ndarray)):
|
||||||
|
labels = [labels] * len(images)
|
||||||
|
new_images = to_disp_images(images)
|
||||||
|
for idx, (disp, label) in enumerate(zip(new_images, labels)):
|
||||||
|
frame_width = 3
|
||||||
|
bgr = label_colors[label]
|
||||||
|
cv2.rectangle(disp,
|
||||||
|
(frame_width // 2, frame_width // 2),
|
||||||
|
(disp.shape[1] - frame_width // 2, disp.shape[0] - frame_width // 2),
|
||||||
|
color=bgr,
|
||||||
|
thickness=frame_width)
|
||||||
|
|
||||||
|
if gt_labels is not None:
|
||||||
|
radius = 8
|
||||||
|
color = (0, 1, 0) if gt_labels[idx] == label else (1, 0, 0)
|
||||||
|
cv2.circle(disp, (disp.shape[1] - 2*radius, 2*radius), radius, color, -1)
|
||||||
|
return new_images
|
||||||
|
|
||||||
|
|
||||||
|
def add_cirle_to_images(images, intensities, cmap=plt.cm.viridis, radius=10):
|
||||||
|
new_images = to_disp_images(images)
|
||||||
|
for idx, (disp, val) in enumerate(zip(new_images, intensities)):
|
||||||
|
# color = (0, 1, 0) if gt_labels[idx] == label else (1, 0, 0)
|
||||||
|
# color = plt_colors.to_rgb(val)
|
||||||
|
if isinstance(val, float):
|
||||||
|
color = cmap(val).ravel()
|
||||||
|
else:
|
||||||
|
color = val
|
||||||
|
cv2.circle(disp, (2*radius, 2*radius), radius, color, -1)
|
||||||
|
# new_images.append(disp)
|
||||||
|
return new_images
|
||||||
|
|
||||||
|
|
||||||
|
def get_pos_in_image(loc, text_size, image_shape):
|
||||||
|
bottom_offset = int(6*text_size)
|
||||||
|
right_offset = int(95*text_size)
|
||||||
|
line_height = int(35*text_size)
|
||||||
|
mid_offset = right_offset
|
||||||
|
top_offset = line_height + int(0.05*line_height)
|
||||||
|
if loc == 'tl':
|
||||||
|
pos = (2, top_offset)
|
||||||
|
elif loc == 'tr':
|
||||||
|
pos = (image_shape[1]-right_offset, top_offset)
|
||||||
|
elif loc == 'tr+1':
|
||||||
|
pos = (image_shape[1]-right_offset, top_offset + line_height)
|
||||||
|
elif loc == 'tr+2':
|
||||||
|
pos = (image_shape[1]-right_offset, top_offset + line_height*2)
|
||||||
|
elif loc == 'bl':
|
||||||
|
pos = (2, image_shape[0]-bottom_offset)
|
||||||
|
elif loc == 'bl-1':
|
||||||
|
pos = (2, image_shape[0]-bottom_offset-line_height)
|
||||||
|
elif loc == 'bl-2':
|
||||||
|
pos = (2, image_shape[0]-bottom_offset-2*line_height)
|
||||||
|
# elif loc == 'bm':
|
||||||
|
# pos = (mid_offset, image_shape[0]-bottom_offset)
|
||||||
|
# elif loc == 'bm-1':
|
||||||
|
# pos = (mid_offset, image_shape[0]-bottom_offset-line_height)
|
||||||
|
elif loc == 'br':
|
||||||
|
pos = (image_shape[1]-right_offset, image_shape[0]-bottom_offset)
|
||||||
|
elif loc == 'br-1':
|
||||||
|
pos = (image_shape[1]-right_offset, image_shape[0]-bottom_offset-line_height)
|
||||||
|
elif loc == 'br-2':
|
||||||
|
pos = (image_shape[1]-right_offset, image_shape[0]-bottom_offset-2*line_height)
|
||||||
|
elif loc == 'bm':
|
||||||
|
pos = (image_shape[1]-right_offset*2, image_shape[0]-bottom_offset)
|
||||||
|
elif loc == 'bm-1':
|
||||||
|
pos = (image_shape[1]-right_offset*2, image_shape[0]-bottom_offset-line_height)
|
||||||
|
elif loc == 'bm-2':
|
||||||
|
pos = (image_shape[1]-right_offset*2, image_shape[0]-bottom_offset-2*line_height)
|
||||||
|
else:
|
||||||
|
raise ValueError("Unknown location {}".format(loc))
|
||||||
|
return pos
|
||||||
|
|
||||||
|
|
||||||
|
def add_id_to_images(images, ids, gt_ids=None, loc='tl', color=(1,1,1), size=0.7, thickness=1):
|
||||||
|
new_images = to_disp_images(images)
|
||||||
|
for idx, (disp, val) in enumerate(zip(new_images, ids)):
|
||||||
|
if gt_ids is not None:
|
||||||
|
color = (0,1,0) if ids[idx] == gt_ids[idx] else (1,0,0)
|
||||||
|
# if val != 0:
|
||||||
|
pos = get_pos_in_image(loc, size, disp.shape)
|
||||||
|
cv2.putText(disp, str(val), pos, cv2.FONT_HERSHEY_DUPLEX, size, color, thickness, cv2.LINE_AA)
|
||||||
|
return new_images
|
||||||
|
|
||||||
|
|
||||||
|
def add_error_to_images(images, errors, loc='bl', size=0.65, vmin=0., vmax=30.0, thickness=1,
|
||||||
|
format_string='{:.1f}', colors=None):
|
||||||
|
new_images = to_disp_images(images)
|
||||||
|
if colors is None:
|
||||||
|
colors = color_map(to_numpy(errors), cmap=plt.cm.jet, vmin=vmin, vmax=vmax)
|
||||||
|
if images[0].dtype == np.uint8:
|
||||||
|
colors *= 255
|
||||||
|
for disp, err, color in zip(new_images, errors, colors):
|
||||||
|
pos = get_pos_in_image(loc, size, disp.shape)
|
||||||
|
cv2.putText(disp, format_string.format(err), pos, cv2.FONT_HERSHEY_DUPLEX, size, color, thickness, cv2.LINE_AA)
|
||||||
|
return new_images
|
||||||
|
|
||||||
|
|
||||||
|
def add_landmarks_to_images(images, landmarks, color=None, radius=2, gt_landmarks=None,
|
||||||
|
lm_errs=None, lm_confs=None, lm_rec_errs=None,
|
||||||
|
draw_dots=True, draw_wireframe=False, draw_gt_offsets=False, landmarks_to_draw=None,
|
||||||
|
offset_line_color=None):
|
||||||
|
|
||||||
|
def draw_wireframe_lines(img, lms):
|
||||||
|
pts = lms.reshape((-1,1,2)).astype(np.int32)
|
||||||
|
cv2.polylines(img, [pts[:17]], isClosed=False, color=color, lineType=cv2.LINE_AA) # head outline
|
||||||
|
cv2.polylines(img, [pts[17:22]], isClosed=False, color=color, lineType=cv2.LINE_AA) # left eyebrow
|
||||||
|
cv2.polylines(img, [pts[22:27]], isClosed=False, color=color, lineType=cv2.LINE_AA) # right eyebrow
|
||||||
|
cv2.polylines(img, [pts[27:31]], isClosed=False, color=color, lineType=cv2.LINE_AA) # nose vert
|
||||||
|
cv2.polylines(img, [pts[31:36]], isClosed=False, color=color, lineType=cv2.LINE_AA) # nose hor
|
||||||
|
cv2.polylines(img, [pts[36:42]], isClosed=True, color=color, lineType=cv2.LINE_AA) # left eye
|
||||||
|
cv2.polylines(img, [pts[42:48]], isClosed=True, color=color, lineType=cv2.LINE_AA) # right eye
|
||||||
|
cv2.polylines(img, [pts[48:60]], isClosed=True, color=color, lineType=cv2.LINE_AA) # outer mouth
|
||||||
|
cv2.polylines(img, [pts[60:68]], isClosed=True, color=color, lineType=cv2.LINE_AA) # inner mouth
|
||||||
|
|
||||||
|
def draw_wireframe_lines_98(img, lms):
|
||||||
|
pts = lms.reshape((-1,1,2)).astype(np.int32)
|
||||||
|
cv2.polylines(img, [pts[:33]], isClosed=False, color=color, lineType=cv2.LINE_AA) # head outline
|
||||||
|
cv2.polylines(img, [pts[33:42]], isClosed=True, color=color, lineType=cv2.LINE_AA) # left eyebrow
|
||||||
|
# cv2.polylines(img, [pts[38:42]], isClosed=False, color=color, lineType=cv2.LINE_AA) # right eyebrow
|
||||||
|
cv2.polylines(img, [pts[42:51]], isClosed=True, color=color, lineType=cv2.LINE_AA) # nose vert
|
||||||
|
cv2.polylines(img, [pts[51:55]], isClosed=False, color=color, lineType=cv2.LINE_AA) # nose hor
|
||||||
|
cv2.polylines(img, [pts[55:60]], isClosed=False, color=color, lineType=cv2.LINE_AA) # left eye
|
||||||
|
cv2.polylines(img, [pts[60:68]], isClosed=True, color=color, lineType=cv2.LINE_AA) # right eye
|
||||||
|
cv2.polylines(img, [pts[68:76]], isClosed=True, color=color, lineType=cv2.LINE_AA) # outer mouth
|
||||||
|
cv2.polylines(img, [pts[76:88]], isClosed=True, color=color, lineType=cv2.LINE_AA) # inner mouth
|
||||||
|
cv2.polylines(img, [pts[88:96]], isClosed=True, color=color, lineType=cv2.LINE_AA) # inner mouth
|
||||||
|
|
||||||
|
def draw_offset_lines(img, lms, gt_lms, errs):
|
||||||
|
if gt_lms.sum() == 0:
|
||||||
|
return
|
||||||
|
if lm_errs is None:
|
||||||
|
# if offset_line_color is None:
|
||||||
|
offset_line_color = (1,1,1)
|
||||||
|
colors = [offset_line_color] * len(lms)
|
||||||
|
else:
|
||||||
|
colors = color_map(errs, cmap=plt.cm.jet, vmin=0, vmax=15.0)
|
||||||
|
if img.dtype == np.uint8:
|
||||||
|
colors *= 255
|
||||||
|
for i, (p1, p2) in enumerate(zip(lms, gt_lms)):
|
||||||
|
if landmarks_to_draw is None or i in landmarks_to_draw:
|
||||||
|
if p1.min() > 0:
|
||||||
|
cv2.line(img, tuple(p1.astype(int)), tuple(p2.astype(int)), colors[i], thickness=1, lineType=cv2.LINE_AA)
|
||||||
|
|
||||||
|
new_images = to_disp_images(images)
|
||||||
|
landmarks = to_numpy(landmarks)
|
||||||
|
gt_landmarks = to_numpy(gt_landmarks)
|
||||||
|
lm_errs = to_numpy(lm_errs)
|
||||||
|
img_size = new_images[0].shape[0]
|
||||||
|
default_color = (255,255,255)
|
||||||
|
|
||||||
|
if gt_landmarks is not None and draw_gt_offsets:
|
||||||
|
for img_id in range(len(new_images)):
|
||||||
|
if gt_landmarks[img_id].sum() == 0:
|
||||||
|
continue
|
||||||
|
dists = None
|
||||||
|
if lm_errs is not None:
|
||||||
|
dists = lm_errs[img_id]
|
||||||
|
draw_offset_lines(new_images[img_id], landmarks[img_id], gt_landmarks[img_id], dists)
|
||||||
|
|
||||||
|
for img_id, (disp, lm) in enumerate(zip(new_images, landmarks)):
|
||||||
|
if len(lm) in [68, 21, 19, 98, 8, 5, 38]:
|
||||||
|
if draw_dots:
|
||||||
|
for lm_id in range(0,len(lm)):
|
||||||
|
if landmarks_to_draw is None or lm_id in landmarks_to_draw or len(lm) != 68:
|
||||||
|
lm_color = color
|
||||||
|
if lm_color is None:
|
||||||
|
if lm_errs is not None:
|
||||||
|
lm_color = color_map(lm_errs[img_id, lm_id], cmap=plt.cm.jet, vmin=0, vmax=1.0)
|
||||||
|
else:
|
||||||
|
lm_color = default_color
|
||||||
|
# if lm_errs is not None and lm_errs[img_id, lm_id] > 40.0:
|
||||||
|
# lm_color = (1,0,0)
|
||||||
|
cv2.circle(disp, tuple(lm[lm_id].astype(int).clip(0, disp.shape[0]-1)), radius=radius, color=lm_color, thickness=-1, lineType=cv2.LINE_AA)
|
||||||
|
if lm_confs is not None:
|
||||||
|
max_radius = img_size * 0.05
|
||||||
|
try:
|
||||||
|
conf_radius = max(2, int((1-lm_confs[img_id, lm_id]) * max_radius))
|
||||||
|
except ValueError:
|
||||||
|
conf_radius = 2
|
||||||
|
# if lm_confs[img_id, lm_id] > 0.4:
|
||||||
|
cirle_color = (0,0,255)
|
||||||
|
# if lm_confs[img_id, lm_id] < is_good_landmark(lm_confs, lm_rec_errs):
|
||||||
|
# if not is_good_landmark(lm_confs[img_id, lm_id], lm_rec_errs[img_id, lm_id]):
|
||||||
|
if lm_errs[img_id, lm_id] > 10.0:
|
||||||
|
cirle_color = (255,0,0)
|
||||||
|
cv2.circle(disp, tuple(lm[lm_id].astype(int)), conf_radius, cirle_color, 1, lineType=cv2.LINE_AA)
|
||||||
|
|
||||||
|
# Draw outline if we actually have 68 valid landmarks.
|
||||||
|
# Landmarks can be zeros for UMD landmark format (21 points).
|
||||||
|
if draw_wireframe:
|
||||||
|
nlms = (np.count_nonzero(lm.sum(axis=1)))
|
||||||
|
if nlms == 68:
|
||||||
|
draw_wireframe_lines(disp, lm)
|
||||||
|
elif nlms == 98:
|
||||||
|
draw_wireframe_lines_98(disp, lm)
|
||||||
|
else:
|
||||||
|
# colors = ['tab:gray', 'tab:orange', 'tab:brown', 'tab:pink', 'tab:cyan', 'tab:olive', 'tab:red', 'tab:blue']
|
||||||
|
# colors_rgb = list(map(plt_colors.to_rgb, colors))
|
||||||
|
|
||||||
|
colors = sns.color_palette("Set1", n_colors=14)
|
||||||
|
for i in range(0,len(lm)):
|
||||||
|
cv2.circle(disp, tuple(lm[i].astype(int)), radius=radius, color=colors[i], thickness=2, lineType=cv2.LINE_AA)
|
||||||
|
return new_images
|
||||||
|
|
||||||
|
|
||||||
|
def draw_z(z_vecs):
|
||||||
|
|
||||||
|
fy = 1
|
||||||
|
width = 10
|
||||||
|
z_zoomed = []
|
||||||
|
for lvl, _ft in enumerate(to_numpy(z_vecs)):
|
||||||
|
# _ft = (_ft-_ft.min())/(_ft.max()-_ft.min())
|
||||||
|
vmin = 0 if lvl == 0 else -1
|
||||||
|
|
||||||
|
canvas = np.zeros((int(fy*len(_ft)), width, 3))
|
||||||
|
canvas[:int(fy*len(_ft)), :] = color_map(cv2.resize(_ft.reshape(-1,1), dsize=(width, int(fy*len(_ft))),
|
||||||
|
interpolation=cv2.INTER_NEAREST), vmin=-1.0, vmax=1.0)
|
||||||
|
z_zoomed.append(canvas)
|
||||||
|
return make_grid(z_zoomed, nCols=len(z_vecs), padsize=1, padval=0).transpose((1,0,2))
|
||||||
|
|
||||||
|
|
||||||
|
def overlay_heatmap(img, hm, heatmap_opacity=0.45):
|
||||||
|
img_dtype = img.dtype
|
||||||
|
img_new = img.copy()
|
||||||
|
if img_new.dtype == np.uint8:
|
||||||
|
img_new = img_new.astype(np.float32) / 255.0
|
||||||
|
|
||||||
|
# hm = np.clip(hm, a_min=0, a_max=1.0)
|
||||||
|
hm_colored = color_map(hm**3, vmin=0, vmax=1.0, cmap=plt.cm.inferno)
|
||||||
|
if len(hm.shape) > 2:
|
||||||
|
mask = cv2.blur(hm, ksize=(3, 3))
|
||||||
|
print('mask', mask.dtype)
|
||||||
|
mask = mask.mean(axis=2)
|
||||||
|
mask = mask > 0.05
|
||||||
|
for c in range(3):
|
||||||
|
# img_new[...,c] = img[...,c] + hm[...,c]
|
||||||
|
img_new[..., c][mask] = img[..., c][mask] * 0.7 + hm[..., c][mask] * 0.3
|
||||||
|
else:
|
||||||
|
# mask = mask > 0.05
|
||||||
|
# img_new[mask] = img[mask] * 0.7 + hm_col[mask] * 0.3
|
||||||
|
# heatmap_opacity = 0.7
|
||||||
|
if hm_colored.shape != img.shape:
|
||||||
|
hm_colored = cv2.resize(hm_colored, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_CUBIC)
|
||||||
|
img_new = img_new + hm_colored * heatmap_opacity
|
||||||
|
|
||||||
|
img_new = img_new.clip(0, 1)
|
||||||
|
if img_dtype == np.uint8:
|
||||||
|
img_new = cvt32FtoU8(img_new)
|
||||||
|
assert img_new.dtype == img.dtype
|
||||||
|
assert img_new.shape == img.shape
|
||||||
|
return img_new
|
||||||
|
|
||||||
|
|
||||||
|
def draw_z_vecs(levels_z, ncols, size, vmin=-1, vmax=1, vertical=False):
|
||||||
|
z_fy = 1.0
|
||||||
|
width, height = [int(x) for x in size[:2]]
|
||||||
|
def draw_z(z):
|
||||||
|
z_zoomed = []
|
||||||
|
for lvl, ft in enumerate(z):
|
||||||
|
_ft = ft[:]
|
||||||
|
# _ft = (_ft-_ft.min())/(_ft.max()-_ft.min())
|
||||||
|
# canvas = np.zeros((height, width, 3))
|
||||||
|
if vertical:
|
||||||
|
_ft_reshaped = _ft.reshape(-1, 1)
|
||||||
|
else:
|
||||||
|
_ft_reshaped = _ft.reshape(1, -1)
|
||||||
|
|
||||||
|
canvas = color_map(
|
||||||
|
cv2.resize(_ft_reshaped, dsize=(width, height), interpolation=cv2.INTER_NEAREST),
|
||||||
|
vmin=vmin,
|
||||||
|
vmax=vmax
|
||||||
|
)
|
||||||
|
|
||||||
|
z_zoomed.append(canvas)
|
||||||
|
return z_zoomed
|
||||||
|
|
||||||
|
# pivots not used anymore FIXME: remove
|
||||||
|
def draw_pivot(z_imgs, pivot):
|
||||||
|
z_imgs_new = to_disp_images(z_imgs)
|
||||||
|
for new_img in z_imgs_new:
|
||||||
|
y = int(pivot*z_fy)
|
||||||
|
cv2.line(new_img, (0, y), (new_img.shape[1], y), (1, 1, 1), thickness=1)
|
||||||
|
return z_imgs_new
|
||||||
|
|
||||||
|
# pivots = [z.shape[1] for z in levels_z if z is not None]
|
||||||
|
# z_vis_list_per_level = [draw_pivot(draw_z(z), p) for z,p in zip(levels_z, pivots) if z is not None]
|
||||||
|
z_vis_list_per_level = [draw_z(z) for z in levels_z if z is not None]
|
||||||
|
z_grid_per_sample = [make_grid(all_vis_sample, nCols=len(levels_z)) for all_vis_sample in zip(*z_vis_list_per_level)]
|
||||||
|
return make_grid(z_grid_per_sample, nCols=ncols, normalize=False)
|
||||||
|
|
||||||
|
|
||||||
|
def draw_status_bar(text, status_bar_width, status_bar_height, dtype=np.float32, text_size=-1, text_color=(255,255,255)):
|
||||||
|
img_status_bar = np.zeros((status_bar_height, status_bar_width, 3), dtype=dtype)
|
||||||
|
if text_size <= 0:
|
||||||
|
text_size = status_bar_height * 0.025
|
||||||
|
cv2.putText(img_status_bar, text, (4,img_status_bar.shape[0]-5), cv2.FONT_HERSHEY_SIMPLEX, text_size, text_color, 1, cv2.LINE_AA)
|
||||||
|
return img_status_bar
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import numpy as np
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import ntpath
|
||||||
|
import time
|
||||||
|
from subprocess import Popen, PIPE
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from common import utils
|
||||||
|
# from common.vis.html import HTML
|
||||||
|
from common.image import tensor2im, save_image
|
||||||
|
from common.landmark import landmark_to_image
|
||||||
|
|
||||||
|
|
||||||
|
class Visualizer():
|
||||||
|
"""This class includes several functions that can display/save images
|
||||||
|
and print/save logging information.
|
||||||
|
|
||||||
|
It uses a Python library 'visdom' for display,
|
||||||
|
and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, opt, logger):
|
||||||
|
"""Initialize the Visualizer class
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
||||||
|
Step 1: Cache the training/test options
|
||||||
|
Step 2: connect to a visdom server
|
||||||
|
Step 3: create an HTML object for saveing HTML filters
|
||||||
|
Step 4: create a logging file to store training losses
|
||||||
|
"""
|
||||||
|
self.opt = opt # cache the option
|
||||||
|
self.logger = logger # logger info
|
||||||
|
|
||||||
|
self.name = opt.MODEL.name
|
||||||
|
self.path_output = Path(opt.OUTPUT_DIR) # the output path for debug image
|
||||||
|
|
||||||
|
if self.opt.VISUAL.use_visdom: # connect to a visdom server given <vsdm_port> and <vsdm_server>
|
||||||
|
import visdom
|
||||||
|
self.ncols = opt.VISUAL.vsdm_ncol
|
||||||
|
self.vis = visdom.Visdom(server=opt.VISUAL.vsdm_server, port=opt.VISUAL.vsdm_port, env=opt.VISUAL.vsdm_env)
|
||||||
|
|
||||||
|
if not self.vis.check_connection():
|
||||||
|
self.create_visdom_connections()
|
||||||
|
|
||||||
|
if self.opt.VISUAL.use_HTML:
|
||||||
|
# create an HTML object at <checkpoints_dir>/web/;
|
||||||
|
# images will be saved under <checkpoints_dir>/web/images/
|
||||||
|
self.web_dir = self.path_output.joinpath('web')
|
||||||
|
self.img_dir = self.path_output.joinpath('web', 'images')
|
||||||
|
|
||||||
|
print(f'create web directory {self.web_dir} ...')
|
||||||
|
self.img_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# create a logging file to store training losses
|
||||||
|
self.logger.info(f'================ Training Loss ({time.strftime("%c")}) ================\n')
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
"""Reset the self.saved status"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def create_visdom_connections(self):
|
||||||
|
"""If the program could not connect to Visdom server,
|
||||||
|
this function will start a new server at port < self.opt.VISUAL.vsdm_port > """
|
||||||
|
|
||||||
|
cmd = sys.executable + ' -m visdom.server -p %d &>/dev/null &' % self.opt.VISUAL.vsdm_port
|
||||||
|
self.logger.info('\n\nCould not connect to Visdom server. \n Trying to start a server....')
|
||||||
|
self.logger.info('Command: %s' % cmd)
|
||||||
|
Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
|
||||||
|
|
||||||
|
|
||||||
|
def display_current_results(self, visuals, epoch=0, batch=0):
|
||||||
|
"""Display current results on visdom; save current results to an HTML file.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
visuals (OrderedDict) - - dictionary of images to display or save
|
||||||
|
epoch (int) - - the current epoch
|
||||||
|
save_result (bool) - - if save the current results to an HTML file
|
||||||
|
"""
|
||||||
|
|
||||||
|
if self.opt.VISUAL.use_visdom: # show images in the browser using visdom
|
||||||
|
ncols = self.ncols
|
||||||
|
|
||||||
|
if ncols > 0: # show all the images in one visdom panel
|
||||||
|
ncols = min(ncols, len(visuals))
|
||||||
|
h, w = next(iter(visuals.values())).shape[:2]
|
||||||
|
|
||||||
|
table_css = """<style>
|
||||||
|
table {border-collapse: separate; border-spacing: 4px; white-space: nowrap; text-align: center}
|
||||||
|
table td {width: % dpx; height: % dpx; padding: 4px; outline: 4px solid black}
|
||||||
|
</style>""" % (w, h) # create a table css
|
||||||
|
|
||||||
|
# create a table of images.
|
||||||
|
title = self.name
|
||||||
|
label_html = ''
|
||||||
|
label_html_row = ''
|
||||||
|
images = []
|
||||||
|
idx = 0
|
||||||
|
for label, image in visuals.items():
|
||||||
|
image_numpy = tensor2im(image)
|
||||||
|
label_html_row += '<td>%s</td>' % label
|
||||||
|
images.append(image_numpy.transpose([2, 0, 1]))
|
||||||
|
idx += 1
|
||||||
|
if idx % ncols == 0:
|
||||||
|
label_html += '<tr>%s</tr>' % label_html_row
|
||||||
|
label_html_row = ''
|
||||||
|
white_image = np.ones_like(image_numpy.transpose([2, 0, 1])) * 255
|
||||||
|
while idx % ncols != 0:
|
||||||
|
images.append(white_image)
|
||||||
|
label_html_row += '<td></td>'
|
||||||
|
idx += 1
|
||||||
|
if label_html_row != '':
|
||||||
|
label_html += '<tr>%s</tr>' % label_html_row
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.vis.images(images, nrow=ncols, win=self.opt.VISUAL.vsdm_id + 1, padding=2, opts=dict(title=title + ' images'))
|
||||||
|
label_html = '<table>%s</table>' % label_html
|
||||||
|
self.vis.text(table_css + label_html, win=self.opt.VISUAL.vsdm_id + 2, opts=dict(title=title + ' labels'))
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
print("CANNOT vis image, text")
|
||||||
|
self.create_visdom_connections()
|
||||||
|
|
||||||
|
else: # show each image in a separate visdom panel;
|
||||||
|
idx = 1
|
||||||
|
try:
|
||||||
|
for label, image in visuals.items():
|
||||||
|
image_numpy = tensor2im(image)
|
||||||
|
self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label), win=self.opt.VISUAL.vsdm_id + idx)
|
||||||
|
idx += 1
|
||||||
|
except Exception:
|
||||||
|
print("CANNOT vis image")
|
||||||
|
self.create_visdom_connections()
|
||||||
|
|
||||||
|
if self.opt.VISUAL.use_HTML: # save images to an HTML file
|
||||||
|
|
||||||
|
# create a webpage
|
||||||
|
webpage = HTML(str(self.web_dir), 'Experiment name = %s' % self.name, opt=self.opt, refresh=-1)
|
||||||
|
|
||||||
|
# save images to the disk
|
||||||
|
for ilabel, data in visuals.items():
|
||||||
|
image_numpy = tensor2im(data)
|
||||||
|
img_path = self.img_dir.joinpath(f'epoch_{epoch:04d}_{batch:04d}_{ilabel}.png')
|
||||||
|
save_image(image_numpy, img_path)
|
||||||
|
|
||||||
|
# for epoch and batch
|
||||||
|
for iepoch in range(epoch, 0, -1):
|
||||||
|
# print(f"DEBUG: iepoch={iepoch}, batch={batch}")
|
||||||
|
if iepoch % self.opt.FREQ.epoch_display != 0 : continue
|
||||||
|
|
||||||
|
for ibatch in range(batch, -1, -1):
|
||||||
|
# print(f"DEBUG: ibatch={ibatch}")
|
||||||
|
if ibatch % self.opt.FREQ.batch_display != 0: continue
|
||||||
|
|
||||||
|
# print(f"DEBUG add page: iepoch={iepoch} ibatch={ibatch}")
|
||||||
|
webpage.add_header(f'epoch [{iepoch:04d}] - Batch [{ibatch:04d}]')
|
||||||
|
ims, txts, links = [], [], []
|
||||||
|
|
||||||
|
for ilabel in visuals.keys():
|
||||||
|
img_path = f'images/epoch_{iepoch:04d}_{ibatch:04d}_{ilabel}.png'
|
||||||
|
ims.append(img_path)
|
||||||
|
txts.append(ilabel)
|
||||||
|
links.append(img_path)
|
||||||
|
|
||||||
|
webpage.add_images(ims, txts, links, width=self.opt.VISUAL.vsdm_wsize)
|
||||||
|
webpage.save()
|
||||||
|
|
||||||
|
def plot_current_losses(self, epoch, counter_ratio, losses):
|
||||||
|
"""display the current losses on visdom display: dictionary of error labels and values
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
epoch (int) -- current epoch
|
||||||
|
counter_ratio (float) -- progress (percentage) in the current epoch, between 0 to 1
|
||||||
|
losses (OrderedDict) -- training losses stored in the format of (name, float) pairs
|
||||||
|
"""
|
||||||
|
if not self.opt.VISUAL.use_visdom: return
|
||||||
|
|
||||||
|
if not hasattr(self, 'plot_data'):
|
||||||
|
self.plot_data = {'X': [], 'Y': [], 'legend': list(losses.keys())}
|
||||||
|
|
||||||
|
self.plot_data['X'].append(epoch + counter_ratio)
|
||||||
|
self.plot_data['Y'].append([losses[k] for k in self.plot_data['legend']])
|
||||||
|
|
||||||
|
try:
|
||||||
|
# print("np.array(self.plot_data['X'])=", np.array(self.plot_data['X']))
|
||||||
|
# print("np.array(self.plot_data['Y'])=", np.array(self.plot_data['Y']))
|
||||||
|
# print("self.plot_data['legend']", self.plot_data['legend'])
|
||||||
|
|
||||||
|
|
||||||
|
self.vis.line(
|
||||||
|
X=np.stack([np.array(self.plot_data['X'])] * len(self.plot_data['legend']), 1),
|
||||||
|
Y=np.array(self.plot_data['Y']),
|
||||||
|
opts={
|
||||||
|
'title': self.name + ' loss over time',
|
||||||
|
'legend': self.plot_data['legend'],
|
||||||
|
'xlabel': 'epoch',
|
||||||
|
'ylabel': 'loss'},
|
||||||
|
win=self.opt.VISUAL.vsdm_id)
|
||||||
|
except Exception:
|
||||||
|
raise("CANNOT vis line")
|
||||||
|
self.create_visdom_connections()
|
||||||
|
|
||||||
|
# losses: same format as |losses| of plot_current_losses
|
||||||
|
def print_current_losses(self, epoch, iters, losses, t_comp=None, t_data=None):
|
||||||
|
"""print current losses on console; also save the losses to the disk
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
epoch (int) -- current epoch
|
||||||
|
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
|
||||||
|
losses (OrderedDict) -- training losses stored in the format of (name, float) pairs
|
||||||
|
t_comp (float) -- computational time per data point (normalized by batch_size)
|
||||||
|
t_data (float) -- data loading time per data point (normalized by batch_size)
|
||||||
|
"""
|
||||||
|
msg = f"[Epoch:{epoch:03d}-{iters:03d}]"
|
||||||
|
for k,v in losses.items():
|
||||||
|
msg += f" {k}= {v:0.5f} "
|
||||||
|
|
||||||
|
self.logger.info(f'{msg}') # save the message
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Motion VAE
|
||||||
|
|
||||||
|
This code was a pytorch implement of "Ling et al, Character Controllers using Motion VAEs, ACM-ToG 2021", please note that this method not contain motion prior.
|
||||||
|
|
||||||
|
We conduct two kinds of MotionVAE:
|
||||||
|
- METHOD1: VAE + LSTM
|
||||||
|
- METHOD2: VAE + Autoregression (only conditional on one prev frame)
|
||||||
|
|
||||||
|
We also conduct two kinds of training model:
|
||||||
|
- Generate landmark sequence without condition (MotionVAE)
|
||||||
|
- Generate landmark sequnece with speech condition (MotionCVAE)
|
||||||
|
|
||||||
|
|
||||||
|
MotionVAE Model File:
|
||||||
|
- src/models/model_MotionVAE.py
|
||||||
|
- src/nn/MotionVAE.py
|
||||||
|
- src/nn/MotionVAE2.py
|
||||||
|
|
||||||
|
Condition MotionVAE Model File:
|
||||||
|
- src/models/model_MotionCVAE.py
|
||||||
|
- src/nn/MoCVAE.py
|
||||||
|
- src/nn/MoCVAE2.py
|
||||||
|
|
||||||
|
|
||||||
|
## 1) Genearte Landmark Sequence (MotionVAE)
|
||||||
|
|
||||||
|
(1) For method 1 training:
|
||||||
|
|
||||||
|
> - python train3.py --opt experiments/MotionVAE/train-MotionVAE-LRW.yaml
|
||||||
|
|
||||||
|
(2) For method 2 training:
|
||||||
|
|
||||||
|
> - python train3.py --opt experiments/MotionVAE/train-MotionVAE2-LRW.yaml
|
||||||
|
|
||||||
|
|
||||||
|
## 2) Talking Landmark Sequence (MoCVAE)
|
||||||
|
(1) For method 1 training:
|
||||||
|
|
||||||
|
> - python train3.py --opt experiments/MotionVAE/train-MoCVAE-LRW.yaml
|
||||||
|
|
||||||
|
(2) For method 2 training:
|
||||||
|
|
||||||
|
> - python train3.py --opt experiments/MotionVAE/train-MoCVAE2-LRW.yaml
|
||||||
Whitespace-only changes.
@@ -0,0 +1,113 @@
|
|||||||
|
import time
|
||||||
|
import sys
|
||||||
|
import pprint
|
||||||
|
import shutil
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch.utils.data import DataLoader
|
||||||
|
|
||||||
|
from src.datasets import create_dataset
|
||||||
|
from src.models import create_model, calculate_model_params
|
||||||
|
from src.config import config as opt
|
||||||
|
from src.config import update_config
|
||||||
|
|
||||||
|
from common.vis.visualizer import Visualizer
|
||||||
|
from common.logger import Logger
|
||||||
|
from common.animation import save_animation_grid
|
||||||
|
|
||||||
|
|
||||||
|
torch.autograd.set_detect_anomaly(True)
|
||||||
|
|
||||||
|
|
||||||
|
def parese_args():
|
||||||
|
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
|
||||||
|
|
||||||
|
# general
|
||||||
|
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
|
||||||
|
args, _ = pareser.parse_known_args()
|
||||||
|
update_config(args.opt)
|
||||||
|
|
||||||
|
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
|
||||||
|
args = pareser.parse_args()
|
||||||
|
|
||||||
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
args = parese_args()
|
||||||
|
path_config = Path(args.opt)
|
||||||
|
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
|
||||||
|
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
|
||||||
|
|
||||||
|
logger.info(pprint.pformat(opt))
|
||||||
|
opt.OUTPUT_DIR = logger.path_output
|
||||||
|
|
||||||
|
# load motion
|
||||||
|
test_dataset = create_dataset(opt, phase='test')
|
||||||
|
test_loader = DataLoader(test_dataset,
|
||||||
|
batch_size=opt.TEST.batch_size * len(opt.GPUS),
|
||||||
|
shuffle=True, # NOTE: usually set False
|
||||||
|
num_workers=opt.WORKERS,
|
||||||
|
pin_memory=False)
|
||||||
|
|
||||||
|
# logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
|
||||||
|
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
|
||||||
|
|
||||||
|
|
||||||
|
# get model
|
||||||
|
model = create_model(opt, logger)
|
||||||
|
model.setup(opt) # load model
|
||||||
|
# model.remove_weightnorm()
|
||||||
|
|
||||||
|
# Add for WaveFlow
|
||||||
|
# model.netG.module = model.netG.module.remove_weightnorm(model.netG.module)
|
||||||
|
for i, batch_input in enumerate(test_loader):
|
||||||
|
|
||||||
|
motion = batch_input['data'].float().to(device) # (nbatch, nsteps=60, dim_motion=136)
|
||||||
|
speech = batch_input["cond"].float().to(device) # (nbatch, nsteps=173, dim_condit=80)
|
||||||
|
motion = motion.permute(0, 2, 1) # (nbatch, 136, 60)
|
||||||
|
speech = speech.permute(0, 2, 1) # (nbatch, 80, 173)
|
||||||
|
B = motion.size(0)
|
||||||
|
motion_gt = motion.permute(0,2,1)[0:1, :, :]
|
||||||
|
|
||||||
|
|
||||||
|
# generate k samples
|
||||||
|
motion_pt = []
|
||||||
|
for j in range(8):
|
||||||
|
data_pt = model.testing(batch_input, cur_epoch=opt.MODEL.load_epoch, save_animation=False) # B x nsteps x 136
|
||||||
|
data_pt = data_pt[0:1, :, :]
|
||||||
|
motion_pt.append(data_pt)
|
||||||
|
|
||||||
|
motion_pt = torch.cat(motion_pt, dim=0) # 8 x nsteps x 136
|
||||||
|
nsteps = min(motion_gt.size(1), motion_pt.size(1))
|
||||||
|
total_motion = torch.cat([motion_gt[:, :nsteps, :], motion_pt[:, :nsteps, :]], dim=0)
|
||||||
|
|
||||||
|
print(f"total motion shape = {total_motion.shape}")
|
||||||
|
|
||||||
|
path_save=Path(opt.OUTPUT_DIR).joinpath(f'sampled_{opt.MODEL.load_epoch:05d}_{i:03d}.mp4')
|
||||||
|
|
||||||
|
save_animation_grid(total_motion, path_save=path_save, ncol=3, w=256, h=256, dpi=100)
|
||||||
|
|
||||||
|
print(f"SVAE -> {opt.OUTPUT_DIR}")
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
|
# # infer
|
||||||
|
# epoch_beg = 400
|
||||||
|
# epoch_end = 580
|
||||||
|
# for epoch in range(epoch_end, epoch_beg, -50):
|
||||||
|
# print(f"Testing the epoch{epoch}/{epoch_end}")
|
||||||
|
|
||||||
|
# opt.MODEL.load_epoch = epoch # set load epoch
|
||||||
|
# model.setup(opt) # load model
|
||||||
|
|
||||||
|
# for i, ibatch_data in enumerate(test_loader):
|
||||||
|
# model.testing(ibatch_data, cur_epoch=epoch, cur_batch=i)
|
||||||
|
# model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*100+1))
|
||||||
|
# model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*1000+1))
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+177
@@ -0,0 +1,177 @@
|
|||||||
|
import sys
|
||||||
|
import pprint
|
||||||
|
import argparse
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import librosa
|
||||||
|
|
||||||
|
from src.models import create_model, calculate_model_params
|
||||||
|
from src.config import config as opt
|
||||||
|
from src.config import update_config
|
||||||
|
|
||||||
|
from common.vis.visualizer import Visualizer
|
||||||
|
from common.logger import Logger
|
||||||
|
from common.animation import save_images_with_audio
|
||||||
|
|
||||||
|
|
||||||
|
torch.autograd.set_detect_anomaly(True)
|
||||||
|
|
||||||
|
|
||||||
|
def parese_args():
|
||||||
|
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
|
||||||
|
|
||||||
|
# general
|
||||||
|
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
|
||||||
|
args, _ = pareser.parse_known_args()
|
||||||
|
update_config(args.opt)
|
||||||
|
|
||||||
|
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
|
||||||
|
args = pareser.parse_args()
|
||||||
|
|
||||||
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
args = parese_args()
|
||||||
|
path_config = Path(args.opt)
|
||||||
|
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
|
||||||
|
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
|
||||||
|
|
||||||
|
logger.info(pprint.pformat(opt))
|
||||||
|
opt.OUTPUT_DIR = logger.path_output
|
||||||
|
|
||||||
|
# load motion
|
||||||
|
# test_dataset = create_dataset(opt, phase='test')
|
||||||
|
# test_loader = DataLoader(test_dataset,
|
||||||
|
# batch_size=opt.TEST.batch_size * len(opt.GPUS),
|
||||||
|
# shuffle=True, # NOTE: usually set False
|
||||||
|
# num_workers=opt.WORKERS,
|
||||||
|
# pin_memory=False)
|
||||||
|
|
||||||
|
# path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
# vid = "Celebrating-Independence-Day"
|
||||||
|
# path_audio = path_data.joinpath(vid, "audio/audio_trim.wav")
|
||||||
|
# path_speech = path_data.joinpath(vid, "audio/feat_mel_no_align_trim.npy")
|
||||||
|
# path_motion = path_data.joinpath(vid, "audio/feat_ldmk_trim_norm.npy")
|
||||||
|
|
||||||
|
path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/test_video_15.wav")
|
||||||
|
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/cut_lsz.wav")
|
||||||
|
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/obama.wav")
|
||||||
|
# data extract audio
|
||||||
|
# Load data_audio and extract features
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
fps = 30
|
||||||
|
numcep = 27
|
||||||
|
nseqR = opt.MODEL.n_lookprevs_speech # 3~9
|
||||||
|
nseqL = opt.MODEL.n_lookahead_speech # 3~9
|
||||||
|
|
||||||
|
data, sr = librosa.load(str(path_audio), sr=16000)
|
||||||
|
hop_len = int(sr / fps)
|
||||||
|
n_fft = int(sr * 0.13) # default 2048
|
||||||
|
print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
|
||||||
|
|
||||||
|
# melspectrogram
|
||||||
|
feat = librosa.feature.melspectrogram(y=data, sr=sr,
|
||||||
|
n_fft=n_fft, # FFT窗口的长度
|
||||||
|
hop_length=hop_len, # 帧移
|
||||||
|
win_length=n_fft, # 窗口长度,默认=n_fft
|
||||||
|
window="hann", # 加hanming窗
|
||||||
|
n_mels=numcep, # 滤波器组
|
||||||
|
fmin=0.0, fmax=8000)
|
||||||
|
feat = np.log(feat+1).T
|
||||||
|
print(f"sr={sr}, data ={data.shape}, feat = {feat.shape}, (min,max)=({np.min(feat), np.max(feat)}")
|
||||||
|
|
||||||
|
# padding
|
||||||
|
# Add empty initial and final contexts
|
||||||
|
|
||||||
|
empty_contextR = np.zeros((nseqR, numcep), dtype=feat.dtype)
|
||||||
|
empty_contextL = np.zeros((nseqL, numcep), dtype=feat.dtype)
|
||||||
|
feat = np.concatenate((empty_contextR, feat, empty_contextL)) # (469, 27)
|
||||||
|
# feat = torch.from_numpy(feat).unsqueeze_(0)
|
||||||
|
print(f"after padding feat ={feat.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
# logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
|
||||||
|
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
|
||||||
|
|
||||||
|
# get model
|
||||||
|
model = create_model(opt, logger)
|
||||||
|
model.setup(opt) # load model
|
||||||
|
# model.remove_weightnorm()
|
||||||
|
|
||||||
|
|
||||||
|
nstep = feat.shape[0]
|
||||||
|
nstep_new = nstep - nseqR - nseqL
|
||||||
|
wsize = nseqR + 1 + nseqL
|
||||||
|
|
||||||
|
|
||||||
|
# prepare data condition: nc_condit = (nseqR + 1 + nseqL) * nc_speech
|
||||||
|
data_speech = torch.from_numpy(feat) # (nstep, nc_speech)
|
||||||
|
res_condit = data_speech.unfold(dimension=0, size=wsize, step=1) # (nstep_new, nc_speech, wsize)
|
||||||
|
res_condit = res_condit.swapaxes_(1,2) # (nstep_new, wsize, nc_speech)
|
||||||
|
res_condit = res_condit.reshape(1, nstep_new, -1) # (1, nsetp_new, nc_condit)
|
||||||
|
assert res_condit.shape[-1] == wsize * numcep
|
||||||
|
|
||||||
|
model.infer(res_condit, path_audio, f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}")
|
||||||
|
|
||||||
|
# # Add for WaveFlow
|
||||||
|
# # model.netG.module = model.netG.module.remove_weightnorm(model.netG.module)
|
||||||
|
# # for i, batch_input in enumerate(test_loader):
|
||||||
|
|
||||||
|
# motion = batch_input['data'].float().to(device) # (nbatch, nsteps=60, dim_motion=136)
|
||||||
|
# speech = batch_input['cond'].float().to(device) # (nbatch, nsteps=173, dim_condit=80)
|
||||||
|
# motion = motion.permute(0, 2, 1) # (nbatch, 136, 60)
|
||||||
|
# speech = speech.permute(0, 2, 1) # (nbatch, 80, 173)
|
||||||
|
# B = motion.size(0)
|
||||||
|
# motion_gt = motion.permute(0,2,1)[0:1, :, :]
|
||||||
|
|
||||||
|
# # generate k samples
|
||||||
|
# motion_pt = []
|
||||||
|
# for j in range(3):
|
||||||
|
# data_pt = model.testing(batch_input, cur_epoch=opt.MODEL.load_epoch, save_animation=False) # B x nsteps x 136
|
||||||
|
# data_pt = data_pt[0:1, :, :]
|
||||||
|
# motion_pt.append(data_pt)
|
||||||
|
|
||||||
|
# # save
|
||||||
|
# print("data_pt shape = ", data_pt.shape)
|
||||||
|
# np.save(f"data/ldmk_pdt_align30_{j}.npy", data_pt.cpu().numpy()[0])
|
||||||
|
|
||||||
|
|
||||||
|
# motion_pt = torch.cat(motion_pt, dim=0) # 8 x nsteps x 136
|
||||||
|
# nsteps = min(motion_gt.size(1), motion_pt.size(1))
|
||||||
|
# total_motion = torch.cat([motion_gt[:, :nsteps, :], motion_pt[:, :nsteps, :]], dim=0)
|
||||||
|
# print(f"total motion shape = {total_motion.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# path_save=Path(opt.OUTPUT_DIR).joinpath(f'sampled_{opt.MODEL.load_epoch:05d}.mp4')
|
||||||
|
# save_animation_grid(total_motion, path_save=path_save, path_audio=path_audio, ncol=2, w=256, h=256, dpi=100)
|
||||||
|
# # animation_with_audio(path_save, path_audio)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# print(f"SVAE -> {opt.OUTPUT_DIR}")
|
||||||
|
# # break
|
||||||
|
|
||||||
|
|
||||||
|
# # # infer
|
||||||
|
# # epoch_beg = 400
|
||||||
|
# # epoch_end = 580
|
||||||
|
# # for epoch in range(epoch_end, epoch_beg, -50):
|
||||||
|
# # print(f"Testing the epoch{epoch}/{epoch_end}")
|
||||||
|
|
||||||
|
# # opt.MODEL.load_epoch = epoch # set load epoch
|
||||||
|
# # model.setup(opt) # load model
|
||||||
|
|
||||||
|
# # for i, ibatch_data in enumerate(test_loader):
|
||||||
|
# # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=i)
|
||||||
|
# # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*100+1))
|
||||||
|
# # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*1000+1))
|
||||||
|
# # break
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import numpy as np\n",
|
||||||
|
"from pathlib import Path\n",
|
||||||
|
"\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"%matplotlib inline"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"data_pos shape = (8155, 6)\n",
|
||||||
|
"data_exp shape = (8155, 50)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# load data\n",
|
||||||
|
"# load pose\n",
|
||||||
|
"path_data = Path(\"/yrfs/lsen/DATA/Obama/processing\")\n",
|
||||||
|
"vid = \"Weekly-Address-Enrolling-in-the-Affordable-Care-Act-Marketplace\"\n",
|
||||||
|
"\n",
|
||||||
|
"path_exp = path_data.joinpath(vid, \"audio/feat_DECA_exp_trim.npy\")\n",
|
||||||
|
"path_pos = path_data.joinpath(vid, \"audio/feat_DECA_pos_trim.npy\")\n",
|
||||||
|
"\n",
|
||||||
|
"data_pos = np.load(path_pos) # (N, 6)\n",
|
||||||
|
"data_exp = np.load(path_exp) # (N, 50)\n",
|
||||||
|
"\n",
|
||||||
|
"print(f\"data_pos shape = {data_pos.shape}\")\n",
|
||||||
|
"print(f\"data_exp shape = {data_exp.shape}\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 58,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABJAAAAI/CAYAAAAoSiMoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOzdd1xV9f8H8NdhKO4FrlAB0RxImCPN3KscZWmlOTEzK60sm7bX92fDUrOh5so0K0duTakkB4qJe6CAe4GKIiLr/P54dwQV8MI9555z7309Hw8e18G9563Avfe8zvvz/iiqqoKIiIiIiIiIiCg/HmYXQERERERERERE1sYAiYiIiIiIiIiICsQAiYiIiIiIiIiICsQAiYiIiIiIiIiICsQAiYiIiIiIiIiICsQAiYiIiIiIiIiICuRldgFF4evrqwYEBJhdBhERERERERGRy9i2bVuiqqp+ef2dUwZIAQEBiI6ONrsMIiIiIiIiIiKXoSjKkfz+jkvYiIiIiIiIiIioQAyQiIiIiIiIiIioQAyQiIiIiIiIiIioQE45A4mIiIiIiIiIyBYZGRk4fvw40tLSzC7FMnx8fODv7w9vb2+b78MAiYiIiIiIiIhc1vHjx1GmTBkEBARAURSzyzGdqqpISkrC8ePHERgYaPP9uISNiIiIiIiIiFxWWloaKlWqxPDoP4qioFKlSoXuyGKAREREREREREQujeHRjYry/8EAiYiIiIiIiIjIRTz55JO46667EBoaij59+iAlJUWXx2WARERERERERETkIr788kvs2LEDO3fuRM2aNfH111/r8rgMkIiIiIiIiIiIDJSQkIB69eph8ODB1zuDUlNTsW7dOjRu3BiNGjXC0KFDce3aNQDA66+/jgYNGiA0NBRjxowBAJw7dw69e/dGs2bN0KxZM2zYsCHPY5UtWxaADMu+evWqbsv3GCARERERERERERnswIEDGD58OHbu3ImyZcti/PjxGDJkCObPn49du3YhMzMT3377Lc6fP49FixZhz5492LlzJ9566y0AwAsvvIDRo0dj69atWLBgAYYNG5bvscLDw1G1alXs378fo0aN0qV+L10ehYiIiIiIiIjI6l58EYiJ0fcxw8KAr7667afVqFEDrVq1AgAMGDAAH374IQIDA1G3bl0AwODBgzF58mSMHDkSPj4+GDZsGLp3744ePXoAANauXYu9e/def7xLly7h8uXLKFOmzC3HmjFjBrKysjBq1CjMnz8f4eHhdv8z2YFERERERERERGQwW5eSeXl5YcuWLejduzcWL16M+++/HwCQnZ2NTZs2ISYmBjExMThx4gTKlCmDrl27Iiws7JaOJE9PTzz++ONYsGCBLvWzA4mIiIiIiIiI3IMNnUJGOXr0KDZt2oSWLVti3rx56NSpE77//nscOnQIwcHB+PHHH9G2bVukpKQgNTUV3bp1Q4sWLRAcHAwA6NKlC77++mu88sorAICYmBiEhYVh9erV14+hqioOHz6M4OBgqKqKpUuXol69errUzwCJiIiIiIiIiMhg9evXx6xZs/D000+jTp06mDBhAlq0aIFHH30UmZmZaNasGUaMGIHz58/joYceQlpaGlRVxZdffgkAmDhxIp577jmEhoYiMzMTbdq0wXfffXfDMVRVxeDBg3Hp0iWoqoq77roL3377rS71K6qq6vJAjtS0aVM1Ojra7DKIiIiIiIiIyOL27duH+vXrm1pDQkICevTogd27d5taR255/b8oirJNVdWmeX0+ZyAREREREREREVGBGCARERERERERERkoICDAUt1HRcEAiYiIiIiIiIiICsQAiYiIiIiIiIiICsQAiYiIiIiIiIiICsQAiYiIiIiIiIiICuRldgFERERERETkBoYMAfbvB6pWlY9q1XJ+nfujeHGzKyVyCaNGjcKMGTOQkpKiy+MxQCIiIiIiIiJjnTkDzJoF3HknkJoKbNwInDuX9+dWqCBBUtu2wOTJgAcXzhAVVnR0NC5evKjrY/InkYiIiIiIiIz1zz9yO2MGsHMncPYskJ4OHD8OREcDy5YB06YBH30EPPEE4O8PfPcd8Pvv5tZNpJOEhATUq1cPgwcPRmhoKPr06YPU1FSsW7cOjRs3RqNGjTB06FBcu3YNAPD666+jQYMGCA0NxZgxYwAA586dQ+/evdGsWTM0a9YMGzZsyPNYWVlZeOWVV/Dpp5/q+m9gBxIREREREREZKzISKFECaNIk58+8vYE77pCPm2VmAvXrAx9+CPTqBSiKw0olMsqBAwfwww8/oFWrVhg6dCjGjx+P77//HuvWrUPdunUxaNAgfPvttxg0aBAWLVqE/fv3Q1GU651EL7zwAkaPHo377rsPR48eRdeuXbFv375bjvP111/jwQcfRLVq1XStnwESERERERERGWv9eqBFC6BYMds+38sLGDsWCA8Hli8HevQwtj5yGy+uehExp2N0fcywqmH46v6vbvt5NWrUQKtWrQAAAwYMwIcffojAwEDUrVsXADB48GBMnjwZI0eOhI+PD4YNG4bu3bujx3/f/2vXrsXevXuvP96lS5dw+fJllClT5vqfnTx5Er/++iv++usv/f6B/+ESNiIiIiIiIjLOpUvAjh1A69aFu1///kBgIPDBB4CqGlMbkQMpNnbSeXl5YcuWLejduzcWL16M+++/HwCQnZ2NTZs2ISYmBjExMThx4gTKlCmDrl27IiwsDMOGDcP27dtx6NAhBAcHIyAgAKmpqQgODtalfnYgERERERERkXE2bgSyswsfIHl7A2+8AQwfDqxeDfx3Ek1kD1s6hYxy9OhRbNq0CS1btsS8efPQqVMnfP/999cDnx9//BFt27ZFSkoKUlNT0a1bN7Ro0eJ6ANSlSxd8/fXXeOWVVwAAMTExCAsLw+rVq284zunTp6//unTp0jh06JAu9bMDiYiIiIiIiIyzfr0sSWvZsvD3HTwYqFGDXUjkEurXr49Zs2YhNDQU58+fx+jRozFjxgw8+uijaNSoETw8PDBixAhcvnwZPXr0QGhoKNq2bYsvv/wSADBx4kRER0cjNDQUDRo0wHfffefQ+tmBRERERERERMaJjATuvhsoVarw9y1WTLqQnn0WiIgAOnbUvz4iB/Hw8Lgl9OnYsSO2b99+w59Vq1YNW7ZsueX+vr6+mD9/fqGOmZKSUvhC88EOJCIiIiIiIjJGWhqwZUvhl6/lFh4OVK8uXUhEZBoGSERERERERGSMLVuA9HSgTZuiP4aPD/Daa7IU7u+/9auNyIECAgKwe/dus8uwCwMkIiIiIiIiMkZkpNz+t3V5kT31FFClCvDhh/bXRERFwgCJiIiIiIiIjBEZCTRsCFSqZN/jlCgBvPIKsG6d7OpGRA7HAImIiIiIiIj0l5kJbNhg3/K13EaMAHx92YVEZBIGSERERERERKS/HTuAlBT7BmjnVqoU8PLLwKpVMluJiByKARIRERERERHpT5t/pFeABADPPQdUrAh89JF+j0nkYoYMGYLAwECEhYUhLCwMMTExujwuAyQiIiIiIiLS3/r1QGAg4O+v32OWKQOMHg0sXQps367f4xK5mM8++wwxMTGIiYlBWFiYLo/JAImIiIiIiIj0parAP//o232kGTUKKFeOs5DIqSQkJKBevXoYPHgwQkND0adPH6SmpmLdunVo3LgxGjVqhKFDh+LatWsAgNdffx0NGjRAaGgoxowZAwA4d+4cevfujWbNmqFZs2bYsGGDQ/8NDJCIiIiIiIhIXwcOAOfOGRMglSsHvPACsGgRsGuX/o9PZJADBw5g+PDh2LlzJ8qWLYvx48djyJAhmD9/Pnbt2oXMzEx8++23OH/+PBYtWoQ9e/Zg586deOuttwAAL7zwAkaPHo2tW7diwYIFGDZsWL7HGjt2LEJDQzF69OjroZS9vHR5FCIiIiIiIiLN+vVyq9cObDd74QVg/HiZhTR/vjHHIJf04ouATiOBrgsLA7766vafV6NGDbRq1QoAMGDAAHz44YcIDAxE3bp1AQCDBw/G5MmTMXLkSPj4+GDYsGHo3r07evToAQBYu3Yt9u7de/3xLl26hMuXL6NMmTI3HOd///sfqlativT0dAwfPhzjxo3DO++8Y/e/kx1IREREREREpK/ISKByZaBOHWMev2JFWcr266/Avn3GHINIZ4qi2PR5Xl5e2LJlC3r37o3Fixfj/vvvBwBkZ2dj06ZN12cbnThxAmXKlEHXrl0RFhZ2vSOpWrVqUBQFxYsXR3h4OLbotGshO5CIiIiIiIhIX5GRsnzNxhPmInnpJWDiRODjj4E5c4w7DrkUWzqFjHL06FFs2rQJLVu2xLx589CpUyd8//33OHToEIKDg/Hjjz+ibdu2SElJQWpqKrp164YWLVogODgYANClSxd8/fXXeOWVVwDg+oDs1atX33CcU6dOoVq1alBVFYsXL0ZISIgu9bMDiYiIiIiIiPRz9Chw5Ihxy9c0vr7AM88A8+YBsbHGHotIB/Xr18esWbMQGhqK8+fPY/To0ZgxYwYeffRRNGrUCB4eHhgxYgQuX76MHj16IDQ0FG3btsWXX34JAJg4cSKio6MRGhqKBg0a4LvvvsvzOP3790ejRo3QqFEjJCYmXp+hZC9FVVVdHsiRmjZtqkZHR5tdBhEREREREd3sp5+AAQOAf/8FGjc29lhnzgABAUDfvsCMGcYei5zWvn37UL9+fVNrSEhIQI8ePbB7925T68gtr/8XRVG2qaraNK/PZwcSERERERER6ScyEihbFggNNf5YVaoAI0YAP/4IxMUZfzwiN8YAiYiIiIiIiPSzfj3QqhXg6emY440cCWRlAX/84ZjjERVBQECApbqPioIBEhEREREREekjMVF2RWvd2nHH9PeX23PnHHdMIjfEAImIiIiIiIj08c8/cuvIAKl4caBMGQmviMgwDJCIiIiIiIhIH+vXS6DTrJljj+vnxwCJyGALine truncated
|
||||||
|
"text/plain": [
|
||||||
|
"<Figure size 1440x720 with 1 Axes>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"needs_background": "light"
|
||||||
|
},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# visualize the pose [3:6]\n",
|
||||||
|
"plt.figure(figsize=(20,10))\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# 30fps * 6s = 180帧\n",
|
||||||
|
"beg, nframe = 1000, 30*3\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 3], color='r', label=\"pose-3\")\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 4], color='g', label=\"pose-4\")\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 5], color='b', label=\"pose-5\")\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 0], color='black', label=\"pose-0\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.legend()\n",
|
||||||
|
"plt.show()\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 71,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"data_pos filter shape = (8155, 6)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABJAAAAI/CAYAAAAoSiMoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOzdd3gcd7X/8ffMdvVqyVaxZbn3Frf0kAKEJCSQQEhIgAsBkhAInZtLb5d2fxAIPbRQQjqQDoQkdty7JcuWZLlJtuqqa/vM74/ZWUu2yu5qJa3s83qePFHZMpZWszOfOd9zFF3XEUIIIYQQQgghhBBiKOpEb4AQQgghhBBCCCGESG4SIAkhhBBCCCGEEEKIYUmAJIQQQgghhBBCCCGGJQGSEEIIIYQQQgghhBiWBEhCCCGEEEIIIYQQYlgSIAkhhBBCCCGEEEKIYVknegPikZeXp8+YMWOiN0MIIYQQQgghhBDinLFz585WXdfzB/vepAyQZsyYwY4dOyZ6M4QQQgghhBBCCCHOGYqiHBvqe7KETQghhBBCCCGEEEIMSwIkIYQQQgghhBBCCDEsCZCEEEIIIYQQQgghxLAkQBJCCCGEEEIIIYQQw5IASQghhBBCCCGEEEIMSwIkIYQQQgghhBBCCDEsCZCEEEIIIYQQQgghxLAkQBJCCCGEEEIIIYQQw5IASQghhBBCCCGEEEIMSwIkIYQQQgghhBBCCDEsCZCEEEIIIYQQQgghxLAkQBJCCCGEEEIIIYQQw5IASQghhBBCCCGEEEIMSwIkIYQQQgghhBBCCDEsCZCEEEIIIYQQQgghxLAkQBJCCCGEEEIIIYQQw5IASQghhBBCCCGEEEIMSwIkIYQQQgghhBBCCDEsCZCEEEIIIYQQQgghxLAkQBJCCCGEEEIIIYQQw5IASQghhBBCCCGEEEIMSwIkIYQQQgghhBBCCDEs60RvgBBCnGt6enqoqakhJSWFjIwMMjIySElJQVGUid40IYQQQgghhIiLBEhCCJFgHR0ddHV10dfXR2NjIwAzZ86kpKRkgrdMCCGEEEIIIeIjS9iEECLBfD4fqqqyfv16LrjgAlwuFx0dHRO9WUIIIYQQQggRNwmQhBAiwfx+P3a7HUVRIsvYuru70XV9ojdNCCGEEEIIIeIiAZIQQiSYz+fDbrdHPs/IyCAQCODz+SZwq4QQQgghhBAifhIgCSFEgvn9fhwOR+Tz9PR0ALq7uydqk4QQQgghhBBiVCRAEkKIBDOXsJlSU1NRFIWurq4J3CohhBBCCCGEiJ8ESEIIkUDBYJBQKDSgAklVVdLS0qQCSQghhBBCCDFpSYAkhBAJ5Pf7AQZUIIGxjK2np0caaQshhBBCCCEmJQmQhBAigcxG2YMFSKFQiL6+vonYLCGEEEIIIYQYFQmQhBAigcwKpP5L2EAaaQshhBBCCCEmNwmQhBAigYZawpaSkoLFYpEASQghhBBCCDEpSYAkhBAJ5PP5sFgsWK3WAV9XFEUaaQshhBBCCCEmLQmQhBAigfx+/1nVR2gacLqRthb+XAghhBBCCCEmCwmQhBAigXw+3+kAaedO+MAHIDUVfvYzMjIy0HWd3t7eid1IIYQQQgghhIiRBEhCCJFAfr+flK4uWLcOVq2Cxx4DXYcdO6SRthBCCCGEEGLSkgBJCCESRNd1/H4/Of/6F2zZAj/4ATQ0wJIlUF+Pw+HAZrPR1dU10ZsqhBBCCCGEEDGxjnwTIYQQ0QgGg2iahqOxEVJS4P77QVGguBgOHUJRFNLT06UCSQghhBBCCDHpSAWSEEIkiN/vB8B26hSUlhrhERgBUkMDAE6nM3I7IYQQQgghhJgsJEASQogE8fl8AFgbGmD69NPfKC6Gzk7o7kZVVZnCJoQQQgghhJh0JEASQogEMSuLLPX1ZwdIAA0NkQBJ1/UJ2EIhhBBCCCGEiI8ESEIIkSB+vx/V50NpaTGWsJmKioz/19djsVgAJEASQgghhBBCTCoSIAkhRIL4fD5S29qMTwarQKqvR1WN3a4sYxNCCCGEEEJMJhIgCSFEgvj9flJbW41P+gdI/SqQJEASQgghhBBCTEYSIAkhRIL4fD5SWlqMT/oHSE4n5OVFeiABhEKhCdhCIYQQQgghhIiPBEhCCJEgfr8fV3MzWCwwbdrAbxYXSwWSEEIIIYQQYtJKSICkKMqbFUU5pChKraIonx/k+7cpirIv/N8mRVGWRntfIYSYDHRdx+/342hqMpasWa0Db1BUJAGSEEIIIYQQYtIadYCkKIoFeAh4C7AAuFVRlAVn3OwIcKmu60uArwO/jOG+QgiR9AKBALquYz91auDyNZNUIAkhhBBCCCEmsURUIK0GanVdr9N13Q88CtzQ/wa6rm/Sdb09/OkWoDja+wohxGTg9/sBsJ48OXSA1NqKGr6dBEhCCCGEEEKIySQRAVIRcKLf5/Xhrw3lv4AX4ryvEEIkJZ/PB8Eg6smTUFp69g2Kjdzc0tQESIAkhBBCCCGEmFwSESApg3xNH/SGinI5RoD0uTjue5eiKDsURdnRYk45Euesqqoqjhw5MtGbIUTU/H4/jrY2lFBo6AokwNrYCEiAJIQQQgghhJhcEhEg1QMl/T4vBk6eeSNFUZYAvwZu0HW9LZb7Aui6/ktd11fpur4qPz8/AZstkpnb7aa7u3uiN0OIqEUaaMPgAVKRUVxpOXUKkABJCCGEEEIkl2AwGGnLIMRgrCPfZETbgdmKopQBDcC7gff0v4GiKKXAU8B7dV2vjuW+4vwTDAYj/wkxWfh8PlJbW41PhlnCpp48CWVlhEKhcdw6IYQQQgghzqbrOm63m+bmZlpbW7FaraxduxZFGWyxkDjfjTpA0nU9qCjKvcBLgAX4ja7rlYqifCT8/Z8DXwJygZ+GX4jBcDXRoPcd7TaJyc3n8wHICbaYVPx+P1nDBUjp6ZCRgXLSKLKUCiQhhBBCCDGRvF4v+/btw+PxYLVaSU9Pp7Ozk97eXtLS0iZ680QSSkQFErquPw88f8bXft7v4w8CH4z2vuL85vV6AQmQxOTi9/txNTVBXh6kpg5+o+Ji1IYGQAIkIYQQQggxcbxeL3v37iUQCLBgwQJyc3Px+/1s3bqVzs5OCZDEoBLRA0mIhDIDJFnCJiaTYDBo9EAarP+RqbgYpAJJCCGEEEJMIDM82r9/P7fddhtf+MIX0DQNh8OBw+Ggs7NzojdRJCkJkETS6V+BpOuDDuUTIukEg0Fsp04NvnzNVFyMUl+PoigSIAkhhBBCiHHn8/nYu3cvL7/8Mvfddx+9vb08/PDD3Hzzzfh8PjIzM+ns7JTzMDEoCZBE0jEDJJAqDTF5BAMBbCdPDl+BVFQEp05h0TR5bQshhBBCiHGl6zoHDhzg4Ycf5ktf+hLLly/nwIED/OhHP+KZZ57hbW97G1arFb/fP+CcTAiTBEgi6fTfWckyNjEZaJqGpaMD1eMZeQmbruNob5cASQghhBBCjKvjx4/z2GOP8atf/YrbbruNf//730yZMoX77ruP3//+97z66qt88ING62JZxiYGk5Am2kIkktfrxWKxEAqFpJG2mBSCwSDOpibjk5ECJMDV1iYBkhBCCCGEGDednZ0cOXKEJ598kiVLlvDII48QnpAOwB133EFjYyOf+9znOHnyJIWFhRQWFk7gFotkJBVIIqkEg0GCwSCp4SlWk6UCqaOjg/b29oneDDFBgsEgjuZm45MReiABOFpbJUASQgghhDjHnThxgj179tDc3Dyhx36BQICqqioqKiqoqanhE5/4xIDwyPSud70LgF27dkkFkhiUBEgiqfh8PoDI2MjJUIHU0tLC3r17OXjwoDSbO08Fg0GcjY3GJ1FUIDlaWibFa1sIIYQQQsSvqamJzs5Oqqqq2LZtGydOnJiQ84W6ujr8fj/PP/88+fn53HrrrYPebvr06SxdupQNGzbg8Xjw+/3jvKUi2UmAJJKK2f/IrEBK9pPs1tZWqqqqsFgs0mzuPGYuYdNTUiA3d+gbZmeD04m9pUUqkIQQQgghzmGhUIje3l5KSkpYtGgRDoeDuro6uru7x3U7dF2nra2N3t5eXnzxRT760Y/idDqHvP3111/P9u3b6ezslCokcRYJkERSOTNASuYlbG1tbRw4cIC0tDSWLFkCGEvZxPknGAziaGpCLymBQcqBIxQFiouxT3AZsxBCCCGEGFu9vb0ApKenk5ubS3l5OWAsJxtPPp+PQCDA448/jtVq5aMf/eiwt7/++uvRNI1t27ZJgCTOIgGSSCperxdVVXG5XEDyViD5/X4qKysj4VF6ejo2m012suepYDCIo7U1skRtWBIgCSGEEOcFXdfl/f481tPTA5xuzWGz2YDxv0De1dVFd3c3jz32GLfeeuuIjbFXrFjB1KlT2bp1q5zbiLNIgCSSitfrxel0YrUaAwKTtQKps7MTXdcpLy/HarWiKApZWVl0dHRIH6TzUDAYxNbZCVOmjHzj4mJsTU1yQCmEEEKc444cOcKePXsmejPEBOnp6cFqtUaWi5nnN+NdgdTd3c0LL7xAb28vH//4x0e8vaqqXHfddWzevBm3252052NiYkiAJJKK1+vF4XCgqiqKoiRtBVJnZyeqqpKenh75WmZmJj6fT/ognYfMAEkZrv+RKT8fa3u7BEhCCCHEOa6vr0+OC89jPT09pKWlRaadTdQF8q6uLl555RXWrVvHihUrorrP9ddfT29vL3v27KGrq2uMt1BMJhIgiaRiViABWCyWpA6Q0tPTUdXTf0JZWVmR74nzS8jrxdrbi5KfP/KNs7NRPR50mWohhBBCnNMCgYBcMDpPaZoWCZBMiqJgtVrHNUDSNI1Tp05x6NAh3vzmN0d9vyuuuIKUlBQ2bdqEx+MZwy0Uk40ESCJpBINBY5pVvzLPZCyZDAaD9PT0kJmZOeDrKSkp2Gw2aaR9HtJbW40P8vJGvnE4aFQkaBRCCCHOaRIgnb/Line truncated
|
||||||
|
"text/plain": [
|
||||||
|
"<Figure size 1440x720 with 1 Axes>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"needs_background": "light"
|
||||||
|
},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Gaussion Filter\n",
|
||||||
|
"from scipy.ndimage import gaussian_filter1d\n",
|
||||||
|
"\n",
|
||||||
|
"data_pos_filter = gaussian_filter1d(data_pos, sigma=1, axis=0)\n",
|
||||||
|
"print(f\"data_pos filter shape = {data_pos_filter.shape}\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# 30fps * 6s = 180帧\n",
|
||||||
|
"beg, nframe = 1000, 30*10\n",
|
||||||
|
"\n",
|
||||||
|
"plt.figure(figsize=(20,10))\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 3], color='silver', label=\"pose-3\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 3], color='r', label=\"pose-3 filter\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 4], color='silver', label=\"pose-4\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 4], color='g', label=\"pose-4 filter\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 5], color='silver', label=\"pose-5\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 5], color='b', label=\"pose-5 filter\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 0], color='silver', label=\"pose-0\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 0], color='black', label=\"pose-0 filter\")\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 70,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"data_pos filter shape = (8155, 6)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABJAAAAI/CAYAAAAoSiMoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOzdd3wcd53/8dfMNq16taot9xrHdmI71ek9AQIhFQLhQktoBwfkAtwdd0AoP9ol1AsECBCSEAgESE9IcZw47lXulmVbVu9ly8x8f3/sjCzb0mp3tdKu7M/z8eCBo21jWdqdeX8/389HU0ohhBBCCCGEEEIIIcRw9FQfgBBCCCGEEEIIIYRIbxIgCSGEEEIIIYQQQoioJEASQgghhBBCCCGEEFFJgCSEEEIIIYQQQgghopIASQghhBBCCCGEEEJEJQGSEEIIIYQQQgghhIjKneoDSERxcbGaOnVqqg9DCCGEEEIIIYQQ4qSxbt26FqVUyVC3TcgAaerUqaxduzbVhyGEEEIIIYQQQghx0tA07cBwt8kWNiGEEEIIIYQQQggRlQRIQgghhBBCCCGEECIqCZCEEEIIIYQQQgghRFQSIAkhhBBCCCGEEEKIqCRAEkIIIYQQQgghhBBRSYAkhBBCCCGEEEIIIaKSAEkIIYQQQgghhBBCRCUBkhBCCCGEEEIIIYSISgIkIYQQQgghhBBCCBGVBEhCCCGEEEIIIYQQIioJkIQQQgghhBBCCCFEVBIgCSGEEEIIIYQQQoioJEASQgghhBBCCCGEEFFJgCSEEEIIIYQQQgghopIASQghhBBCCCGEEEJEJQGSEEIIIYQQQgghhIhKAiQhhBBCCCGEEEIIEZUESEIIIYQQQgghhBAiKgmQhBBCCCGEEEIIIURUEiAJIYQQQgghhBBCiKgkQBJCCCGEEEIIIYQQUUmAJIQQQgghhBBCCCGikgBJCCHGkmXBbbfBs8+m+kiEEEIIIYQQImESIAkhxFh67TX4wx/gmWdSfSRCCCGEEEIIkTAJkIQQYiz99reR/29uTu1xCCGEEEIIIcQoSIAkhBBjpb8f/vjHyJ8lQBJCCCGEEEJMYBIgCSHEWPnrX6G7G4qLJUASQgghhBBCTGgSIAkhxFj57W+hqgquu04CJCGEEEIIIcSEJgGSEEIkmVKK8KFDqOeeg/e9D0pLoaUFlEr1oQkhhBBCCCFEQiRAEkKIJGttbeXAt7+NZprsPvts2t1uCIUi29mEEEIIIYQQYgKSAEkIIZKsr6+P0uefJzB/Pu0VFTRaVuQG2cYmhBBCCCGEmKAkQBJCiCRT27aRs2sXGR/5CMuXL8dTXh65QQIkIYQQQgghxAQlAZIQQiSZZ9WqyB/e/W4AfFVVAFiNjak6JCGEEEIIIYQYFQmQhBAiyfTDh1EuV2QCG5AxeTIAwfr6VB6WEEIIIYQQQiRMAiQhhEgyV0MDxqRJ4HIBkD1tGgDhw4dTeVhCCCGEEEIIkTAJkIQQIomUUrgbGzGdvkeAr6AA0+vFOHIkhUcmhBBCCCGEEImTAEkIIZIoHA7ja27GqqgY+Jqm65iFhdIDSQghhBBCCDFhSYAkhBBJFAwE8DU3o9n9jxyquBittRXDMFJ0ZEIIIYQQQgiROAmQhBAiicLNzbgCATS7cbZDmzQJT2cnPT09KToyIYQQQgghhEicBEhCCJFERm0tAK7q6mO+7i4rw9PRQVdXVwqOSgghhBBCCCFGRwIkIYRIInXoEACuKVOO+bo+aRLezk66u7tTcVhCCCGEEEIIMSoSIAkhRBKpgwcB0I8LkCgpwdXXR09LSwqOSgghhBBCCCFGRwIkIYRIIu3wYZSmQXn5sTeUlACgmpoIBoMpODIhhBBCCCGESJwESEIIkUT6kSMYRUXg9R57gx0geWQbmxBCCCGEEGICkgBJCCGSyN3QgFlWduINToDU0SEBkhBCCCGEEGLCkQBJCCGSxLIsvI2NmBUVJ95YXAxATiAgAZIQQgghhBBiwpEASQghkiQUCuFrbobKyhNvtCuQsvr66O3tHecjE0IIIYQQQojRkQBJCCGSJNjairu3F6qqTrwxPx9cLtwdHZimOe7HJoQQQgghhBCjIQGSEEIkiVlXB4BrypQTb9R1KC7G3d6OZVnjfGRCCCGEEEIIMToSIAkhRJKYBw4A4J46deg72AGSUgql1PgdmBBCCCGEEEKMkgRIQgiRJOrgQQBc1dVD36GkBFdbG4BUIQkhhBBCCCEmFAmQhBAiWQ4dAkAbqgcSQEkJuh0gSR8kIYQQQgghxEQiAZIQQiSJfuQIRn4++P1D30EqkIQQQgghhBATlARIQgiRJK4jRwiXlg5/h5IStI4OME0JkIQQQgghhBATSlICJE3TrtI0baemaXs0Tfv3IW5/n6Zpm+3/rdI0bVGsjxVCiInC09iIVV4+/B2Ki9GUwtPVJQGSEEIIIYQQYkIZdYCkaZoL+DFwNTAfuFXTtPnH3W0/cKFS6nTga8D/xfFYIYRIe4Zh4G1uxqqoGP5OJSUAeDo6JEASQgghhBBCTCjJqEBaDuxRSu1TSoWAR4F3Db6DUmqVUqrd/s+3gKpYHyuEEBNBqKsLb0fH8A204ZgASZpoCyGEEEIIISaSZARIlcDBQf99yP7acO4EnknwsUIIkZbCBw4AoE2ePPydnACps1MqkIQQQgghhBATijsJz6EN8TU15B017WIiAdL5CTz2o8BHAaZMmRL/UYoJpb6+Hq/XS3FxcaoPRYiYmHaA5KquHv5O9s+zBEhCCCGEEEKIiSYZFUiHgMFL7lVA/fF30jTtdOAXwLuUUq3xPBZAKfV/SqmlSqmlJfYqvjh51dXVceTIkVQfhhAxs+rqAHBPnTr8newAySs9kIQQQgghhBATTDIqkNYAszRNmwYcBm4Bbht8B03TpgB/Bm5XSu2K57Hi1GNZFsFgEJ/Pl+pDESJ2hw8DIwRIHg8qP1+aaAshhBBCiJTr6+vj05/+NLm5uVx77bUUFxej6zoLFy5M9aGJNDXqAEkpZWia9kngOcAFPKSU2qZp2sft238G/CdQBPxE0zQAw64mGvKxoz0mMbEFg0EAaTIsJhTt8GGMrCzcOTnR71hcjKejg7AESEIIIYQQIkUCgQDXX389L774Irqu84Mf/IAZM2bwvve9j1mzZpGRkZHqQxRpKBlb2FBKPa2Umq2UmqGU+ob9tZ/Z4RFKqQ8rpQqUUovt/y2N9lhxagsEAoAESGJicR05gjFp0sh3LCmRHkhCCCGEECJlQqEQN9xwAy+88AJf/OIXeeONN/jud7+L2+3mvvvuo6mpKdWHKNJUMrawCZFUToBkGEaKj0SI2LmbmjBKS0e+Y0kJnm3bJEASQgghhBDjLhwOc/PNN/P000/z2c9+ls985jOUl5dz1llnUV1dzY033sjbb78tg6vEkJJSgSREMg2uQFJqyKF8QqQdvbsbKz9/xPtpJSV4Ojqkwk4IIYQQQoy7//3f/+Uvf/kLn/jEJ/jCF75AeXn5wG1nnXUWAKtXr07V4Yk0JwGSSDtOgKSUkioNMWG4u7shL2/kO+bl4e7rk59tIYQQQoiT3UMPwf/8T6qPYkBvby/f+ta3OPPMM/nyl798THgEUFVVRUlJCVu2bCEUCqXoKEU6kwBJpJ1AIMD0n/2Mij//eeJUafT3Q09Pqo9CpIhlWbh6elAxVCCRnY2rvx9LtmgKIYQQQpzcfvUr+Na3IE3CmO9+97u0trbyxS9+8YTwCEDTNJYuXUpNTQ2dnZ0pOEKR7iRAEmknEAgw6aWXKHrzzYnRBykUggsugHe+M9VHIlLE6OnBFQpBLAGSM6Wtt3dMj0kIIYQQQqTY3r2RheY1a1J9JLS2tvK///u/nHXWWdx4443D3u+cc86hrq6OQ4cOjePRiYlCAiSRVkzTJBQI4G1rw93TMzEqkL72NVi7FrVuHUjPplOS0doKgBZjBRIgFWtCCCGEECezvj44cgSA4HPPpfRQLMvi61//Ou3t7XzjG99A07Rh7+v0QXrrrbfG6/DEBCIBkkgrwWAQT0cHmmni7ulJ/wqkt95C3Xcf4bw8tK4ukJGXpySrrQ2IMUByKpC6u8fugIQQQgghRGrV1g78se8f/2Djxo20tLSkZEhQTU0Nv/nNb7jwwgu59NJLo9536dKlAGzYsIFwODwehycmEAmQRFoJBAJ47WqOtK9A6u3FfN/7CE6axO5//VcAQlu3pvaYREqYdoCkFxaOfGe7AkmTLWxCCCGEECcta/duAPoXLyZv+3ZC3d1s27aNnhRUof/f//0f7e3tfP3rXx/xvoWFhUyfPp0dO3bQ1dU1DkcnJhIJkERaCQQC+CZIgBT6zGfQ9+9n33/+J+V2/6PApk0pPiqRCqq9HYgxQJIKJCGEEEKIk154587I/99+O3ogwIK+PoBxn24WDAb5+9//zrJlyzj//PNjesxZZ53Fjh076OjoGNuDExOOBEgirQwOkPRwGCNN+8QYe/fi/eUvabj5Zmb8y7+Qf/rpWF4vxvbtqT40kQJOgOQqKhr5ztJEWwghhBDipGfs2oWRmYn7pptA0/C88Ubk6+PcouPgwYPs37+fK664IubHLF++nObmZvbs2TOGRyYmIgmQRFoJBAJkDkq6nQvzdNP/4osAZN11Fz6fD83tJjRlCtquXSk+MpEKcQVI9hY2PU3DUSGEEEIkx4EDB9i8eXOqD0Okyt69BCor8VdWwqJFuFeuBMY/QHr11VdRSnHxxRfH/Jjly5cDsHbt2rTeESLGnwRIIq0EAgH8g0KjdA2QrJUrMfx+suwpBQBq5ky8Bw4QCARSeGQiJezQM54tbJoESEIIIcRJrbu7OyX9bkR6cNXWYkyeHJl4dtFFaG++iRYKjXtj6lWrVuFyuTj77LNjfsySJUtwuVzSB0mcQAIkkVYCgQA+uyExMHBhnm48a9bQv3AhLp9v4Guu+fPx19fTaW/BE6eLine truncated
|
||||||
|
"text/plain": [
|
||||||
|
"<Figure size 1440x720 with 1 Axes>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"needs_background": "light"
|
||||||
|
},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# savgol_filter (比高斯更加具有尖锐性,且window可控)\n",
|
||||||
|
"from scipy.signal import savgol_filter\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"data_pos_filter = savgol_filter(data_pos, window_length=5, polyorder=3, axis=0, mode='nearest')\n",
|
||||||
|
"print(f\"data_pos filter shape = {data_pos_filter.shape}\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# 30fps * 6s = 180帧\n",
|
||||||
|
"beg, nframe = 1000, 30*10\n",
|
||||||
|
"\n",
|
||||||
|
"plt.figure(figsize=(20,10))\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 3], color='silver', label=\"pose-3\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 3], color='r', label=\"pose-3 filter\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 4], color='silver', label=\"pose-4\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 4], color='g', label=\"pose-4 filter\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 5], color='silver', label=\"pose-5\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 5], color='b', label=\"pose-5 filter\")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_pos[beg:beg+nframe, 0], color='silver', label=\"pose-0\")\n",
|
||||||
|
"plt.plot(data_pos_filter[beg:beg+nframe, 0], color='black', label=\"pose-0 filter\")\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 41,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABIkAAAFlCAYAAABvDLgGAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOzdd1gUVxcH4N9QBBUrKhZAQcSCggWwl8TeY68xts8WW4yJRo0paozRGKOJLcaosWGPvUTFXkHACoqAUsRGkQ679/vjZCgKSJktwHmfZ57VLTN3l90p5557riSEAGOMMcYYY4wxxhgr2gx03QDGGGOMMcYYY4wxpnscJGKMMcYYY4wxxhhjHCRijDHGGGOMMcYYYxwkYowxxhhjjDHGGGPgIBFjjDHGGGOMMcYYAweJGGOMMcYYY4wxxhgAI103IDsVKlQQNWrU0HUzGGOMMcYYY4wxxgoNDw+Pl0KIim/fr9dBoho1auDmzZu6bgZjjDHGGGOMMcZYoSFJUlBm9/NwM8YYY4wxxhhjjDHGQSLGGGOMMcYYY4wxxkEixhhjjDHGGGOMMQY9r0nEGGOMMcYYY4wx9j7JyckIDg5GQkKCrpuiV0xNTWFpaQljY+McPZ+DRIwxxhhjjDHGGCvQgoODUapUKdSoUQOSJOm6OXpBCIFXr14hODgYNjY2OXoNDzdjjDHGGGOMMcZYgZaQkABzc3MOEKUjSRLMzc1zlV3FQSLGGGOMMcYYY4wVeBwgelduPxMOEjHGGGOMMcYYY4zpqcWLF8POzg61a9fGiRMnNLotrknEGGOMMcYYY4wxpofu3buHnTt34u7duwgNDUWHDh3g5+cHQ0NDjWyPM4kYY4wxxhhjjDHGFLB161a4urqiYcOGGD9+PK5duwZHR0ckJCQgNjYWDg4OuHPnDtzd3dGmTRv06dMH9erVw4QJE6BWq99Z3z///IPBgwfDxMQENjY2sLOzw/Xr1zXWfs4kYowxxhhjjDHGWOExfTrg5aXsOhs2BFasyPYp9+/fh5ubGy5dugRjY2NMmjQJvr6+6NWrF+bNm4f4+HgMHz4c9evXh7u7O65fv4579+6hevXq6NKlC/bt24f+/ftnWGdISAiaNWuW+n9LS0uEhIQo+97S4SARY4wxVhQ8egRYWwPFium6JYwxxhhjhdLp06fh4eEBFxcXAEB8fDwqVaqE+fPnw8XFBaampli5cmXq811dXWFrawsAGDJkCC5evPhOkEgI8c52NFmgm4NEjDHGWGEmBLBgAfDNN8BPPwFffKHrFjHGGGOMadZ7Mn40RQiBTz75BIsXL85w/7NnzxATE4Pk5GQkJCSgZMmSAN4N9kiShP379+O7774DAGzYsAGWlpZ4+vRp6nOCg4NRtWpVjb0HrknEGGOMFVbx8cDQoRQgMjAArl3TdYsYY4wxxgqt9u3bY8+ePXj+/DkA4PXr1wgKCsK4ceOwYMECDBs2DLNmzUp9/vXr1xEQEAC1Wg03Nze0atUKffr0gZeXF7y8vODs7IxevXph586dSExMREBAAB4+fAhXV1eNvQfOJGKMMcYKo7AwoHdv4OZNYMkSChD5+Oi6VYwxxhhjhVa9evWwcOFCdOrUCWq1GsbGxujduzeMjIwwdOhQqFQqtGjRAmfOnIGBgQGaN2+O2bNn4/bt26lFrN/m4OCAgQMHol69ejAyMsLvv/+usZnNAEDKbHybvnB2dhY3b97UdTMYY4yxguXWLaBXLyAiAti6FfjoI+D774FvvwXevAH+S3FmjDHGGCss7t+/j7p16+q6GTnm7u6OZcuW4fDhwxrfVmafjSRJHkII57efy8PNGGOMscLEzQ1o1QqQJODiRQoQAYCTE9UnunNHp81jjDHGGGP6i4NEjDHGWGHw4gUwaBAweDDg6Ahcv05TtcocHenW21snzWOMMcYYY2natWunlSyi3OIgEWOMMVbQ7d0LODgA+/cDCxcC588DlStnfE6NGkCpUlyXiDHGGGOMZYkLVzPGGGMF1cuXwJQpwM6dQOPGwOnTQIMGmT9XkiibiDOJGGOMMcZYFjiTiDHGGCuIfH0pe2jvXmDBAuDq1awDRDInJ8ok0uNJKxhjjDHGmO5wJhFjjDFWEG3fTplEnp4U/MkJR0cgOhoICqLhZ4wxxhhjjKXDmUSMMcZYQXTxIgWHchogAtKey3WJGGOMMcYKhFevXuGDDz6AmZkZJk+enOExDw8PNGjQAHZ2dpg6dSqEAtniHCRijDHGCprkZBpe1qpV7l5Xvz7VJuK6RIwxxhhjBYKpqSkWLFiAZcuWvfPYxIkTsX79ejx8+BAPHz7E8ePH8709DhIxxhhjBY2XFxAXl/sgkZkZULMmZxIxxhhjjGnI1q1b4erqioYNG2L8+PG4du0aHB0dkZCQgNjYWDg4OODOnTtwd3dHmzZt0KdPH9SrVw8TJkyAWq1+Z30lS5ZEq1atYGpqmuH+sLAwREdHo3nz5pAkCSNGjMCBAwfy3X6uScQYY4wVNJcu0W3Llrl/Lc9wxhhjjLFCbvrx6fB65qXoOhtWbogVXVZk+5z79+/Dzc0Nly5dgrGxMSZNmgRfX1/06tUL8+bNQ3x8PIYPH4769evD3d0d169fx71791C9enV06dIF+/btQ//+/XPUnpCQEFhaWqb+39LSEiEhIfl5iwA4SMRY3kVFAefPAz176roljLGi5uJFKjxdrVruX+vkBOzfD8TGAiVLKt40xhhjjLGi6vTp0/Dw8ICLiwsAID4+HpUqVcL8+fPh4uICU1NTrFy5MvX5rq6usLW1BQAMGTIEFy9ezHGQKLP6Q5Ik5fs9cJCIsbz65Rfgu++oLkjTprpuDWOsqBCCgkQdO+bt9Y6OtI47d3jfxRhjjLFC6X0ZP5oihMAnn3yCxYsXZ7j/2bNniImJQXJyMhISElDyv466t4M6kiRh//79+O677wAAGzZsgLOzc6bbsrS0RHBwcOr/g4ODUbVq1Xy/B0VqEkmStFGSpOeSJN3J4vF2kiRFSZLk9d8yX4ntMqZTJ07Q7Zo1um0HY6xo8fcHwsNzX49IxjOcMcYYY4xpRPv27bFnzx48f/4cAPD69WsEBQVh3LhxWLBgAYYNG4ZZs2alPv/69esICAiAWq2Gm5sbWrVqhT59+sDLywteXl5ZBogAoEqVKihVqhSuXr0KIQS2bNmC3r175/s9KJVJtAnAbwC2ZPOcC0KIHgptjzHdiogArl+noRo7dwI//wyYm+u6VYyxouDiRbrNa5CoenWgVCmuS8QYY4wxprB69eph4cKF6NSpE9RqNYyNjdG7d28YGRlh6NChUKlUaNGiBc6cOQMDAwM0b94cs2fPxu3bt1OLWGemRo0aiI6ORlJSEg4cOICTJ0+iXr16WLNmDUaOHIn4+Hh07doVXbt2zfd7UCRIJIQ4L0lSDSXWxViBcOYMoFYDy5YBEycCmzYBn3+u61YxxoqCixeBcuWAunXz9noDA6BBA84kYowxxhjTgEGDBmHQoEGZPmZoaIhr164BANzd3VGiRAm4ubm9d52BgYGZ3u/s7Iw7dzId0JVnigw3y6HmkiR5S5J0TJIkBy1ulzHlnTwJlC4NjBkDtG5NQ84yma6QMcYUd+kSzWpmkI9DuJMTBYkyKXjIGGOMMcaKLm0FiTwBVBdCOAFYBeBAVk+UJGmcJEk3JUm6+eLFCy01j7FcEILqEX34IWBsTJlE/v7Av//qumWMscLuxQvgwYO8DzWTOTrSDI1PnijTLsYYY4wxlivt2rXD4cOHdd2Md2glSCSEiBZCxPz376MAjCVJqpDFc9cLIZyFEM4VK1bURvMYy51Hj4CgIKBTJ/p/375AxYrA6tW6bRdjrPC7fJluW7bM33q4eDVjjDHGGMuEVoJEkiRVlv6b202SJNf/tvtKG9tmTHEnT9KtHCQyMQHGjgUOHQKePtVduxhjhd/Fi0CxYkA2M13kSP36dMvFqxljjDHGWDqKBIkkSdoB4AqA2pIkBUuSNEaSpAmSJE347yn9AdyRJMkbwEoAg4XgQgisgDp5ErC1BWrWTLtv3DgahrZ+ve7axRgr/C5eBFxcAFPT/K2nVCnah3EmEWOMMcYYS0ep2c2GvOfx3wD8psS2GNOp5GSa2Wz48Iz316gBdO8ObNgAfP019fQzxpiS4uMBDw9gxgxl1ufoyJlEjDHGGGMsA23ObsZYwXf1KhATkzbULL2JE4Fnz4ADB7TeLMZYEXDjBgWq81u0WubkBDx8CMTFKbM+xhhjjDGmMU+ePIGZmRmWLVuWep+HhwcaNGgAOzs7TJ06FUoM2OIgEWO5cfIkYGgIfPDBu4917gzY2ABr1mi/XYyxwu/iRbpt0UKZ9Tk60jDZO3eUWR9jjDHGGNOYzz77DF27ds1w38SJE7F+/Xo8fPgQDx8+xPHjx/O9HQ4SMZYbJ08CTZsCZcu++5ihITB+PODuDty7p+2WMcYKu4sXAQcHoHx5ZdbHM5wxxhhjjClu69atcHV1RcOGDTF+/Hhcu3YNjo6OSEhIQGxsLBwcHHDnzh24u7ujTZs26NOnD+rVq4cJEyZArVZnus4DBw7A1tYWDg4OqfeFhYUhOjoazZs3hyRJGDFiBA4oMKpFkZpEjBUJr1/TcI9vvsn6OaNHA/PnA2vXAitXaq9tjLHCTaUCLl8GBg1Sbp01agBmZlyXiDHGGGOFzvTp0+Hl5aXoOhs2bIgVK1Zk+5z79+/Dzc0Nly5dgrGxMSZNmgRfX1/06tUL8+bNQ3x8PIYPH4769evD3d0d169fx71791C9enV06dIF+/btQ//+/TOsMzY2FkuWLMGpU6cyDDULCQmBpaVl6v8tLS0REhKS7/fJQSLGcur0aRqakVk9IlnFikC7dnQxxxhjSrl7F4iKUq4eEQAYGNCQM84kYowxxhhTxOnTp+Hh4QEXFxcAQHx8PCpVqoT58+fDxcUFpqamWJkumcDV1RW2trYLine truncated
|
||||||
|
"text/plain": [
|
||||||
|
"<Figure size 1440x432 with 1 Axes>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"needs_background": "light"
|
||||||
|
},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# visualize the exp [3:6]\n",
|
||||||
|
"plt.figure(figsize=(20,6))\n",
|
||||||
|
"\n",
|
||||||
|
"# 30fps * 6s = 180帧\n",
|
||||||
|
"beg, nframe = 1000, 30*6\n",
|
||||||
|
"\n",
|
||||||
|
"plt.plot(data_exp[beg:beg+nframe, 0], color='r', label=\"exp-0\")\n",
|
||||||
|
"plt.plot(data_exp[beg:beg+nframe, 10], color='g', label=\"exp-10\")\n",
|
||||||
|
"plt.plot(data_exp[beg:beg+nframe, 40], color='black', label=\"exp-40\")\n",
|
||||||
|
"plt.plot(data_exp[beg:beg+nframe, 49], color='b', label=\"exp-49\")\n",
|
||||||
|
"\n",
|
||||||
|
"# plt.ylim(-1,2)\n",
|
||||||
|
"plt.legend()\n",
|
||||||
|
"plt.show()\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"interpreter": {
|
||||||
|
"hash": "7631c3454b293d59f44fb25da873c3d73daf8a0a859dfd3174f920d540a4d0d0"
|
||||||
|
},
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.8.8 64-bit ('base': conda)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.8.8"
|
||||||
|
},
|
||||||
|
"orig_nbformat": 4
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import time
|
||||||
|
import sys
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
import numpy as np
|
||||||
|
import imageio
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch.utils.data import DataLoader
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
|
||||||
|
from src.datasets import create_dataset
|
||||||
|
from src.models.functions import get_pad_mask, get_subsequent_mask
|
||||||
|
from src.models import create_model, calculate_model_params
|
||||||
|
from src.config import config as opt
|
||||||
|
from src.config import update_config
|
||||||
|
from src.datasets.grid_ldmk import GRID_LdmkDataset
|
||||||
|
from src.models.transformer_a2l import TransformerA2L
|
||||||
|
|
||||||
|
from common.logger import Logger
|
||||||
|
from common.vis.visualizer import Visualizer
|
||||||
|
from common.metrics.utils import AverageMeterDict
|
||||||
|
from common.image import save_image
|
||||||
|
from common.landmark import landmark_to_image
|
||||||
|
|
||||||
|
|
||||||
|
def parese_args():
|
||||||
|
pareser = argparse.ArgumentParser(description='Facial Landmark Disentangle Network')
|
||||||
|
|
||||||
|
# general
|
||||||
|
pareser.add_argument("--opt", type=str, default="experiments/W300/test-landmark.yaml", help="experiment configure file name")
|
||||||
|
pareser.add_argument("--load_epoch", default=None, help="experiment configure file name")
|
||||||
|
args, _ = pareser.parse_known_args()
|
||||||
|
update_config(args.opt)
|
||||||
|
return pareser.parse_args()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
args = parese_args()
|
||||||
|
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
|
||||||
|
path_checkpoint = Path(opt.MODEL.path_checkpoint)
|
||||||
|
|
||||||
|
# update load_epoch
|
||||||
|
if args.load_epoch is not None:
|
||||||
|
opt.MODEL.load_epoch = args.load_epoch
|
||||||
|
|
||||||
|
# setting logger and output dir
|
||||||
|
path_config = Path(args.opt)
|
||||||
|
logger = Logger(opt.OUTPUT_DIR, path_config=path_config)
|
||||||
|
opt.OUTPUT_DIR = logger.path_output
|
||||||
|
path_save = Path(opt.OUTPUT_DIR)
|
||||||
|
|
||||||
|
# update load_epoch
|
||||||
|
if args.load_epoch is not None:
|
||||||
|
opt.MODEL.load_epoch = args.load_epoch
|
||||||
|
|
||||||
|
# load data
|
||||||
|
data_test = GRID_LdmkDataset(opt)
|
||||||
|
data_loader = DataLoader(data_test, batch_size=opt.TEST.batch_size, shuffle=False, drop_last=False)
|
||||||
|
logger.info(f"test dataset = {len(data_test)}, data_batch = {len(data_loader)}")
|
||||||
|
|
||||||
|
# load model
|
||||||
|
netG = TransformerA2L(opt) # [100, 500, 1000, 2000, 2300]
|
||||||
|
seleted_epochs = [3390, 3000, 2500, 2000, 1500, 1000, 500] #8000, 9000,10000] #000, 9000, 9500, 10000]
|
||||||
|
|
||||||
|
print("load from -->", path_checkpoint)
|
||||||
|
for epoch in seleted_epochs:
|
||||||
|
netG.eval()
|
||||||
|
|
||||||
|
# load model parameters
|
||||||
|
ipath_checkpoint = path_checkpoint.joinpath("checkpoints", f'{epoch}_net_G.pth')
|
||||||
|
state_dict = torch.load(str(ipath_checkpoint), map_location=str(device))
|
||||||
|
netG.load_state_dict(state_dict)
|
||||||
|
netG = netG.to(device)
|
||||||
|
|
||||||
|
# test data
|
||||||
|
avg_meter = AverageMeterDict()
|
||||||
|
for i, ibatch_data in enumerate(data_loader):
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
batch_ldmk = ibatch_data['ldmk_norm'] # (1, 25N, 68, 2)
|
||||||
|
batch_mfcc = ibatch_data['mfcc_feat'] # (1, 100N, 13)
|
||||||
|
batch_path = ibatch_data['ldmk_path']
|
||||||
|
# batch_mask = get_subsequent_mask(25) # (1, N, N)
|
||||||
|
# batch_mask = batch_mask.to(device)
|
||||||
|
batch_ldmk = batch_ldmk.float().to(device)
|
||||||
|
batch_mfcc = batch_mfcc.float().to(device)
|
||||||
|
|
||||||
|
(B, N, *_) = batch_ldmk.shape
|
||||||
|
|
||||||
|
batch_predt = torch.zeros((B, N+1, 68, 2)).float().to(device) # (1, N, 68, 2)
|
||||||
|
batch_predt[:, :25, :, : ] = batch_ldmk[:, :25, :, :]
|
||||||
|
|
||||||
|
print(f"ldmk={batch_ldmk.shape}, mfcc={batch_mfcc.shape}, predt={batch_predt.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
for j in range(24, N):
|
||||||
|
|
||||||
|
if j == 0:
|
||||||
|
jbatch_ldmk = batch_ldmk[:, :1, :, :] # (1, 1, 68, 2)
|
||||||
|
jbatch_mfcc = batch_mfcc[:, :4, :] # (1, 4, 13)
|
||||||
|
batch_mask = get_subsequent_mask(1).to(device) # (1, 1, 1)
|
||||||
|
elif j < 25:
|
||||||
|
jbatch_ldmk = batch_predt[:, :(j+1), :, :] # (1, J, 68, 2)
|
||||||
|
jbatch_mfcc = batch_mfcc[:, :4*(j+1), :] # (1, 4J, 13)
|
||||||
|
batch_mask = get_subsequent_mask(j+1).to(device) # (1, N, N)
|
||||||
|
|
||||||
|
else:
|
||||||
|
jbatch_ldmk = batch_predt[:, j-24 :(j+1), :, :] # (1, 25, 68, 2)
|
||||||
|
jbatch_mfcc = batch_mfcc[:, 4*j-96 :4*(j+1), :] # (1, 100, 13)
|
||||||
|
batch_mask = get_subsequent_mask(25).to(device) # (1, N, N)
|
||||||
|
|
||||||
|
|
||||||
|
y = netG(jbatch_mfcc, None, jbatch_ldmk, batch_mask, shift=False) # (1, j, 68, 2)
|
||||||
|
batch_predt[:, j+1, :, :] = y[:, -1, :, :] # The last one
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
metr_dict = {}
|
||||||
|
|
||||||
|
# reconstruction loss
|
||||||
|
predt = batch_predt[:, 1:, :, :].reshape(-1, 68, 2) # (BN, 68, 2)
|
||||||
|
targt = batch_ldmk.reshape(-1, 68, 2) # (BN, 68, 2)
|
||||||
|
|
||||||
|
diff = (predt - targt) * (predt - targt) # (BN, 68, 2)
|
||||||
|
diff = torch.sqrt( diff[:, :, 0] + diff[:, :, 1]) # (NB, 68,)
|
||||||
|
|
||||||
|
metr_dict["metric_rec"] = torch.mean(torch.sum(diff, dim=1)) # (1,)
|
||||||
|
metr_dict["metric_mae"] = F.l1_loss(predt, targt, reduce="mean")
|
||||||
|
|
||||||
|
|
||||||
|
# show image
|
||||||
|
if i % 10 == 0 and opt.verbose:
|
||||||
|
|
||||||
|
frames = []
|
||||||
|
|
||||||
|
for j in range(24, N):
|
||||||
|
img = landmark_to_image(batch_ldmk[0, j, :, :], text=f"frame-{j:02}-render")
|
||||||
|
img_predt = landmark_to_image(batch_predt[0, j+1, :, :], text=f"frame-{j:02}-render")
|
||||||
|
frames.append(np.concatenate([img, img_predt], axis=1)) # (2W, H, 3)
|
||||||
|
|
||||||
|
|
||||||
|
jpath_save_img = path_save.joinpath(f"Epoch-{epoch}-Batch-{i:03d}-GIF.gif")
|
||||||
|
|
||||||
|
# duration = (N-25) / 30.0
|
||||||
|
|
||||||
|
imageio.mimsave(str(jpath_save_img), frames, 'GIF', duration=0.25)
|
||||||
|
|
||||||
|
# jpath_save_pdt = path_save.joinpath(f"Epoch-{epoch}-Batch-{i:03d}-predt", f"frame-{j:05d}.jpg")
|
||||||
|
# jpath_save_img.parent.mkdir(exist_ok=True, parents=True)
|
||||||
|
# jpath_save_pdt.parent.mkdir(exist_ok=True, parents=True)
|
||||||
|
|
||||||
|
# save_image(img, jpath_save_img)
|
||||||
|
# save_image(img_predt, jpath_save_pdt)
|
||||||
|
|
||||||
|
|
||||||
|
# update
|
||||||
|
avg_meter.update(metr_dict)
|
||||||
|
|
||||||
|
if i% 10 == 0:
|
||||||
|
print(f"batch {i:03d}:", avg_meter.print_msg())
|
||||||
|
|
||||||
|
print(f"Epoch {epoch} validation:\n\t", avg_meter.print_msg())
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
UNZIP_FILES = False
|
||||||
|
MV_AUDIO_FILES = False
|
||||||
|
MV_VIDEO_FILES = False
|
||||||
|
EXTRACT_AUDIO = True
|
||||||
|
|
||||||
|
total_pid = ["s1.", "s2.", "s3.", "s4.", "s5.", "s6.", "s7.", "s8.", "s9.", "s10." ]
|
||||||
|
# total_pid = [ "s6.", "s7.", "s8.", "s9.", "s21."]
|
||||||
|
|
||||||
|
def is_exist_pid(file_name):
|
||||||
|
for iid in total_pid:
|
||||||
|
if str(iid) in str(file_name.name):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
path_root = Path("/yrfs/lsen/DATA/GRID/")
|
||||||
|
|
||||||
|
if UNZIP_FILES:
|
||||||
|
path_zip = path_root.joinpath("zip_data")
|
||||||
|
path_data = path_root.joinpath("unzip_data")
|
||||||
|
path_data.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_zip_files = sorted(path_zip.glob("./*.tar"))
|
||||||
|
|
||||||
|
print(f"Have {len(v_zip_files)} zip files, \n {v_zip_files[:10]}")
|
||||||
|
|
||||||
|
|
||||||
|
for i, izip in enumerate(v_zip_files):
|
||||||
|
|
||||||
|
if not is_exist_pid(izip): continue
|
||||||
|
|
||||||
|
ipath_data = path_data.joinpath(str(izip.stem))
|
||||||
|
|
||||||
|
# if not ipath_data.exists():
|
||||||
|
cmd = f"cd {str(path_zip)}; tar -xf {str(izip)} -C {str(path_data)}"
|
||||||
|
print(f"RUN: {cmd}")
|
||||||
|
os.system(cmd)
|
||||||
|
|
||||||
|
#break
|
||||||
|
|
||||||
|
if MV_AUDIO_FILES:
|
||||||
|
path_unzip = path_root.joinpath("unzip_data")
|
||||||
|
v_ids_file = sorted(path_unzip.glob("*"))
|
||||||
|
|
||||||
|
print(f"Have {len(v_ids_file)} persons files, \n {v_ids_file[:10]}")
|
||||||
|
|
||||||
|
for i, iid in enumerate(v_ids_file):
|
||||||
|
cmd = f"cd {str(iid)}; mkdir audio; mv *.wav audio"
|
||||||
|
print(f"RUN: {cmd}")
|
||||||
|
os.system(cmd)
|
||||||
|
|
||||||
|
#break
|
||||||
|
|
||||||
|
if MV_VIDEO_FILES:
|
||||||
|
path_data = path_root.joinpath("unzip_data")
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
|
||||||
|
|
||||||
|
# for each person
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name, "video/mpg_6000")
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*.mpg"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_videos in v_dir_videos:
|
||||||
|
ivideo_name = ipath_videos.stem
|
||||||
|
|
||||||
|
# copy video
|
||||||
|
ipath_video_target = path_root.joinpath("processing", id_name, ivideo_name, "video/video_orignal.mp4")
|
||||||
|
|
||||||
|
if not ipath_video_target.exists():
|
||||||
|
ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
|
||||||
|
#print(f"copy {ipath_videos} --> {ipath_video_target}")
|
||||||
|
|
||||||
|
# # copy audio
|
||||||
|
# ipath_audio_source = path_data.joinpath(id_name, f"audio/{ivideo_name}.wav")
|
||||||
|
# ipath_audio_target = path_root.joinpath("processing", id_name, ivideo_name, "audio/audio_orignal.wav")
|
||||||
|
|
||||||
|
# if not ipath_audio_target.exists():
|
||||||
|
# ipath_audio_target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
# shutil.copy(src=str(ipath_audio_source), dst=str(ipath_audio_target))
|
||||||
|
# #print(f"copy {ipath_audio_source} --> {ipath_audio_target}")
|
||||||
|
|
||||||
|
# break
|
||||||
|
|
||||||
|
if EXTRACT_AUDIO:
|
||||||
|
|
||||||
|
path_data = path_root.joinpath("processing")
|
||||||
|
|
||||||
|
vpath_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
|
||||||
|
|
||||||
|
for i, ipath_id in enumerate(vpath_ids):
|
||||||
|
pid = ipath_id.stem # person id
|
||||||
|
|
||||||
|
# if pid in ["s1", "s10", "s11", "s12", "s13", "s14"]:
|
||||||
|
# continue
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
list_dict = []
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
vid = ipath_video.parent.parent.stem # video id
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> processing the {iv}-th video --> {ipath_video}")
|
||||||
|
|
||||||
|
ipath_audio = ipath_video.parent.parent.joinpath("audio/audio_extract.wav")
|
||||||
|
ipath_audio.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
if ipath_audio.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# extract audio
|
||||||
|
cmd = f'ffmpeg -y -i {str(ipath_video)} -vn -acodec pcm_s16le -ac 1 -ar 16000 {str(ipath_audio)}'
|
||||||
|
# print(f"RUN: {cmd}")
|
||||||
|
os.system(cmd)
|
||||||
|
|
||||||
|
# break
|
||||||
|
#break
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=True)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each speaker
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
if id_name not in total_pid: continue
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
|
||||||
|
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
|
||||||
|
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
if ipath_save_feat.exists() or not ipath_audio.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
fps = 25
|
||||||
|
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 640 让这个sr是fps的整数,
|
||||||
|
hop_len = int(sr / fps)
|
||||||
|
n_fft = int(sr * 0.13) # default 2048
|
||||||
|
# print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
|
||||||
|
|
||||||
|
# melspectrogram
|
||||||
|
mel = librosa.feature.melspectrogram(y=data, sr=sr,
|
||||||
|
n_fft=n_fft, # FFT窗口的长度
|
||||||
|
hop_length=hop_len, # 帧移
|
||||||
|
win_length=n_fft, # 窗口长度,默认=n_fft
|
||||||
|
window="hann", # 加hanming窗
|
||||||
|
n_mels=27, # 滤波器组
|
||||||
|
fmin=0.0, fmax=8000)
|
||||||
|
mel = np.log(mel+1).T
|
||||||
|
print(f"sr={sr}, data ={data.shape}, mel = {mel.shape}, frames = {(len(data) / sr) * fps}, (min,max)=({np.min(mel), np.max(mel)}")
|
||||||
|
|
||||||
|
# align to video
|
||||||
|
if mel.shape[0] < 75:
|
||||||
|
print(f"\n skip, mel shape ={mel.shape}, frames={(len(data) / sr) * fps}")
|
||||||
|
else:
|
||||||
|
mel_align = mel[:75, :]
|
||||||
|
|
||||||
|
# save
|
||||||
|
np.save(ipath_save_feat, mel_align)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
import torch
|
||||||
|
from scipy.io.wavfile import read
|
||||||
|
|
||||||
|
# We're using the audio processing from TacoTron2 to make sure it matches
|
||||||
|
sys.path.insert(0, '/ssdata1/lsen/CODE/Audio2Expression/3rdpart/')
|
||||||
|
import tacotron2
|
||||||
|
from tacotron2.layers import TacotronSTFT
|
||||||
|
|
||||||
|
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
# STFT model
|
||||||
|
model = TacotronSTFT(filter_length=1024,
|
||||||
|
hop_length=256,
|
||||||
|
win_length=1024,
|
||||||
|
sampling_rate=22050,
|
||||||
|
mel_fmin=0.0, mel_fmax=8000)
|
||||||
|
|
||||||
|
# dataset load
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=False)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each speaker
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
if id_name not in total_pid: continue
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
|
||||||
|
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
|
||||||
|
ipath_save = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy") # feat_mel_trim_split
|
||||||
|
|
||||||
|
if ipath_save.exists(): continue
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
audio, sr = librosa.load(str(ipath_audio), mono=True) # 16484 = fps * 550 让这个sr是fps的整数,
|
||||||
|
|
||||||
|
if sr != 22050:
|
||||||
|
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
|
||||||
|
|
||||||
|
audio = torch.from_numpy(audio).float()
|
||||||
|
audio = audio.unsqueeze(0)
|
||||||
|
print(f"audio shape = {audio.shape}, audio min-max({audio.min():.4f}, {audio.max():.4f})")
|
||||||
|
audio[audio > 1.0] = 1.0
|
||||||
|
audio[audio < -1.0] = -1.0
|
||||||
|
|
||||||
|
melspec = model.mel_spectrogram(audio)
|
||||||
|
melspec = torch.squeeze(melspec, 0) # (80, 20374)
|
||||||
|
print(f"Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / 75}")
|
||||||
|
|
||||||
|
# save
|
||||||
|
melspec = melspec.permute(1,0) # (nsplits, nsteps, 80)
|
||||||
|
|
||||||
|
np.save(ipath_save, melspec) # (nsplit, 173, 80)
|
||||||
|
print(f"melspec shape = {melspec.shape}, save to --> {ipath_save}")
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import cv2
|
||||||
|
import os, sys
|
||||||
|
import glob
|
||||||
|
import numpy as np
|
||||||
|
import time
|
||||||
|
import pdb
|
||||||
|
import argparse
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/yrfs/lsen/DATA/GRID/processing")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=False)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
|
||||||
|
|
||||||
|
# for each speaker
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
if id_name not in total_pid: continue
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
# create data path
|
||||||
|
path_save_frames = ipath_video.parent.parent.joinpath("frames")
|
||||||
|
|
||||||
|
# if already exists frames
|
||||||
|
if path_save_frames.exists():
|
||||||
|
if len(list(path_save_frames.glob("*.jpg"))) > 10:
|
||||||
|
continue
|
||||||
|
|
||||||
|
path_save_frames.mkdir(parents=True, exist_ok=True)
|
||||||
|
#print("save frames dir = ", {path_save_frames})
|
||||||
|
|
||||||
|
# STEP1: extract frames
|
||||||
|
count = 0
|
||||||
|
cap = cv2.VideoCapture(str(ipath_video))
|
||||||
|
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
success, image = cap.read()
|
||||||
|
if not success:
|
||||||
|
break
|
||||||
|
|
||||||
|
ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}.jpg")
|
||||||
|
|
||||||
|
if not ipath_frame.exists():
|
||||||
|
cv2.imwrite(str(ipath_frame), image)
|
||||||
|
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> Extract {iv}-th video, have {length} frames, {ipath_video}")
|
||||||
|
|
||||||
|
#print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
|
||||||
|
|
||||||
|
#break
|
||||||
|
#break
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
from pathlib2 import Path
|
||||||
|
from face_alignment import FaceAlignment, LandmarksType
|
||||||
|
|
||||||
|
|
||||||
|
def select_ldmk(ladmks):
|
||||||
|
|
||||||
|
ladmks = np.array(ladmks)
|
||||||
|
area = []
|
||||||
|
for i in range(ladmks.shape[0]):
|
||||||
|
lands = ladmks[i, ...]
|
||||||
|
|
||||||
|
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
|
||||||
|
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
|
||||||
|
area.append((xmax - xmin) * (ymax-ymin))
|
||||||
|
|
||||||
|
|
||||||
|
print("area = ", area, "select = ", np.argmax(area))
|
||||||
|
return ladmks[np.argmax(area), :, :]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
|
||||||
|
|
||||||
|
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=True)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each person
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
#if id_name != "s29": continue
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
#print(f"ipath_data = {ipath_data}")
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
ipath_landmk.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# STEP1: get frames
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
# STEP2: extract landmarks
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
if not ipath_landmk_frame.exists():
|
||||||
|
|
||||||
|
# detect image
|
||||||
|
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
|
||||||
|
|
||||||
|
ldmk_pred = model.get_landmarks(np.array(image))
|
||||||
|
if ldmk_pred is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# select the first one or the bigger one face
|
||||||
|
if len(ldmk_pred) > 1:
|
||||||
|
ldmk_pred = select_ldmk(ldmk_pred)
|
||||||
|
else:
|
||||||
|
ldmk_pred = ldmk_pred[0]
|
||||||
|
|
||||||
|
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
|
||||||
|
|
||||||
|
#break
|
||||||
|
#break
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
import librosa
|
||||||
|
import python_speech_features
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import multiprocessing
|
||||||
|
|
||||||
|
|
||||||
|
def splited_by_windows(data, wind_stride, wind_length, padding=True):
|
||||||
|
"""
|
||||||
|
data: seq_len1 x dim1
|
||||||
|
return: seq_len2 x wind_length x dim1
|
||||||
|
where seq_len2 = (L + 2p - k) // wind_stride + 1
|
||||||
|
"""
|
||||||
|
|
||||||
|
seq_len1, dim1 = data.shape
|
||||||
|
|
||||||
|
seq_len2 = seq_len1 // wind_stride + 1
|
||||||
|
|
||||||
|
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
|
||||||
|
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
|
||||||
|
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
|
||||||
|
|
||||||
|
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
|
||||||
|
|
||||||
|
for i in range(seq_len2):
|
||||||
|
ibeg = i * wind_stride
|
||||||
|
iend = i * wind_stride + wind_length
|
||||||
|
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
|
||||||
|
|
||||||
|
return data_output
|
||||||
|
|
||||||
|
|
||||||
|
# def func_processing(path_audio):
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each person
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
# if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
jpath_frame = jpath_data.joinpath("frames")
|
||||||
|
nframes = len(sorted(jpath_frame.glob("*.jpg")))
|
||||||
|
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
|
||||||
|
|
||||||
|
ipath_audio = jpath_data.joinpath("audio/audio_extract.wav")
|
||||||
|
ipath_feat = jpath_data.joinpath("audio/mfcc_feat.npy")
|
||||||
|
ipath_feat_align = jpath_data.joinpath("audio/mfcc_feat_align.npy")
|
||||||
|
|
||||||
|
# for some data not have .wav files
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"NOT EXISTING: {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ipath_feat_align.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# extarct mfcc feature
|
||||||
|
audio, sr = librosa.load(str(ipath_audio), sr=16000) # 16000, (69760, )
|
||||||
|
mfcc = python_speech_features.mfcc(audio, 16000, winstep=0.01) # seqlen1 x 13
|
||||||
|
np.save(ipath_feat, mfcc)
|
||||||
|
|
||||||
|
|
||||||
|
# splited by windows (to fit video frame with fps 25)
|
||||||
|
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
|
||||||
|
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
|
||||||
|
## seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
|
||||||
|
mfcc_align = splited_by_windows(mfcc, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
|
||||||
|
np.save(ipath_feat_align, mfcc_align)
|
||||||
|
|
||||||
|
if j % 50 == 0:
|
||||||
|
print(f"--> Extract {j}-th video landmark: audio shape={audio.shape}, mfcc shape={mfcc.shape}, mfcc_align = {mfcc_align.shape} duration={len(audio) / sr}")
|
||||||
|
|
||||||
|
# break
|
||||||
|
# break
|
||||||
Whitespace-only changes.
@@ -0,0 +1,98 @@
|
|||||||
|
import os,sys
|
||||||
|
import cv2
|
||||||
|
import math
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from reconstruction import Reconstruction
|
||||||
|
|
||||||
|
def get_rect(lands):
|
||||||
|
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
|
||||||
|
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
|
||||||
|
|
||||||
|
length = 1.2 * math.sqrt((xmax - xmin) * (xmax - xmin) + (ymax - ymin) * (ymax - ymin))
|
||||||
|
left = (xmax + xmin) / 2 - length / 2
|
||||||
|
top = (ymax + ymin) / 2 - length / 2
|
||||||
|
rect = np.array([left, top, length], dtype=np.float)
|
||||||
|
|
||||||
|
return rect
|
||||||
|
|
||||||
|
def show_landmarks(path_img, path_save, lands):
|
||||||
|
|
||||||
|
img = cv2.imread(str(path_img))
|
||||||
|
for i in range(68):
|
||||||
|
cv2.circle(img, (lands[i,0], lands[i,1]), 2, (255,0,0))
|
||||||
|
|
||||||
|
ipath_save = path_save.joinpath(path_img.stem + "_land.jpg")
|
||||||
|
|
||||||
|
cv2.imwrite(str(ipath_save), img)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
# load Reconstruction
|
||||||
|
model = Reconstruction()
|
||||||
|
|
||||||
|
# load data
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=True)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each person
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
# print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> Extract {iv}-th video landmark in {ipath_video}")
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
#print(f"ipath_data = {ipath_data}")
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_ladmks = ipath_data.joinpath("landmk")
|
||||||
|
ipath_coeffs = ipath_data.joinpath("coeff")
|
||||||
|
|
||||||
|
|
||||||
|
# STEP1: get frames and landmark
|
||||||
|
vpath_frames = sorted(ipath_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
vpath_ladmks = list(ipath_ladmks.glob("*.txt"))
|
||||||
|
vpath_coeffs = list(ipath_coeffs.glob("*.txt"))
|
||||||
|
|
||||||
|
if len(vpath_frames) != len(vpath_ladmks) or len(vpath_frames) ==0: # if missing landmark data
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ipath_coeffs.exists() and len(vpath_coeffs) == len(vpath_frames): # if have already reconstruction
|
||||||
|
continue
|
||||||
|
|
||||||
|
# STEP2: reconstruction
|
||||||
|
for ik, ipath_frame in enumerate(vpath_frames):
|
||||||
|
fid = int(ipath_frame.stem[-4:])
|
||||||
|
ipath_ladmk = ipath_ladmks.joinpath(f"frame-{fid:04d}.txt") # get landmark path
|
||||||
|
|
||||||
|
if not ipath_ladmk.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# read image and landmark
|
||||||
|
image = Image.open(str(ipath_frame)).convert('RGB') # (h, w, 3)
|
||||||
|
ladmk = np.loadtxt(ipath_ladmk, dtype=int) # (68, 2)
|
||||||
|
bbox = get_rect(ladmk)
|
||||||
|
# show_landmarks(image, path_save, ildmk)
|
||||||
|
|
||||||
|
# reconstruction
|
||||||
|
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=ipath_ladmks.parent)
|
||||||
|
|
||||||
|
if ik % 100 == 99:
|
||||||
|
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")
|
||||||
|
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import os,sys
|
||||||
|
import numpy as np
|
||||||
|
import librosa
|
||||||
|
import python_speech_features
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import multiprocessing
|
||||||
|
|
||||||
|
path_work = "/mnt/data/CODE/Audio-driven-TalkingFace-HeadPose/audio-to-expression"
|
||||||
|
sys.path.insert(0, path_work)
|
||||||
|
|
||||||
|
from src.tools.audio import get_melspec
|
||||||
|
|
||||||
|
|
||||||
|
def splited_by_windows(data, wind_stride, wind_length, padding=True):
|
||||||
|
"""
|
||||||
|
data: seq_len1 x dim1
|
||||||
|
return: seq_len2 x wind_length x dim1
|
||||||
|
where seq_len2 = (L + 2p - k) // wind_stride + 1
|
||||||
|
"""
|
||||||
|
|
||||||
|
seq_len1, dim1 = data.shape
|
||||||
|
|
||||||
|
seq_len2 = seq_len1 // wind_stride + 1
|
||||||
|
|
||||||
|
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
|
||||||
|
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
|
||||||
|
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
|
||||||
|
|
||||||
|
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
|
||||||
|
|
||||||
|
for i in range(seq_len2):
|
||||||
|
ibeg = i * wind_stride
|
||||||
|
iend = i * wind_stride + wind_length
|
||||||
|
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
|
||||||
|
|
||||||
|
return data_output
|
||||||
|
|
||||||
|
|
||||||
|
# def func_processing(path_audio):
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each person
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
# if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
jpath_frame = jpath_data.joinpath("frames")
|
||||||
|
nframes = len(sorted(jpath_frame.glob("*.jpg")))
|
||||||
|
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
|
||||||
|
|
||||||
|
ipath_audio = jpath_data.joinpath("audio/audio_extract.wav")
|
||||||
|
ipath_feat_save = jpath_data.joinpath("audio/melspec_feat.npy")
|
||||||
|
|
||||||
|
# for some data not have .wav files
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"NOT EXISTING: {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ipath_feat_save.exists():
|
||||||
|
print(f"EXSTING, {ipath_feat_save}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# extarct mfcc feature
|
||||||
|
audio, sr = librosa.load(str(ipath_audio), sr=16000) #16000, (69760, )
|
||||||
|
mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
|
||||||
|
|
||||||
|
|
||||||
|
y, sr = librosa.load(str(ipath_audio), sr=44100)
|
||||||
|
melFrames = np.transpose(get_melspec(y, sr, wsize=0.04, hsize=0.04)) # (n_frame, 64)
|
||||||
|
melDelta = np.insert(np.diff(melFrames, n=1, axis=0), 0, np.zeros((1, 64)), axis=0) # (n_frame - 1 , 64) + (1, 64) --> (n_frame, 64)
|
||||||
|
melDDelta = np.insert(np.diff(melFrames, n=2, axis=0), 0, np.zeros((2, 64)), axis=0) # (n_frame - 2 , 64) + (2, 64) --> (n_frame, 64)
|
||||||
|
data_audio = np.concatenate((melDelta, melDDelta), axis=1) # (n_frame, 128)
|
||||||
|
|
||||||
|
# save
|
||||||
|
np.save(str(ipath_feat_save), data_audio)
|
||||||
|
# print(f"SAVE: mfcc size={data_audio.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
|
||||||
|
|
||||||
|
# break
|
||||||
|
# break
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import os
|
||||||
|
import glob
|
||||||
|
import pdb
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from scipy.io import loadmat,savemat
|
||||||
|
|
||||||
|
COMBINE_COEFF_RBGFACE = True
|
||||||
|
COMBINE_LAMDK_RBGFACE = False
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each person
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
# if (j+1) % 100 == 100: print(f"processing {j+1}/{len(v_dir_videos)}")
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
jpath_frame = jpath_data.joinpath("frames")
|
||||||
|
jpath_ladmk = jpath_data.joinpath("landmk")
|
||||||
|
|
||||||
|
jpath_ladmk_save = jpath_data.joinpath("video/landmark.npy")
|
||||||
|
jpath_ladmk_save.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_frames = sorted(jpath_frame.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
|
||||||
|
v_ladmks = sorted(jpath_ladmk.glob("*.txt"), key=lambda x: int(x.stem[-4:]))
|
||||||
|
|
||||||
|
# print(f"contain {len(v_frames)} frames in {str(jpath_data)} -> {v_frames[:5]}")
|
||||||
|
|
||||||
|
|
||||||
|
if len(v_ladmks) != len(v_frames):
|
||||||
|
print(f"\t ERROR && Continue: This video have missing landmark, {str(jpath_ladmk)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif jpath_ladmk_save.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
else:
|
||||||
|
ladmk_all = np.zeros((len(v_frames), 68, 2), np.float32)
|
||||||
|
|
||||||
|
for k, iframe in enumerate(v_frames):
|
||||||
|
fid = int(iframe.stem[-4:])
|
||||||
|
|
||||||
|
# load data
|
||||||
|
kpath_proj = jpath_ladmk.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
ladmk_all[k, :, :] = np.loadtxt(str(kpath_proj)) # (68, 2)
|
||||||
|
|
||||||
|
|
||||||
|
# save combine data
|
||||||
|
np.save(str(jpath_ladmk_save), ladmk_all)
|
||||||
|
# print(f"combine the coeff: {str(jpath_videos)} --> {str(jpath_ladmk_save)}")
|
||||||
|
|
||||||
|
# break
|
||||||
|
# break
|
||||||
Whitespace-only changes.
@@ -0,0 +1,113 @@
|
|||||||
|
"""
|
||||||
|
generated train annotation data
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from collections import OrderedDict
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
pid_for_train = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
|
||||||
|
"s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20",
|
||||||
|
"s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30"]
|
||||||
|
pid_for_test = ["s31", "s32", "s33", "s34"]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
path_anno = Path("data/GRID/anno_test_half.pickle")
|
||||||
|
|
||||||
|
annodb = OrderedDict()
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
|
||||||
|
|
||||||
|
# iter
|
||||||
|
for i, ipath_id in enumerate(vpath_ids):
|
||||||
|
pid = ipath_id.stem # person id
|
||||||
|
|
||||||
|
# select train pid
|
||||||
|
if pid not in pid_for_test:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
list_dict = []
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
vid = ipath_video.parent.parent.stem # video id
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> processing the {iv}-th video --> {ipath_video}")
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
ipath_frame = ipath_data.joinpath("frames")
|
||||||
|
ipath_ladmk = ipath_data.joinpath("landmk")
|
||||||
|
# ipath_coeff = ipath_data.joinpath("coeff")
|
||||||
|
ipath_mfccs = ipath_data.joinpath("audio/mfcc_feat.npy")
|
||||||
|
|
||||||
|
|
||||||
|
# STEP1: check if missing data
|
||||||
|
vpath_frame = sorted(ipath_frame.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
# vpath_coeff = sorted(ipath_coeff.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
vpath_ladmk = sorted(ipath_ladmk.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
nframes = len(vpath_frame)
|
||||||
|
|
||||||
|
# assert
|
||||||
|
if (nframes < 25) or (nframes != len(vpath_ladmk)) : # or (nframes != len(vpath_coeff)):
|
||||||
|
print(f"DEBUG: nframes={nframes}, nladmk={len(vpath_ladmk)}, --> {ipath_video}") # ncoeff={len(vpath_coeff)}
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load mfcc
|
||||||
|
list_mfcc = np.load(ipath_mfccs) # nframes x 28 x 12
|
||||||
|
|
||||||
|
# # load 3DMM & landmarks
|
||||||
|
# list_idn = np.zeros((nframes, 100), dtype=float) # coeff idn, nframes x 100
|
||||||
|
# list_exp = np.zeros((nframes, 79), dtype=float) # coeff exp, nframes x 79
|
||||||
|
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(vpath_frame):
|
||||||
|
fid = int(kpath_frame.stem[-4:]) # frame id
|
||||||
|
|
||||||
|
# # 3dmm
|
||||||
|
# kpath_3dmm = ipath_coeff.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
# coeff = np.loadtxt(kpath_3dmm, dtype=float) # 316: idn-100, exp-79, tex-100, euler-3, trans-3, illum-27, camr-4
|
||||||
|
# list_idn[k, :] = coeff[:100] # 100 identity coeff
|
||||||
|
# list_exp[k, :] = coeff[100:100+79] # 79 expression coeff
|
||||||
|
|
||||||
|
# ldmk
|
||||||
|
kpath_ldmk = ipath_ladmk.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
ldmk = np.loadtxt(kpath_ldmk) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
|
||||||
|
# STEP 3: concat data
|
||||||
|
list_dict.append({"pid": pid, "vid": vid,
|
||||||
|
"mfcc": list_mfcc,
|
||||||
|
# "exp": list_exp, "idn":list_idn,
|
||||||
|
"ldmk": v_ldmk, "ldmk_norm": v_ldmk_norm, "ldmk_auxs":v_ldmk_auxs
|
||||||
|
})
|
||||||
|
|
||||||
|
annodb[pid] = list_dict
|
||||||
|
|
||||||
|
# pickle and save
|
||||||
|
with open(str(path_anno), "wb") as f:
|
||||||
|
pickle.dump(annodb, f)
|
||||||
|
|
||||||
|
print(f"Total have {len(annodb)} item anno, save to --> {path_anno}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""
|
||||||
|
generated train annotation data
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from collections import OrderedDict
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
pid_for_train = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
|
||||||
|
"s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20",
|
||||||
|
"s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30"]
|
||||||
|
pid_for_test = ["s31", "s32", "s33", "s34"]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/GRID/processing")
|
||||||
|
path_anno = Path("data/GRID/anno_train_full.pickle")
|
||||||
|
|
||||||
|
annodb = OrderedDict()
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
|
||||||
|
|
||||||
|
# iter
|
||||||
|
n_videos = 0
|
||||||
|
for i, ipath_id in enumerate(vpath_ids):
|
||||||
|
pid = ipath_id.stem # person id
|
||||||
|
|
||||||
|
# select train pid
|
||||||
|
if pid not in pid_for_train:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
list_dict = []
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
vid = ipath_video.parent.parent.stem # video id
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> processing the {iv}-th video --> {ipath_video}")
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
ipath_frame = ipath_data.joinpath("frames")
|
||||||
|
ipath_ladmk = ipath_data.joinpath("landmk")
|
||||||
|
# ipath_coeff = ipath_data.joinpath("coeff")
|
||||||
|
ipath_mfccs = ipath_data.joinpath("audio/mfcc_feat.npy")
|
||||||
|
|
||||||
|
|
||||||
|
# STEP1: check if missing data
|
||||||
|
vpath_frame = sorted(ipath_frame.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
# vpath_coeff = sorted(ipath_coeff.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
vpath_ladmk = sorted(ipath_ladmk.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
nframes = len(vpath_frame)
|
||||||
|
|
||||||
|
# assert
|
||||||
|
if (nframes < 60) or (nframes != len(vpath_ladmk)) : # or (nframes != len(vpath_coeff)):
|
||||||
|
print(f"DEBUG: nframes={nframes}, nladmk={len(vpath_ladmk)}, --> {ipath_video}") # ncoeff={len(vpath_coeff)}
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load mfcc
|
||||||
|
# list_mfcc = np.load(ipath_mfccs) # nframes x 28 x 12
|
||||||
|
|
||||||
|
# # load 3DMM & landmarks
|
||||||
|
# list_idn = np.zeros((nframes, 100), dtype=float) # coeff idn, nframes x 100
|
||||||
|
# list_exp = np.zeros((nframes, 79), dtype=float) # coeff exp, nframes x 79
|
||||||
|
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(vpath_frame):
|
||||||
|
fid = int(kpath_frame.stem[-4:]) # frame id
|
||||||
|
|
||||||
|
# # 3dmm
|
||||||
|
# kpath_3dmm = ipath_coeff.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
# coeff = np.loadtxt(kpath_3dmm, dtype=float) # 316: idn-100, exp-79, tex-100, euler-3, trans-3, illum-27, camr-4
|
||||||
|
# list_idn[k, :] = coeff[:100] # 100 identity coeff
|
||||||
|
# list_exp[k, :] = coeff[100:100+79] # 79 expression coeff
|
||||||
|
|
||||||
|
# ldmk
|
||||||
|
kpath_ldmk = ipath_ladmk.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
ldmk = np.loadtxt(kpath_ldmk) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
|
||||||
|
# STEP 3: concat data
|
||||||
|
list_dict.append({"pid": pid, "vid": vid,
|
||||||
|
# "mfcc": list_mfcc,
|
||||||
|
# "exp": list_exp, "idn":list_idn,
|
||||||
|
# "ldmk_norm": v_ldmk_norm, "ldmk_auxs":v_ldmk_auxs
|
||||||
|
"ldmk": v_ldmk,
|
||||||
|
})
|
||||||
|
n_videos += 1
|
||||||
|
|
||||||
|
# add to annodb
|
||||||
|
annodb[pid] = list_dict
|
||||||
|
|
||||||
|
# pickle and save
|
||||||
|
with open(str(path_anno), "wb") as f:
|
||||||
|
pickle.dump(annodb, f)
|
||||||
|
|
||||||
|
print(f"Total have {n_video} video items, save to --> {path_anno}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Expression")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
# from common.animation import save_animation, save_animation_with_gt
|
||||||
|
|
||||||
|
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/GRID/processing')
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=True)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each speaker
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
if id_name not in total_pid: continue
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
|
||||||
|
ipath_ldmk = ipath_data.joinpath("landmk-PFLD")
|
||||||
|
ipath_save_feat = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
|
||||||
|
if ipath_save_feat.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load landmark
|
||||||
|
feat_ldmk = []
|
||||||
|
prev_ldmk = None
|
||||||
|
nContinue = 0
|
||||||
|
for j in range(75):
|
||||||
|
jpath_ldmk = ipath_ldmk.joinpath(f"frame-{j:04d}.txt")
|
||||||
|
|
||||||
|
if not jpath_ldmk.exists():
|
||||||
|
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk)
|
||||||
|
if nContinue <= 2:
|
||||||
|
data_ldmk = prev_ldmk
|
||||||
|
nContinue += 1
|
||||||
|
else:
|
||||||
|
nContinue += 1
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_ldmk = np.loadtxt(jpath_ldmk).astype(np.float)
|
||||||
|
data_ldmk, _, _ = landmark_normalize(data_ldmk) # normalize
|
||||||
|
|
||||||
|
prev_ldmk = data_ldmk
|
||||||
|
nContinue = 0
|
||||||
|
|
||||||
|
feat_ldmk.append(data_ldmk)
|
||||||
|
|
||||||
|
# save
|
||||||
|
feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
|
||||||
|
|
||||||
|
if nContinue <= 2 and feat_ldmk.shape[0] == 75:
|
||||||
|
np.save(ipath_save_feat, feat_ldmk)
|
||||||
|
print(f"feat shape = {feat_ldmk.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
|
||||||
|
# save to animation
|
||||||
|
else:
|
||||||
|
print(f"ERROR: some landmark missing or length not same, length = {feat_ldmk.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib2 import Path
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/GRID/processing/s1')
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
|
||||||
|
path_audio_wav = Path("data/paper_GRID_gt/audio_wav")
|
||||||
|
path_ldmk_25fps = Path("data/paper_GRID_gt/ldmk_25fps")
|
||||||
|
path_audio_feat = Path("data/paper_GRID_gt/feat_mel_no_align")
|
||||||
|
path_video_25fps = Path("data/paper_GRID_gt/video_25fps")
|
||||||
|
|
||||||
|
path_audio_wav.mkdir(parents=True, exist_ok=True)
|
||||||
|
path_ldmk_25fps.mkdir(parents=True, exist_ok=True)
|
||||||
|
path_video_25fps.mkdir(parents=True, exist_ok=True)
|
||||||
|
path_audio_feat.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
ncount = 0
|
||||||
|
for i, ipath in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ipath_data = ipath.parent.parent
|
||||||
|
print(f"ipath_data = {ipath_data}")
|
||||||
|
|
||||||
|
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
|
||||||
|
ipath_ldmks = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
ipath_video = ipath_data.joinpath("video/video_orignal.mp4")
|
||||||
|
ipath_audio_feat = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
|
||||||
|
|
||||||
|
# skip if not exsits
|
||||||
|
if not ipath_ldmks.exists(): continue
|
||||||
|
if not ipath_audio.exists(): continue
|
||||||
|
if not ipath_video.exists(): continue
|
||||||
|
|
||||||
|
|
||||||
|
# copy to
|
||||||
|
# ipath_audio_target = path_audio_wav.joinpath(f"clips_{ncount:03d}.wav")
|
||||||
|
# shutil.copy(src=str(ipath_audio), dst=str(ipath_audio_target))
|
||||||
|
# print(f"copy {ipath_audio} --> {ipath_audio_target}")
|
||||||
|
|
||||||
|
# ipath_ldmks_target = path_ldmk_25fps.joinpath(f"clips_{ncount:03d}.npy")
|
||||||
|
# shutil.copy(src=str(ipath_ldmks), dst=str(ipath_ldmks_target))
|
||||||
|
# print(f"copy {ipath_ldmks} --> {ipath_ldmks_target}")
|
||||||
|
|
||||||
|
# ipath_video_target = path_video_25fps.joinpath(f"clips_{ncount:03d}.mp4")
|
||||||
|
# shutil.copy(src=str(ipath_video), dst=str(ipath_video_target))
|
||||||
|
# print(f"copy {ipath_video} --> {ipath_video_target}")
|
||||||
|
|
||||||
|
ipath_audio_feat_tgt = path_audio_feat.joinpath(f"clips_{ncount:03d}.npy")
|
||||||
|
shutil.copy(src=str(ipath_audio_feat), dst=str(ipath_audio_feat_tgt))
|
||||||
|
print(f"copy {ipath_audio_feat} --> {ipath_audio_feat_tgt}")
|
||||||
|
|
||||||
|
|
||||||
|
ncount += 1
|
||||||
|
if ncount >= 100: break
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import os
|
||||||
|
import cv2
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
# UNZIP_FILES = False
|
||||||
|
MV_VIDEO_FILES = False
|
||||||
|
# RESAMPLE_FPS = True
|
||||||
|
# RESAMPLE_RATE = False
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
path_root = Path("/mnt/data2/DATA/LRW/")
|
||||||
|
|
||||||
|
|
||||||
|
if MV_VIDEO_FILES:
|
||||||
|
path_data = path_root.joinpath("lipread_mp4")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_root.joinpath("lipread_mp4", id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("**/*.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_videos in v_dir_videos:
|
||||||
|
ivideo_name = ipath_videos.stem
|
||||||
|
itrain_test = ipath_videos.parent.name
|
||||||
|
|
||||||
|
# copy video
|
||||||
|
ipath_video_target = path_root.joinpath("processing", id_name, itrain_test, ivideo_name, "video/video_orignal.mp4")
|
||||||
|
|
||||||
|
if not ipath_video_target.exists():
|
||||||
|
ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
|
||||||
|
|
||||||
|
#print(f"copy {ipath_videos} --> {ipath_video_target}")
|
||||||
|
|
||||||
|
# copy audio
|
||||||
|
ipath_audio_source = path_root.joinpath("lipread_wav", id_name, itrain_test, ivideo_name+".wav")
|
||||||
|
ipath_audio_target = path_root.joinpath("processing", id_name, itrain_test, ivideo_name, "audio/audio_orignal.wav")
|
||||||
|
|
||||||
|
if not ipath_audio_target.exists():
|
||||||
|
ipath_audio_target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy(src=str(ipath_audio_source), dst=str(ipath_audio_target))
|
||||||
|
|
||||||
|
#print(f"copy {ipath_audio_source} --> {ipath_audio_target}")
|
||||||
|
|
||||||
|
|
||||||
|
# if RESAMPLE_FPS:
|
||||||
|
# path_data = path_root.joinpath("processing")
|
||||||
|
|
||||||
|
# v_ids = sorted(path_data.glob("*"))
|
||||||
|
# print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
|
||||||
|
|
||||||
|
# # for each word
|
||||||
|
# for i, ipath_id in enumerate(v_ids):
|
||||||
|
# id_name = ipath_id.stem
|
||||||
|
|
||||||
|
# dir_video = path_data.joinpath(id_name)
|
||||||
|
# v_dir_videos = sorted(dir_video.glob("**/*.mp4"))
|
||||||
|
|
||||||
|
# print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
# # for each video
|
||||||
|
# for ipath_videos in v_dir_videos:
|
||||||
|
# ivideo_name = ipath_videos.stem
|
||||||
|
# itrain_test = ipath_videos.parent.name
|
||||||
|
|
||||||
|
# # copy video
|
||||||
|
# ipath_video_target = ipath_videos.parent.joinpath("video_25fps.mp4")
|
||||||
|
|
||||||
|
# cap = cv2.VideoCapture(str(ipath_videos))
|
||||||
|
# nframe = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
# nfps = int(cap.get(cv2.CAP_PROP_FPS))
|
||||||
|
# w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||||
|
|
||||||
|
# print(f"FPS = {nfps}, length = {nframe}, (w,h)=({w}, {h})")
|
||||||
|
|
||||||
|
# if not ipath_video_target.exists():
|
||||||
|
# #ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
# #shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
|
||||||
|
# pass
|
||||||
|
# #print(f"convert {ipath_videos} --> {ipath_video_target}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import cv2
|
||||||
|
import os, sys
|
||||||
|
import glob
|
||||||
|
import numpy as np
|
||||||
|
import time
|
||||||
|
import pdb
|
||||||
|
import argparse
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/processing")
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=True)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("**/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ivideo_name = ipath_video.stem
|
||||||
|
itrain_test = ipath_video.parent.name
|
||||||
|
|
||||||
|
# create data path
|
||||||
|
path_save_frames = ipath_video.parent.parent.joinpath("frames")
|
||||||
|
|
||||||
|
# if already exists frames
|
||||||
|
if path_save_frames.exists():
|
||||||
|
if len(list(path_save_frames.glob("*.jpg"))) > 20:
|
||||||
|
continue
|
||||||
|
|
||||||
|
path_save_frames.mkdir(parents=True, exist_ok=True)
|
||||||
|
#print("save frames dir = ", {path_save_frames})
|
||||||
|
|
||||||
|
# STEP1: extract frames
|
||||||
|
count = 0
|
||||||
|
cap = cv2.VideoCapture(str(ipath_video))
|
||||||
|
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
success, image = cap.read()
|
||||||
|
if not success:
|
||||||
|
break
|
||||||
|
|
||||||
|
ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}.jpg")
|
||||||
|
|
||||||
|
if not ipath_frame.exists():
|
||||||
|
cv2.imwrite(str(ipath_frame), image)
|
||||||
|
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> Extract {iv}-th video, have {length} frames, {ipath_video}")
|
||||||
|
#print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
|
||||||
|
|
||||||
|
#break
|
||||||
|
#break
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
from pathlib2 import Path
|
||||||
|
from face_alignment import FaceAlignment, LandmarksType
|
||||||
|
|
||||||
|
|
||||||
|
def select_ldmk(ladmks):
|
||||||
|
|
||||||
|
ladmks = np.array(ladmks)
|
||||||
|
area = []
|
||||||
|
for i in range(ladmks.shape[0]):
|
||||||
|
lands = ladmks[i, ...]
|
||||||
|
|
||||||
|
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
|
||||||
|
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
|
||||||
|
area.append((xmax - xmin) * (ymax-ymin))
|
||||||
|
|
||||||
|
|
||||||
|
print("area = ", area, "select = ", np.argmax(area))
|
||||||
|
return ladmks[np.argmax(area), :, :]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/processing")
|
||||||
|
|
||||||
|
|
||||||
|
model = FaceAlignment(LandmarksType._2D, flip_input=False)
|
||||||
|
|
||||||
|
v_ids = sorted(path_data.glob("*"), reverse=False)
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
# if id_name not in ["ABUSE", "ACCESS", "ACCORDING", "ACCUSED", "ACROSS"]:
|
||||||
|
# continue
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("**/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for iv, ipath_video in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
#print(f"ipath_data = {ipath_data}")
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
ipath_landmk.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# STEP1: get frames
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
# STEP2: extract landmarks
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
if not ipath_landmk_frame.exists():
|
||||||
|
|
||||||
|
# detect image
|
||||||
|
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
|
||||||
|
|
||||||
|
ldmk_pred = model.get_landmarks(np.array(image))
|
||||||
|
if ldmk_pred is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# select the first one or the bigger one face
|
||||||
|
if len(ldmk_pred) > 1:
|
||||||
|
ldmk_pred = select_ldmk(ldmk_pred)
|
||||||
|
else:
|
||||||
|
ldmk_pred = ldmk_pred[0]
|
||||||
|
|
||||||
|
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
|
||||||
|
|
||||||
|
# break
|
||||||
|
# break
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import os
|
||||||
|
import glob
|
||||||
|
import pdb
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from scipy.io import loadmat,savemat
|
||||||
|
|
||||||
|
COMBINE_COEFF_RBGFACE = True
|
||||||
|
COMBINE_LAMDK_RBGFACE = False
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/LRW/processing")
|
||||||
|
|
||||||
|
|
||||||
|
#num_train_file = 3000
|
||||||
|
#num_train_count = 0
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
if (j+1) % 100 == 100: print(f"processing {j+1}/{len(v_dir_videos)}")
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
#print(f"jpath_data = {jpath_data}")
|
||||||
|
|
||||||
|
jpath_frames = jpath_data.joinpath("frames")
|
||||||
|
v_frames = sorted(jpath_frames.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
|
||||||
|
#print(f"contain {len(v_frames)} frames in {str(jpath_data)}")
|
||||||
|
|
||||||
|
#
|
||||||
|
if COMBINE_COEFF_RBGFACE:
|
||||||
|
jpath_coeff = jpath_data.joinpath("rgbface/coeff")
|
||||||
|
jpath_coeff_save = jpath_data.joinpath("video/coeff_rgbface2.npy")
|
||||||
|
jpath_coeff_save.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_coeff = sorted(jpath_coeff.glob("*.txt"))
|
||||||
|
#print(f"contain {len(v_coeff)} reconstruction/tans in {str(jpath_data)}")
|
||||||
|
|
||||||
|
if len(v_coeff) != len(v_frames):
|
||||||
|
print(f"\t ERROR && Continue: This video missing coeff{len(v_coeff)}/{len(v_frames)}, {str(jpath_coeff)} ")
|
||||||
|
continue
|
||||||
|
# elif jpath_coeff_save.exists():
|
||||||
|
# continue
|
||||||
|
else:
|
||||||
|
coeff_all = np.zeros((len(v_frames), 61), np.float32) # 55 + 3 + 3
|
||||||
|
|
||||||
|
for k, iframe in enumerate(v_frames):
|
||||||
|
fid = int(iframe.stem[-4:])
|
||||||
|
|
||||||
|
# load data
|
||||||
|
kpath_coeff = jpath_coeff.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
|
||||||
|
kk_coeff = np.loadtxt(str(kpath_coeff)).reshape(-1)
|
||||||
|
|
||||||
|
kk_coeff_expr = kk_coeff[100:155] # (55, ) , identity-100, expression-55 ==> (55, )
|
||||||
|
kk_coeff_rts = kk_coeff[155:161] # (6) , rotation-3, translation-3, scale-1 ==> (6, )
|
||||||
|
|
||||||
|
coeff_all[k, :] = np.r_[kk_coeff_expr, kk_coeff_rts] # (61, ) expression-55 + rotation-3 + trans-3
|
||||||
|
|
||||||
|
# save combine data
|
||||||
|
np.save(str(jpath_coeff_save), coeff_all)
|
||||||
|
#print(f"combine the coeff: {str(jpath_coeff)} --> {str(jpath_coeff_save)}")
|
||||||
|
|
||||||
|
# combine landmark of RGBFaceNet
|
||||||
|
if COMBINE_LAMDK_RBGFACE:
|
||||||
|
jpath_ladmk_proj = jpath_data.joinpath("rgbface/landmark_proj")
|
||||||
|
jpath_ladmk_crop = jpath_data.joinpath("rgbface/landmark_crop")
|
||||||
|
|
||||||
|
jpath_proj_save = jpath_data.joinpath("video/landmark_rgbface_proj.npy")
|
||||||
|
jpath_crop_save = jpath_data.joinpath("video/landmark_rgbface_crop.npy")
|
||||||
|
jpath_crop_save.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_ladmk_proj = sorted(jpath_ladmk_proj.glob("*.txt"))
|
||||||
|
v_ladmk_crop = sorted(jpath_ladmk_crop.glob("*.txt"))
|
||||||
|
|
||||||
|
#print(f"contain {len(v_ladmk_proj)} / {len(v_ladmk_crop)} landmark proj/crop in {str(jpath_data)}")
|
||||||
|
|
||||||
|
if len(v_ladmk_proj) != len(v_frames) or len(v_ladmk_crop) != len(v_frames):
|
||||||
|
print(f"\t ERROR && Continue: This video missing landmark, {str(jpath_ladmk_proj)} ")
|
||||||
|
continue
|
||||||
|
elif jpath_proj_save.exists() and jpath_crop_save.exists():
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
ladmk_proj_all = np.zeros((len(v_frames), 68, 2), np.float32)
|
||||||
|
ladmk_crop_all = np.zeros((len(v_frames), 68, 2), np.float32)
|
||||||
|
|
||||||
|
for k, iframe in enumerate(v_frames):
|
||||||
|
fid = int(iframe.stem[-4:])
|
||||||
|
|
||||||
|
# load data
|
||||||
|
kpath_proj = jpath_ladmk_proj.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
kpath_crop = jpath_ladmk_crop.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
|
||||||
|
ladmk_proj_all[k, :, :] = np.loadtxt(str(kpath_proj)) # (68, 2)
|
||||||
|
ladmk_crop_all[k, :, :] = np.loadtxt(str(kpath_crop)) # (68, 2)
|
||||||
|
|
||||||
|
# save combine data
|
||||||
|
np.save(str(jpath_proj_save), ladmk_proj_all)
|
||||||
|
np.save(str(jpath_crop_save), ladmk_crop_all)
|
||||||
|
|
||||||
|
#print(f"combine the coeff: {str(jpath_ladmk_proj)} --> {str(jpath_proj_save)}")
|
||||||
|
|
||||||
|
#break
|
||||||
|
#break
|
||||||
|
|
||||||
|
|
||||||
|
# combine 3dmm
|
||||||
|
|
||||||
|
#
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
|
||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from scipy.io import loadmat,savemat
|
||||||
|
|
||||||
|
COMBINE_COEFF_RBGFACE = True
|
||||||
|
COMBINE_LAMDK_RBGFACE = True
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data/DATA/LRW/processing")
|
||||||
|
|
||||||
|
|
||||||
|
#num_train_file = 3000
|
||||||
|
#num_train_count = 0
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
#print(f"jpath_data = {jpath_data}")
|
||||||
|
|
||||||
|
jpath_frames = jpath_data.joinpath("frames")
|
||||||
|
v_frames = sorted(jpath_frames.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
|
||||||
|
n_frames = len(v_frames)
|
||||||
|
#print(f"contain {len(v_frames)} frames in {str(jpath_data)}")
|
||||||
|
|
||||||
|
|
||||||
|
jpath_coeff = jpath_data.joinpath("reconstruction/coeff")
|
||||||
|
jpath_coeff_save = jpath_data.joinpath("video/coeff_reconstruction.npy")
|
||||||
|
jpath_coeff_save.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
n_coeff = len(list(jpath_coeff.glob("*.txt")))
|
||||||
|
#print(f"contain {len(v_coeff)} reconstruction/tans in {str(jpath_data)}")
|
||||||
|
|
||||||
|
if n_frames != n_coeff:
|
||||||
|
print(f"\t ERROR && Continue: This video missing coeff {n_coeff}/{n_frames}, {str(jpath_coeff)}")
|
||||||
|
continue
|
||||||
|
# elif jpath_coeff_save.exists():
|
||||||
|
# continue
|
||||||
|
else:
|
||||||
|
coeff_all = np.zeros((n_frames, 70), np.float32) # 80 identity + 64 expression + 80 texture + 3 rot + 27 light + 3 trans
|
||||||
|
for k, iframe in enumerate(v_frames):
|
||||||
|
fid = int(iframe.stem[-4:])
|
||||||
|
|
||||||
|
# load data
|
||||||
|
kpath_coeff = jpath_coeff.joinpath(f"frame-{fid:04d}.txt")
|
||||||
|
kk_coeff = np.loadtxt(str(kpath_coeff)).reshape(-1)
|
||||||
|
|
||||||
|
kk_coeff_exp = kk_coeff[ 80:144] # (64, ) , expression-64 ==> (55, )
|
||||||
|
kk_coeff_rot = kk_coeff[224:227] # (3, ), rotation-3,
|
||||||
|
kk_coeff_tra = kk_coeff[254:257] # (3, ), translation - 3
|
||||||
|
|
||||||
|
coeff_all[k, :] = np.r_[kk_coeff_exp, kk_coeff_rot, kk_coeff_tra] # (70, ) expression-55 + rotation-3 + trans-3
|
||||||
|
|
||||||
|
#print(f"coef shape={coeff_all.shape}, path = {kpath_coeff}")
|
||||||
|
# save combine data
|
||||||
|
np.save(str(jpath_coeff_save), coeff_all)
|
||||||
|
|
||||||
|
if j % 100 == 99:
|
||||||
|
print(f"processing {j+1}/{len(v_dir_videos)}, shape={coeff_all.shape} --> {str(jpath_coeff_save)}")
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from collections import OrderedDict
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
path_anno = Path("data/LRW/anno_LRW_test_full.pickle")
|
||||||
|
annodb = OrderedDict()
|
||||||
|
|
||||||
|
nvideo = 0
|
||||||
|
# nvideo_target = 5000
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_words = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
|
||||||
|
|
||||||
|
for i, ipath_wd in enumerate(vpath_words):
|
||||||
|
pid = ipath_wd.stem
|
||||||
|
# if nvideo > nvideo_target: break
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_wd.glob("test/*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files")
|
||||||
|
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
|
||||||
|
# if nvideo > nvideo_target: break
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
|
||||||
|
|
||||||
|
nframes = len(v_path_frames)
|
||||||
|
if not (nframes > 20 and nframes== len(v_path_ladmks)):
|
||||||
|
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> picking the {iv}-th video landmark: vid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
# frames --> read landmarks
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
dict_anno = {
|
||||||
|
"pid": pid,
|
||||||
|
"vid":vid,
|
||||||
|
# "ldmk": v_ldmk,
|
||||||
|
"ldmk_norm": v_ldmk_norm,
|
||||||
|
# "ldmk_auxs":v_ldmk_auxs
|
||||||
|
}
|
||||||
|
|
||||||
|
# count video numbers
|
||||||
|
nvideo += 1
|
||||||
|
annodb[vid] = dict_anno
|
||||||
|
|
||||||
|
# pickle and save
|
||||||
|
with open(str(path_anno), "wb") as f:
|
||||||
|
pickle.dump(annodb, f)
|
||||||
|
|
||||||
|
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
path_anno = Path("data/LRW/anno_train_full.pickle")
|
||||||
|
annodb = []
|
||||||
|
|
||||||
|
nvideo = 0
|
||||||
|
nvideo_target = 5000
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_words = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
|
||||||
|
|
||||||
|
for i, ipath_wd in enumerate(vpath_words):
|
||||||
|
pid = ipath_wd.stem
|
||||||
|
|
||||||
|
# if nvideo > nvideo_target: break
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
|
||||||
|
# if nvideo > nvideo_target: break
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
|
||||||
|
|
||||||
|
nframes = len(v_path_frames)
|
||||||
|
|
||||||
|
if not (nframes > 20 and nframes== len(v_path_ladmks)):
|
||||||
|
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
# frames --> read landmarks
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
dict_anno = {
|
||||||
|
"pid": pid,
|
||||||
|
"vid":vid,
|
||||||
|
# "ldmk": v_ldmk,
|
||||||
|
"ldmk_norm": v_ldmk_norm,
|
||||||
|
# "ldmk_auxs":v_ldmk_auxs
|
||||||
|
}
|
||||||
|
|
||||||
|
# count video numbers
|
||||||
|
nvideo += 1
|
||||||
|
annodb.append(dict_anno)
|
||||||
|
|
||||||
|
# pickle and save
|
||||||
|
with open(str(path_anno), "wb") as f:
|
||||||
|
pickle.dump(annodb, f)
|
||||||
|
|
||||||
|
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
|
||||||
|
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
path_anno = Path("data/LRW/anno_valid_full.pickle")
|
||||||
|
annodb = []
|
||||||
|
|
||||||
|
nvideo = 0
|
||||||
|
nvideo_target = 50000000
|
||||||
|
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_words = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
|
||||||
|
|
||||||
|
for i, ipath_wd in enumerate(vpath_words):
|
||||||
|
pid = ipath_wd.stem
|
||||||
|
|
||||||
|
# if nvideo > nvideo_target: break
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_wd.glob("val/*/video/video_orignal.mp4"))
|
||||||
|
if len(vpath_videos) <= 0: continue
|
||||||
|
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
|
||||||
|
# if nvideo > nvideo_target: break
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
|
||||||
|
|
||||||
|
nframes = len(v_path_frames)
|
||||||
|
|
||||||
|
if not (nframes > 20 and nframes== len(v_path_ladmks)):
|
||||||
|
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
# frames --> read landmarks
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
dict_anno = {
|
||||||
|
"pid": pid,
|
||||||
|
"vid":vid,
|
||||||
|
# "ldmk": v_ldmk,
|
||||||
|
"ldmk_norm": v_ldmk_norm,
|
||||||
|
# "ldmk_auxs":v_ldmk_auxs
|
||||||
|
}
|
||||||
|
|
||||||
|
# count video numbers
|
||||||
|
nvideo += 1
|
||||||
|
annodb.append(dict_anno)
|
||||||
|
|
||||||
|
# pickle and save
|
||||||
|
with open(str(path_anno), "wb") as f:
|
||||||
|
pickle.dump(annodb, f)
|
||||||
|
|
||||||
|
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
|
||||||
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
path_save = Path('data/LRW') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
nvideo = 0
|
||||||
|
nvideo_target = 1000
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_words = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
|
||||||
|
|
||||||
|
|
||||||
|
motion_test = []
|
||||||
|
speech_test = []
|
||||||
|
|
||||||
|
for i, ipath_wd in enumerate(vpath_words):
|
||||||
|
pid = ipath_wd.stem
|
||||||
|
if nvideo >= nvideo_target: break
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_wd.glob("test/*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
|
||||||
|
if len(vpath_videos) <= 0: continue
|
||||||
|
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
if nvideo >= nvideo_target: break
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
ipath_mfcc = ipath_data.joinpath("audio/feat_mfcc_align.npy")
|
||||||
|
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
|
||||||
|
|
||||||
|
if not ipath_mfcc.exists(): continue
|
||||||
|
# load speech
|
||||||
|
mfcc = np.load(ipath_mfcc) # 29 x 27
|
||||||
|
|
||||||
|
nframes = len(v_path_frames)
|
||||||
|
|
||||||
|
if not (nframes == 29 and len(v_path_ladmks) ==29 and mfcc.shape[0] == 29):
|
||||||
|
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks, {mfcc.shape[0]} mfcc")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
|
||||||
|
# frames --> read landmarks
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
|
||||||
|
motion_test.append(v_ldmk_norm) # (29, 68, 2)
|
||||||
|
speech_test.append(mfcc) # (29, 27)
|
||||||
|
|
||||||
|
# count video numbers
|
||||||
|
nvideo += 1
|
||||||
|
|
||||||
|
|
||||||
|
motion_test = np.array(motion_test) # (N, 29, 68, 2)
|
||||||
|
speech_test = np.array(speech_test) # (N, 29, 27)
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
|
||||||
|
print(f"save train data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
path_save = Path('data/LRW') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
nvideo = 0
|
||||||
|
nvideo_target = 100000
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_words = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
|
||||||
|
|
||||||
|
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
|
||||||
|
for i, ipath_wd in enumerate(vpath_words):
|
||||||
|
pid = ipath_wd.stem
|
||||||
|
if nvideo >= nvideo_target: break
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
|
||||||
|
if len(vpath_videos) <= 0: continue
|
||||||
|
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
if nvideo >= nvideo_target: break
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk = ipath_data.joinpath("landmk")
|
||||||
|
ipath_mfcc = ipath_data.joinpath("audio/feat_mfcc_align.npy")
|
||||||
|
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
|
||||||
|
|
||||||
|
if not ipath_mfcc.exists(): continue
|
||||||
|
# load speech
|
||||||
|
mfcc = np.load(ipath_mfcc) # 29 x 27
|
||||||
|
|
||||||
|
nframes = len(v_path_frames)
|
||||||
|
|
||||||
|
if not (nframes == 29 and len(v_path_ladmks) ==29 and mfcc.shape[0] == 29):
|
||||||
|
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks, {mfcc.shape[0]} mfcc")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
|
||||||
|
# frames --> read landmarks
|
||||||
|
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
|
||||||
|
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
|
||||||
|
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
|
||||||
|
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
|
||||||
|
|
||||||
|
v_ldmk[k, :, :] = ldmk
|
||||||
|
v_ldmk_norm[k, :, :] = ldmk_norm
|
||||||
|
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
|
||||||
|
|
||||||
|
|
||||||
|
motion_train.append(v_ldmk_norm) # (29, 68, 2)
|
||||||
|
speech_train.append(mfcc) # (29, 27)
|
||||||
|
|
||||||
|
# count video numbers
|
||||||
|
nvideo += 1
|
||||||
|
|
||||||
|
|
||||||
|
motion_train = np.array(motion_train) # (N, 29, 68, 2)
|
||||||
|
speech_train = np.array(speech_train) # (N, 29, 27)
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
import librosa
|
||||||
|
import python_speech_features
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import multiprocessing
|
||||||
|
|
||||||
|
|
||||||
|
def splited_by_windows(data, wind_stride, wind_length, padding=True):
|
||||||
|
"""
|
||||||
|
data: seq_len1 x dim1
|
||||||
|
return: seq_len2 x wind_length x dim1
|
||||||
|
where seq_len2 = (L + 2p - k) // wind_stride + 1
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
seq_len1, dim1 = data.shape
|
||||||
|
|
||||||
|
seq_len2 = seq_len1 // wind_stride + 1
|
||||||
|
|
||||||
|
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
|
||||||
|
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
|
||||||
|
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
|
||||||
|
|
||||||
|
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
|
||||||
|
|
||||||
|
for i in range(seq_len2):
|
||||||
|
ibeg = i * wind_stride
|
||||||
|
iend = i * wind_stride + wind_length
|
||||||
|
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
|
||||||
|
|
||||||
|
return data_output
|
||||||
|
|
||||||
|
|
||||||
|
# def func_processing(path_audio):
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
|
||||||
|
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
jpath_frame = jpath_data.joinpath("frames")
|
||||||
|
nframes = len(sorted(jpath_frame.glob("*.jpg")))
|
||||||
|
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
|
||||||
|
|
||||||
|
|
||||||
|
ipath_audio = jpath_data.joinpath("audio/audio_orignal.wav")
|
||||||
|
ipath_feat_save = jpath_data.joinpath("audio/mfcc_feat.npy")
|
||||||
|
ipath_feat_orignal_save = jpath_data.joinpath("audio/mfcc_feat_orignal.npy")
|
||||||
|
|
||||||
|
# for some data not have .wav files
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"NOT EXISTING: {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ipath_feat_orignal_save.exists():
|
||||||
|
print(f"EXSTING, {ipath_feat_orignal_save}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# extarct mfcc feature
|
||||||
|
audio, sr = librosa.load(str(ipath_audio), sr=16000) # (69760, )
|
||||||
|
mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
|
||||||
|
|
||||||
|
#duration = len(audio) / sr
|
||||||
|
#print(f"audio shape={audio.shape}, mfcc shape={mfcc_orig.shape}, duration={duration}")
|
||||||
|
|
||||||
|
# splited by windows (to fit video frame with fps 25)
|
||||||
|
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
|
||||||
|
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
|
||||||
|
# seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
|
||||||
|
mfcc = splited_by_windows(mfcc_orig, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
|
||||||
|
#print(f"MFCC input size (splited by windows) ={mfcc.shape}")
|
||||||
|
|
||||||
|
# save files
|
||||||
|
np.save(str(ipath_feat_orignal_save), mfcc_orig)
|
||||||
|
# np.save(str(ipath_feat_save), mfcc)
|
||||||
|
# print(f"SAVE: mfcc size={mfcc.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
|
||||||
|
# print(f"SAVE: mfcc size={mfcc_orig.shape} --> {str(ipath_feat_orignal_save)}") # mfcc size=(31, 28, 12)
|
||||||
|
|
||||||
|
#break
|
||||||
|
#break
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
import moviepy
|
||||||
|
from moviepy.editor import VideoFileClip, AudioFileClip
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
|
||||||
|
# for each word
|
||||||
|
v_ids = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
|
||||||
|
|
||||||
|
for i, ipath_id in enumerate(v_ids):
|
||||||
|
id_name = ipath_id.stem
|
||||||
|
|
||||||
|
dir_video = path_data.joinpath(id_name)
|
||||||
|
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for j, jpath_videos in enumerate(v_dir_videos):
|
||||||
|
|
||||||
|
if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
|
||||||
|
|
||||||
|
jpath_data = jpath_videos.parent.parent
|
||||||
|
jpath_frame = jpath_data.joinpath("frames")
|
||||||
|
nframes = len(sorted(jpath_frame.glob("*.jpg")))
|
||||||
|
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
|
||||||
|
|
||||||
|
ipath_video = jpath_data.joinpath("video/video_orignal.mp4")
|
||||||
|
ipath_audio = jpath_data.joinpath("audio/audio_orignal.wav")
|
||||||
|
ipath_save_feat = jpath_data.joinpath("audio/feat_mfcc_align.npy")
|
||||||
|
|
||||||
|
|
||||||
|
video = VideoFileClip(str(ipath_video))
|
||||||
|
# print(f"\nvideo duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||||
|
|
||||||
|
audio = AudioFileClip(str(ipath_audio))
|
||||||
|
# print(f"audio duration = {audio.duration}, fps = {audio.fps}, (start, end)=({audio.start},{audio.end}), nframes={int(audio.duration * audio.fps)}")
|
||||||
|
|
||||||
|
# for some data not have .wav files
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"NOT EXISTING: {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ipath_save_feat.exists():
|
||||||
|
print(f"EXSTING, {ipath_save_feat}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
fps = video.fps
|
||||||
|
|
||||||
|
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 550 让这个sr是fps的整数,
|
||||||
|
hop_len = int(sr / fps) # 640
|
||||||
|
n_fft = int(sr * 0.1) # default 2048
|
||||||
|
# print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
|
||||||
|
|
||||||
|
mfcc = librosa.feature.mfcc(y=data, sr=sr,
|
||||||
|
n_fft=n_fft, # FFT窗口的长度
|
||||||
|
hop_length=hop_len, # 帧移
|
||||||
|
win_length=n_fft, # 窗口长度,默认=n_fft
|
||||||
|
window="hann", # 加hanming窗
|
||||||
|
n_mfcc=27,
|
||||||
|
fmin=0.0, fmax=8000)
|
||||||
|
# mfcc = np.log(mfcc+1).T
|
||||||
|
mfcc = mfcc.T
|
||||||
|
# print(f"sr={sr}, data ={data.shape}, mfcc = {mfcc.shape}, (min,max)=({np.min(mfcc), np.max(mfcc)}")
|
||||||
|
|
||||||
|
|
||||||
|
if mfcc.shape[0] < nframes:
|
||||||
|
print(f"\nERROR:")
|
||||||
|
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||||
|
print(f"audio duration = {audio.duration}, fps = {audio.fps}, (start, end)=({audio.start},{audio.end}), nframes={int(audio.duration * audio.fps)}")
|
||||||
|
print(f"sr={sr}, data ={data.shape}, mfcc = {mfcc.shape}, (min,max)=({np.min(mfcc), np.max(mfcc)}")
|
||||||
|
print(f"mfcc length(={mfcc.shape[0]}) can not < nframe {nframes} ")
|
||||||
|
continue
|
||||||
|
|
||||||
|
else:
|
||||||
|
# save
|
||||||
|
mfcc_align = mfcc[:nframes, :]
|
||||||
|
np.save(str(ipath_save_feat), mfcc_align)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# # extarct mfcc feature
|
||||||
|
# audio, sr = librosa.load(str(ipath_audio), sr=16000) # (69760, )
|
||||||
|
# mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
|
||||||
|
|
||||||
|
# #duration = len(audio) / sr
|
||||||
|
# #print(f"audio shape={audio.shape}, mfcc shape={mfcc_orig.shape}, duration={duration}")
|
||||||
|
|
||||||
|
# # splited by windows (to fit video frame with fps 25)
|
||||||
|
# wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
|
||||||
|
# wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
|
||||||
|
# # seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
|
||||||
|
# mfcc = splited_by_windows(mfcc_orig, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
|
||||||
|
# #print(f"MFCC input size (splited by windows) ={mfcc.shape}")
|
||||||
|
|
||||||
|
# save files
|
||||||
|
# np.save(str(ipath_feat_orignal_save), mfcc_orig)
|
||||||
|
# np.save(str(ipath_feat_save), mfcc)
|
||||||
|
# print(f"SAVE: mfcc size={mfcc.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
|
||||||
|
# print(f"SAVE: mfcc size={mfcc_orig.shape} --> {str(ipath_feat_orignal_save)}") # mfcc size=(31, 28, 12)
|
||||||
|
|
||||||
|
#break
|
||||||
|
#break
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
from common.animation import save_animation, save_animation_with_gt
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path("/mnt/data2/DATA/LRW/processing")
|
||||||
|
path_save = Path('data/LRW') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
nvideo = 0
|
||||||
|
nvideo_target = 100000
|
||||||
|
|
||||||
|
# if not existing
|
||||||
|
vpath_words = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
|
||||||
|
|
||||||
|
|
||||||
|
for i, ipath_wd in enumerate(vpath_words):
|
||||||
|
pid = ipath_wd.stem
|
||||||
|
if nvideo >= nvideo_target: break
|
||||||
|
|
||||||
|
# video
|
||||||
|
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
|
||||||
|
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
|
||||||
|
if len(vpath_videos) <= 0: continue
|
||||||
|
|
||||||
|
for iv, ipath_video in enumerate(vpath_videos):
|
||||||
|
if nvideo >= nvideo_target: break
|
||||||
|
|
||||||
|
ipath_data = ipath_video.parent.parent
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
ipath_frames = ipath_data.joinpath("frames")
|
||||||
|
ipath_landmk_dlib = ipath_data.joinpath("landmk")
|
||||||
|
ipath_landmk_pfld = ipath_data.joinpath("landmk-PFLD")
|
||||||
|
|
||||||
|
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
|
||||||
|
v_path_ladmks_dlib = sorted(ipath_landmk_dlib.glob("*.txt"))
|
||||||
|
v_path_ladmks_pfld = sorted(ipath_landmk_pfld.glob("*.txt"))
|
||||||
|
|
||||||
|
|
||||||
|
nframes = len(v_path_frames)
|
||||||
|
if not (nframes == 29 and len(v_path_ladmks_dlib) ==29 and len(v_path_ladmks_pfld) ==29):
|
||||||
|
print(f"have {nframes} frames, and {len(v_path_ladmks_dlib)} / {len(v_path_ladmks_pfld)} landmarks, ")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if iv % 50 == 0:
|
||||||
|
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
|
||||||
|
|
||||||
|
|
||||||
|
# frames --> read landmarks
|
||||||
|
vldmk_dlib = np.zeros((1, nframes, 68, 2), dtype=float)
|
||||||
|
vldmk_pfld = np.zeros((1, nframes, 68, 2), dtype=float)
|
||||||
|
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
|
||||||
|
kpath_landmk_dlib = ipath_landmk_dlib.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
kpath_landmk_pfld = ipath_landmk_pfld.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
ldmk_dlib = np.loadtxt(kpath_landmk_dlib) # shape = (68, 2)
|
||||||
|
ldmk_dlib, _, _ = landmark_normalize(ldmk_dlib)
|
||||||
|
vldmk_dlib[0, k, :, :] = ldmk_dlib
|
||||||
|
|
||||||
|
ldmk_pfld = np.loadtxt(kpath_landmk_pfld) # shape = (68, 2)
|
||||||
|
ldmk_pfld, _, _ = landmark_normalize(ldmk_pfld)
|
||||||
|
vldmk_pfld[0, k, :, :] = ldmk_pfld
|
||||||
|
|
||||||
|
|
||||||
|
# show annotation
|
||||||
|
save_animation_with_gt(vldmk_dlib, vldmk_pfld,
|
||||||
|
path_save=Path(ipath_data),
|
||||||
|
suffix=f'DLIB_PLDF',
|
||||||
|
w=256, h=256, dpi=100)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
vid = "Celebrating-Independence-Day"
|
||||||
|
path_motion = path_data.joinpath(vid, "audio/feat_ldmk_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
data_motion = np.load(path_motion) # (N, 68, 2)
|
||||||
|
|
||||||
|
print(f"data_motion={data_motion.shape}, mean = {data_motion.mean((0,1))}, min={data_motion.min((0,1))}, max={data_motion.max((0,1))}")
|
||||||
|
|
||||||
|
|
||||||
|
# get rect
|
||||||
|
min_data = data_motion.min(axis=1) # (N, 2)
|
||||||
|
max_data = data_motion.max(axis=1) # (N, 2)
|
||||||
|
print(f"min_x={min_data.shape}, max_y={max_data.shape}")
|
||||||
|
|
||||||
|
# get mean rect
|
||||||
|
|
||||||
|
min_x, min_y = min_data.mean(axis=0) # (2, )
|
||||||
|
max_x, max_y = max_data.mean(axis=0)
|
||||||
|
|
||||||
|
print(f"RECT = ({min_x}, {min_y}, {max_x}, {max_y}), size=({max_x - min_x}, {max_y - min_y})")
|
||||||
|
# RECT = (696.6033078880407, 276.86030534351147, 1056.871755725191, 667.1918575063613), size=(360.26844783715023, 390.33155216284985)
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
# *****************************************************************************
|
||||||
|
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
||||||
|
#
|
||||||
|
# Redistribution and use in source and binary forms, with or without
|
||||||
|
# modification, are permitted provided that the following conditions are met:
|
||||||
|
# * Redistributions of source code must retain the above copyright
|
||||||
|
# notice, this list of conditions and the following disclaimer.
|
||||||
|
# * Redistributions in binary form must reproduce the above copyright
|
||||||
|
# notice, this list of conditions and the following disclaimer in the
|
||||||
|
# documentation and/or other materials provided with the distribution.
|
||||||
|
# * Neither the name of the NVIDIA CORPORATION nor the
|
||||||
|
# names of its contributors may be used to endorse or promote products
|
||||||
|
# derived from this software without specific prior written permission.
|
||||||
|
#
|
||||||
|
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
|
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
|
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
|
||||||
|
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
|
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||||
|
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||||
|
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
|
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
#
|
||||||
|
# *****************************************************************************\
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import torch
|
||||||
|
import torch.utils.data
|
||||||
|
import sys
|
||||||
|
from scipy.io.wavfile import read
|
||||||
|
|
||||||
|
# We're using the audio processing from TacoTron2 to make sure it matches
|
||||||
|
sys.path.insert(0, 'tacotron2')
|
||||||
|
from tacotron2.layers import TacotronSTFT
|
||||||
|
|
||||||
|
MAX_WAV_VALUE = 32768.0
|
||||||
|
|
||||||
|
def files_to_list(filename):
|
||||||
|
"""
|
||||||
|
Takes a text file of filenames and makes a list of filenames
|
||||||
|
"""
|
||||||
|
with open(filename, encoding='utf-8') as f:
|
||||||
|
files = f.readlines()
|
||||||
|
|
||||||
|
files = [f.rstrip() for f in files]
|
||||||
|
return files
|
||||||
|
|
||||||
|
def load_wav_to_torch(full_path):
|
||||||
|
"""
|
||||||
|
Loads wavdata into torch array
|
||||||
|
"""
|
||||||
|
sampling_rate, data = read(full_path)
|
||||||
|
return torch.from_numpy(data).float(), sampling_rate
|
||||||
|
|
||||||
|
|
||||||
|
class Mel2Samp(torch.utils.data.Dataset):
|
||||||
|
"""
|
||||||
|
This is the main class that calculates the spectrogram and returns the
|
||||||
|
spectrogram, audio pair.
|
||||||
|
"""
|
||||||
|
def __init__(self, training_files, segment_length, filter_length,
|
||||||
|
hop_length, win_length, sampling_rate, mel_fmin, mel_fmax):
|
||||||
|
self.audio_files = files_to_list(training_files)
|
||||||
|
random.seed(1234)
|
||||||
|
random.shuffle(self.audio_files)
|
||||||
|
self.stft = TacotronSTFT(filter_length=filter_length,
|
||||||
|
hop_length=hop_length,
|
||||||
|
win_length=win_length,
|
||||||
|
sampling_rate=sampling_rate,
|
||||||
|
mel_fmin=mel_fmin, mel_fmax=mel_fmax)
|
||||||
|
self.segment_length = segment_length
|
||||||
|
self.sampling_rate = sampling_rate
|
||||||
|
|
||||||
|
def get_mel(self, audio):
|
||||||
|
audio_norm = audio / MAX_WAV_VALUE
|
||||||
|
audio_norm = audio_norm.unsqueeze(0)
|
||||||
|
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
|
||||||
|
melspec = self.stft.mel_spectrogram(audio_norm)
|
||||||
|
melspec = torch.squeeze(melspec, 0)
|
||||||
|
return melspec
|
||||||
|
|
||||||
|
def __getitem__(self, index):
|
||||||
|
# Read audio
|
||||||
|
filename = self.audio_files[index]
|
||||||
|
audio, sampling_rate = load_wav_to_torch(filename)
|
||||||
|
if sampling_rate != self.sampling_rate:
|
||||||
|
raise ValueError("{} SR doesn't match target {} SR".format(
|
||||||
|
sampling_rate, self.sampling_rate))
|
||||||
|
|
||||||
|
# Take segment
|
||||||
|
if audio.size(0) >= self.segment_length:
|
||||||
|
max_audio_start = audio.size(0) - self.segment_length
|
||||||
|
audio_start = random.randint(0, max_audio_start)
|
||||||
|
audio = audio[audio_start:audio_start+self.segment_length]
|
||||||
|
else:
|
||||||
|
audio = torch.nn.functional.pad(audio, (0, self.segment_length - audio.size(0)), 'constant').data
|
||||||
|
|
||||||
|
mel = self.get_mel(audio)
|
||||||
|
audio = audio / MAX_WAV_VALUE
|
||||||
|
|
||||||
|
return (mel, audio)
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.audio_files)
|
||||||
|
|
||||||
|
# ===================================================================
|
||||||
|
# Takes directory of clean audio and makes directory of spectrograms
|
||||||
|
# Useful for making test sets
|
||||||
|
# ===================================================================
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Get defaults so it can work with no Sacred
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument('-f', "--filelist_path", required=True)
|
||||||
|
parser.add_argument('-c', '--config', type=str,
|
||||||
|
help='JSON file for configuration')
|
||||||
|
parser.add_argument('-o', '--output_dir', type=str,
|
||||||
|
help='Output directory')
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
with open(args.config) as f:
|
||||||
|
data = f.read()
|
||||||
|
data_config = json.loads(data)["data_config"]
|
||||||
|
mel2samp = Mel2Samp(**data_config)
|
||||||
|
|
||||||
|
filepaths = files_to_list(args.filelist_path)
|
||||||
|
|
||||||
|
# Make directory if it doesn't exist
|
||||||
|
if not os.path.isdir(args.output_dir):
|
||||||
|
os.makedirs(args.output_dir)
|
||||||
|
os.chmod(args.output_dir, 0o775)
|
||||||
|
|
||||||
|
for filepath in filepaths:
|
||||||
|
audio, sr = load_wav_to_torch(filepath)
|
||||||
|
melspectrogram = mel2samp.get_mel(audio)
|
||||||
|
filename = os.path.basename(filepath)
|
||||||
|
new_filepath = args.output_dir + '/' + filename + '.pt'
|
||||||
|
print(new_filepath)
|
||||||
|
torch.save(melspectrogram, new_filepath)
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
# path_save = Path('data/obama-landmark-mel') # obama-landmark-mel
|
||||||
|
path_save = Path('data/obama-landmark-mfcc') # obama-landmark-mel
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
data_train, data_valid, data_test = {}, {}, {}
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
ipath_speech = ipath_data.joinpath("audio/mfcc_feat.npy")
|
||||||
|
|
||||||
|
# ipath_motion = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
# ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
# check existing
|
||||||
|
if not ipath_motion.exists() or not ipath_speech.exists() or not ipath_info.exists():
|
||||||
|
msg = "ERROR: NOT exsiting "
|
||||||
|
if not ipath_info.exists():
|
||||||
|
msg += f"\n\t {ipath_info} "
|
||||||
|
if not ipath_motion.exists():
|
||||||
|
msg += f"\n {ipath_motion} "
|
||||||
|
if not ipath_speech.exists():
|
||||||
|
msg += f"\n\t {ipath_speech} "
|
||||||
|
|
||||||
|
print(msg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load data
|
||||||
|
data_motion = np.load(ipath_motion)#.reshape(-1, 136) # (N, 136)
|
||||||
|
data_speech = np.load(ipath_speech) # (M, 80)
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
# assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
data_train[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech
|
||||||
|
}
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
data_valid[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech
|
||||||
|
}
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_test[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
|
||||||
|
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
|
||||||
|
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
|
||||||
|
print(f"save data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)}) --> {path_save}")
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-landmark-mel-pose') # obama-landmark-mel
|
||||||
|
# path_save = Path('data/obama-3dmm-mel') # obama-landmark-mel
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
data_train, data_valid, data_test = {}, {}, {}
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
# ipath_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
# ipath_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
|
||||||
|
ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
|
||||||
|
|
||||||
|
if not ipath_speech.exists() or not ipath_pos.exists() or not ipath_motion.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_speech} or {ipath_pos} or {ipath_motion}" )
|
||||||
|
continue
|
||||||
|
|
||||||
|
# check existing
|
||||||
|
if not ipath_speech.exists() or not ipath_info.exists():
|
||||||
|
msg = "ERROR: NOT exsiting "
|
||||||
|
if not ipath_info.exists():
|
||||||
|
msg += f"\n\t {ipath_info} "
|
||||||
|
if not ipath_speech.exists():
|
||||||
|
msg += f"\n\t {ipath_speech} "
|
||||||
|
|
||||||
|
print(msg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load data
|
||||||
|
# feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
|
||||||
|
# feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
|
||||||
|
data_pose = np.load(ipath_pos) # (nframe_trim, 6) # (N, 6)
|
||||||
|
# data_motion = np.concatenate([feat_idn, feat_exp, feat_pos], axis=1) # (N, 156)
|
||||||
|
|
||||||
|
|
||||||
|
data_motion = np.load(ipath_motion).reshape(-1, 136) # (N, 136)
|
||||||
|
data_speech = np.load(ipath_speech) # (M, 80)
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
# assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
data_train[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech,
|
||||||
|
"data_pose": data_pose
|
||||||
|
}
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
data_valid[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech,
|
||||||
|
"data_pose": data_pose
|
||||||
|
}
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_test[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech,
|
||||||
|
"data_pose": data_pose
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
|
||||||
|
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
|
||||||
|
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
|
||||||
|
print(f"save data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)}) --> {path_save}")
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
from scipy import interpolate
|
||||||
|
|
||||||
|
|
||||||
|
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
|
||||||
|
"""y, N x 136, with 30fps
|
||||||
|
"""
|
||||||
|
|
||||||
|
nsteps = y.shape[0]
|
||||||
|
x = np.arange(0, nsteps, 1)
|
||||||
|
# print("x:", x[::30], x[-10:])
|
||||||
|
func = interpolate.interp1d(x, y=y, axis=0)
|
||||||
|
|
||||||
|
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
|
||||||
|
# print("x_new", x_new[::30], x_new[-10:])
|
||||||
|
y_new = func(x_new)
|
||||||
|
|
||||||
|
if source_fps < target_fps:
|
||||||
|
y_new = np.concatenate([y_new, y[-1:]])
|
||||||
|
|
||||||
|
return y_new
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
# path_save = Path('data/obama-landmark-mel') # obama-landmark-mel
|
||||||
|
path_save = Path('data/obama-landmark-mfcc') # obama-landmark-mel
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
data_train, data_valid, data_test = {}, {}, {}
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
ipath_speech = ipath_data.joinpath("video/mfcc_feat.npy")
|
||||||
|
|
||||||
|
# ipath_motion = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
# ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
|
||||||
|
|
||||||
|
# check existing
|
||||||
|
if not ipath_motion.exists() or not ipath_speech.exists() or not ipath_info.exists():
|
||||||
|
msg = "ERROR: NOT exsiting "
|
||||||
|
if not ipath_info.exists():
|
||||||
|
msg += f"\n\t {ipath_info} "
|
||||||
|
if not ipath_motion.exists():
|
||||||
|
msg += f"\n {ipath_motion} "
|
||||||
|
if not ipath_speech.exists():
|
||||||
|
msg += f"\n\t {ipath_speech} "
|
||||||
|
|
||||||
|
print(msg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
fps = info["fps"]
|
||||||
|
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load data
|
||||||
|
data_motion = np.load(ipath_motion).reshape(-1, 136) # (N, 136)
|
||||||
|
data_speech = np.load(ipath_speech) # (M, 80)
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}, mfcc len / 4 = {data_speech.shape[0] / 4}")
|
||||||
|
# assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
|
||||||
|
# resample fps=25.0
|
||||||
|
data_motion_25fps = landmark_resample_fps(data_motion, source_fps=fps, target_fps=25.0)
|
||||||
|
print(f"data_pt_30fps shape = {data_motion.shape}, data_motion_25fps = {data_motion_25fps.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
# alignment
|
||||||
|
nsetps = min(data_motion_25fps.shape[0], data_speech.shape[0] // 4)
|
||||||
|
print(f"nsetps = {nsetps}")
|
||||||
|
|
||||||
|
data_motion = data_motion_25fps[:nsetps, :]
|
||||||
|
data_speech = data_speech[:nsetps*4, :].reshape(nsetps, -1)
|
||||||
|
print(f"after alignment data_motion = {data_motion.shape}, data_speech = {data_speech.shape}")
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
data_train[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech
|
||||||
|
}
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
data_valid[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech
|
||||||
|
}
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_test[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech
|
||||||
|
}
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
|
||||||
|
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
|
||||||
|
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
|
||||||
|
print(f"save data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)}) --> {path_save}")
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_audio_trim = ipath_data.joinpath("audio/audio_trim.wav")
|
||||||
|
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
data, sr = librosa.load(str(ipath_audio_trim), sr=16484) # 16484 = fps * 550 让这个sr是fps的整数,
|
||||||
|
hop_len = int(sr / fps)
|
||||||
|
n_fft = int(sr * 0.13) # default 2048
|
||||||
|
print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
|
||||||
|
|
||||||
|
# melspectrogram
|
||||||
|
mel = librosa.feature.melspectrogram(y=data, sr=sr,
|
||||||
|
n_fft=n_fft, # FFT窗口的长度
|
||||||
|
hop_length=hop_len, # 帧移
|
||||||
|
win_length=n_fft, # 窗口长度,默认=n_fft
|
||||||
|
window="hann", # 加hanming窗
|
||||||
|
n_mels=27, # 滤波器组
|
||||||
|
fmin=0.0, fmax=8000)
|
||||||
|
mel = np.log(mel+1).T
|
||||||
|
print(f"sr={sr}, data ={data.shape}, mel = {mel.shape}, (min,max)=({np.min(mel), np.max(mel)}")
|
||||||
|
|
||||||
|
# align to video
|
||||||
|
assert mel.shape[0] >= nframe_trim
|
||||||
|
mel_align = mel[:nframe_trim, :]
|
||||||
|
|
||||||
|
# save
|
||||||
|
# np.save(ipath_save_feat, mel_align)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
import torch
|
||||||
|
from scipy.io.wavfile import read
|
||||||
|
|
||||||
|
# We're using the audio processing from TacoTron2 to make sure it matches
|
||||||
|
sys.path.insert(0, '/mnt/data/CODE/Audio2Expression/3rdpart/')
|
||||||
|
import tacotron2
|
||||||
|
from tacotron2.layers import TacotronSTFT
|
||||||
|
|
||||||
|
|
||||||
|
MAX_WAV_VALUE = 32768.0
|
||||||
|
|
||||||
|
def get_mel(self, audio):
|
||||||
|
audio_norm = audio / MAX_WAV_VALUE
|
||||||
|
audio_norm = audio_norm.unsqueeze(0)
|
||||||
|
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
|
||||||
|
melspec = self.stft.mel_spectrogram(audio_norm)
|
||||||
|
melspec = torch.squeeze(melspec, 0)
|
||||||
|
return melspec
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# load STFT
|
||||||
|
model = TacotronSTFT(filter_length=1024,
|
||||||
|
hop_length=256,
|
||||||
|
win_length=1024,
|
||||||
|
sampling_rate=22050,
|
||||||
|
mel_fmin=0.0, mel_fmax=8000)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 6 # 6, 2
|
||||||
|
overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
|
||||||
|
ipath_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
|
||||||
|
|
||||||
|
ipath_save_audio = ipath_data.joinpath("audio/feat_mel_trim_split_6s.npy") # feat_mel_trim_split
|
||||||
|
ipath_save_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_6s.npy") # feat_ldmk_trim_norm_split
|
||||||
|
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
|
||||||
|
if not ipath_audio.exists() or not ipath_ladmk.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_audio} or {ipath_ladmk}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load landmark
|
||||||
|
data_ladmk = np.load(ipath_ladmk).reshape(-1, 136) # (nframe, 136)
|
||||||
|
assert data_ladmk.shape[0] == nframe_trim, f"the length of landmark {data_ladmk.shape[0]} != nframe_trim {nframe_trim}"
|
||||||
|
|
||||||
|
nsize_ldmk = int( nwin_train_secs * fps )
|
||||||
|
nstep_ldmk = int( nwin_train_secs * fps * (1-overlap) )
|
||||||
|
|
||||||
|
data_ladmk = torch.from_numpy(data_ladmk).float()
|
||||||
|
data_ladmk2 = data_ladmk.unfold(dimension=0, size=nsize_ldmk, step=nstep_ldmk) # (nframe_trim//30, 136, 30)
|
||||||
|
data_ladmk2 = data_ladmk2.permute(0, 2, 1) # (nsplits, nsteps, 136)
|
||||||
|
print(f"data landmark unfold = {data_ladmk2.shape}")
|
||||||
|
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
|
||||||
|
print(f"ldmk ==> nsize = {nsize_ldmk}, nstep = {nstep_ldmk}, len = {nframe_trim // nstep_ldmk}")
|
||||||
|
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
|
||||||
|
if sr != 22050:
|
||||||
|
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
|
||||||
|
|
||||||
|
audio = torch.from_numpy(audio).float()
|
||||||
|
audio = audio.unsqueeze(0)
|
||||||
|
melspec = model.mel_spectrogram(audio)
|
||||||
|
melspec = torch.squeeze(melspec, 0) # (80, 20374)
|
||||||
|
print(f"landmark = {data_ladmk.shape}, min-max({data_ladmk.min():.4f}, {data_ladmk.max():.4f}), Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
|
||||||
|
|
||||||
|
|
||||||
|
rato = melspec.shape[1] / nframe_trim
|
||||||
|
|
||||||
|
nsize_audio = int( nsize_ldmk * rato) + 1 # 518 (if nwind=6s),
|
||||||
|
nstep_audio = int( nstep_ldmk * rato)
|
||||||
|
print(f"audio ==> rato = {rato}, nsize = {nsize_audio}, nstep = {nstep_audio}, len={melspec.shape[1] // nstep_audio }")
|
||||||
|
|
||||||
|
|
||||||
|
nsplit = data_ladmk2.shape[0]
|
||||||
|
data_melspec = torch.zeros(nsplit, 80, nsize_audio)
|
||||||
|
# nsize = int(nwin_train_secs * fps * rato) + 1 # rate = melspec.shape[1] / nframe_trim
|
||||||
|
|
||||||
|
for i in range(nsplit):
|
||||||
|
nseg_beg = int( i * nstep_ldmk * rato )
|
||||||
|
nseg_end = nseg_beg + nsize_audio
|
||||||
|
|
||||||
|
# print(f"{i:03d}/{nsplit}, {nseg_beg:05d}-{nseg_end:05d}")
|
||||||
|
data_melspec[i] = melspec[:, nseg_beg:nseg_end]
|
||||||
|
|
||||||
|
|
||||||
|
data_melspec = data_melspec.permute(0, 2, 1) # (nsplits, nsteps, 80)
|
||||||
|
print(f"data_melspec = {data_melspec.shape}, data_ladmk = {data_ladmk2.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
# save
|
||||||
|
np.save(ipath_save_audio, data_melspec) # (nsplit, 173, 80)
|
||||||
|
np.save(ipath_save_ladmk, data_ladmk2) # (nsplit, 60, 136)
|
||||||
|
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
import torch
|
||||||
|
from scipy.io.wavfile import read
|
||||||
|
|
||||||
|
# We're using the audio processing from TacoTron2 to make sure it matches
|
||||||
|
sys.path.insert(0, '/mnt/data2/CODE/Audio2Expression/3rdpart/')
|
||||||
|
import tacotron2
|
||||||
|
from tacotron2.layers import TacotronSTFT
|
||||||
|
|
||||||
|
|
||||||
|
MAX_WAV_VALUE = 32768.0
|
||||||
|
|
||||||
|
def get_mel(self, audio):
|
||||||
|
audio_norm = audio / MAX_WAV_VALUE
|
||||||
|
audio_norm = audio_norm.unsqueeze(0)
|
||||||
|
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
|
||||||
|
melspec = self.stft.mel_spectrogram(audio_norm)
|
||||||
|
melspec = torch.squeeze(melspec, 0)
|
||||||
|
return melspec
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# load STFT
|
||||||
|
model = TacotronSTFT(filter_length=1024,
|
||||||
|
hop_length=256,
|
||||||
|
win_length=1024,
|
||||||
|
sampling_rate=22050,
|
||||||
|
mel_fmin=0.0, mel_fmax=8000)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 2 # 6, 2
|
||||||
|
overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
|
||||||
|
|
||||||
|
ipath_save = ipath_data.joinpath("audio/feat_mel_trim_split_2s.npy") # feat_mel_trim_split
|
||||||
|
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# split frames
|
||||||
|
nsize_split = int( nwin_train_secs * fps )
|
||||||
|
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
|
||||||
|
nsplit = (nframe_trim - nsize_split) // nstep_split + 1
|
||||||
|
print(f"frame ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {nsplit}")
|
||||||
|
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
|
||||||
|
if sr != 22050:
|
||||||
|
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
|
||||||
|
|
||||||
|
audio = torch.from_numpy(audio).float()
|
||||||
|
audio = audio.unsqueeze(0)
|
||||||
|
melspec = model.mel_spectrogram(audio)
|
||||||
|
melspec = torch.squeeze(melspec, 0) # (80, 20374)
|
||||||
|
print(f"Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
|
||||||
|
|
||||||
|
|
||||||
|
rato = melspec.shape[1] / nframe_trim
|
||||||
|
nsize_audio = int( nsize_split * rato) + 1 # 518 (if nwind=6s),
|
||||||
|
# nstep_audio = int( nstep_split * rato)
|
||||||
|
print(f"audio ==> rato = {rato}, nsize = {nsize_audio}") # nstep = {nstep_audio}, len={(melspec.shape[1] - nsize_audio) // nstep_audio + 1}")
|
||||||
|
|
||||||
|
|
||||||
|
data_melspec = torch.zeros(nsplit, 80, nsize_audio)
|
||||||
|
# nsize = int(nwin_train_secs * fps * rato) + 1 # rate = melspec.shape[1] / nframe_trim
|
||||||
|
|
||||||
|
for i in range(nsplit):
|
||||||
|
nseg_beg = int( i * nstep_split * rato )
|
||||||
|
nseg_end = nseg_beg + nsize_audio
|
||||||
|
data_melspec[i] = melspec[:, nseg_beg:nseg_end]
|
||||||
|
# print(f"{i:03d}/{nsplit}, {nseg_beg:05d}-{nseg_end:05d}")
|
||||||
|
|
||||||
|
# save
|
||||||
|
data_melspec = data_melspec.permute(0, 2, 1) # (nsplits, nsteps, 80)
|
||||||
|
np.save(ipath_save, data_melspec) # (nsplit, 173, 80)
|
||||||
|
print(f"data_melspec = {data_melspec.shape}, save to --> {ipath_save}")
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
import torch
|
||||||
|
from scipy.io.wavfile import read
|
||||||
|
|
||||||
|
# We're using the audio processing from TacoTron2 to make sure it matches
|
||||||
|
sys.path.insert(0, '/ssdata1/lsen/CODE/Audio2Expression/3rdpart/')
|
||||||
|
import tacotron2
|
||||||
|
from tacotron2.layers import TacotronSTFT
|
||||||
|
|
||||||
|
|
||||||
|
MAX_WAV_VALUE = 32768.0
|
||||||
|
|
||||||
|
def get_mel(self, audio):
|
||||||
|
audio_norm = audio / MAX_WAV_VALUE
|
||||||
|
audio_norm = audio_norm.unsqueeze(0)
|
||||||
|
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
|
||||||
|
melspec = self.stft.mel_spectrogram(audio_norm)
|
||||||
|
melspec = torch.squeeze(melspec, 0)
|
||||||
|
return melspec
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# load STFT
|
||||||
|
model = TacotronSTFT(filter_length=1024,
|
||||||
|
hop_length=256,
|
||||||
|
win_length=1024,
|
||||||
|
sampling_rate=22050,
|
||||||
|
mel_fmin=0.0, mel_fmax=8000)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 2 # 6, 2
|
||||||
|
overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
|
||||||
|
|
||||||
|
ipath_save = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy") # feat_mel_trim_split
|
||||||
|
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
|
||||||
|
|
||||||
|
if not ipath_audio.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_audio}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# load trim audio
|
||||||
|
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
|
||||||
|
if sr != 22050:
|
||||||
|
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
|
||||||
|
|
||||||
|
audio = torch.from_numpy(audio).float()
|
||||||
|
audio = audio.unsqueeze(0)
|
||||||
|
print(f"audio shape = {audio.shape}, audio min-max({audio.min():.4f}, {audio.max():.4f})")
|
||||||
|
|
||||||
|
melspec = model.mel_spectrogram(audio)
|
||||||
|
melspec = torch.squeeze(melspec, 0) # (80, 20374)
|
||||||
|
print(f"Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
|
||||||
|
|
||||||
|
|
||||||
|
# save
|
||||||
|
melspec = melspec.permute(1,0) # (nsplits, nsteps, 80)
|
||||||
|
|
||||||
|
# np.save(ipath_save, melspec) # (nsplit, 173, 80)
|
||||||
|
print(f"melspec = {melspec.shape}, save to --> {ipath_save}")
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_ldmk = ipath_data.joinpath("landmk-PFLD")
|
||||||
|
ipath_save_feat = ipath_data.joinpath("audio/feat_ldmk_trim.npy")
|
||||||
|
|
||||||
|
if ipath_save_feat.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load landmark
|
||||||
|
feat_ldmk = []
|
||||||
|
prev_ldmk = None
|
||||||
|
nContinue = 0
|
||||||
|
for j in range(ibeg, iend):
|
||||||
|
jpath_ldmk = ipath_ldmk.joinpath(f"frame--{j:05d}.txt")
|
||||||
|
|
||||||
|
if not jpath_ldmk.exists():
|
||||||
|
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk)
|
||||||
|
if nContinue <= 2:
|
||||||
|
data_ldmk = prev_ldmk
|
||||||
|
nContinue += 1
|
||||||
|
else:
|
||||||
|
nContinue += 1
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_ldmk = np.loadtxt(jpath_ldmk).astype(np.float)
|
||||||
|
prev_ldmk = data_ldmk
|
||||||
|
nContinue = 0
|
||||||
|
|
||||||
|
feat_ldmk.append(data_ldmk)
|
||||||
|
# if j % 100 == 0:
|
||||||
|
# print(f"the {j:05d}-th landmark")
|
||||||
|
|
||||||
|
|
||||||
|
# save
|
||||||
|
feat_ldmk = np.array(feat_ldmk)
|
||||||
|
if nContinue <= 2 and feat_ldmk.shape[0] == (iend-ibeg):
|
||||||
|
np.save(ipath_save_feat, feat_ldmk)
|
||||||
|
print(f"feat shape = {feat_ldmk.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
|
||||||
|
else:
|
||||||
|
print(f"ERROR: some landmark missing or length not same, length = {feat_ldmk.shape}/{iend-ibeg}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 2 # 6, 2
|
||||||
|
overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# print(f"\n processing {ivideo_name} ... ")
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
|
||||||
|
|
||||||
|
ipath_save = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_2s.npy") # feat_mel_trim_split
|
||||||
|
|
||||||
|
if not ipath_ladmk.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_ladmk}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load landmark
|
||||||
|
data_ladmk = np.load(ipath_ladmk).reshape(-1, 136) # (nframe, 136)
|
||||||
|
assert data_ladmk.shape[0] == nframe_trim, f"the length of landmark {data_ladmk.shape[0]} != nframe_trim {nframe_trim}"
|
||||||
|
|
||||||
|
|
||||||
|
# split frames
|
||||||
|
nsize_split = int( nwin_train_secs * fps )
|
||||||
|
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
|
||||||
|
nsplit = (nframe_trim - nsize_split) // nstep_split + 1
|
||||||
|
print(f"frame ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {nsplit}")
|
||||||
|
|
||||||
|
# split landmark
|
||||||
|
data_ladmk = torch.from_numpy(data_ladmk).float()
|
||||||
|
data_ladmk2 = data_ladmk.unfold(dimension=0, size=nsize_split, step=nstep_split) # (nframe_trim//30, 136, 30)
|
||||||
|
data_ladmk2 = data_ladmk2.permute(0, 2, 1) # (nsplits, nsteps, 136)
|
||||||
|
print(f"data landmark unfold = {data_ladmk2.shape}")
|
||||||
|
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
|
||||||
|
|
||||||
|
# save
|
||||||
|
np.save(ipath_save, data_ladmk2) # (nsplit, 60, 136)
|
||||||
|
print(f"data_ladmk2 = {data_ladmk2.shape}, save to --> {ipath_save}")
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data2/CODE/Audio2Expression")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
# from common.animation import save_animation, save_animation_with_gt
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # processing
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
if ivideo_name not in ["Celebrating-Independence-Day"]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_ldmk = ipath_data.joinpath("landmk-PFLD")
|
||||||
|
ipath_save_feat = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
|
||||||
|
# if ipath_save_feat.exists():
|
||||||
|
# continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load landmark
|
||||||
|
feat_ldmk = []
|
||||||
|
prev_ldmk = None
|
||||||
|
nContinue = 0
|
||||||
|
for j in range(ibeg, iend):
|
||||||
|
jpath_ldmk = ipath_ldmk.joinpath(f"frame--{j:05d}.txt")
|
||||||
|
|
||||||
|
if not jpath_ldmk.exists():
|
||||||
|
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk)
|
||||||
|
if nContinue <= 2:
|
||||||
|
data_ldmk = prev_ldmk
|
||||||
|
nContinue += 1
|
||||||
|
else:
|
||||||
|
nContinue += 1
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_ldmk = np.loadtxt(jpath_ldmk).astype(np.float)
|
||||||
|
data_ldmk, _, _ = landmark_normalize(data_ldmk) # normalize
|
||||||
|
|
||||||
|
prev_ldmk = data_ldmk
|
||||||
|
nContinue = 0
|
||||||
|
|
||||||
|
feat_ldmk.append(data_ldmk)
|
||||||
|
# if j % 100 == 0:
|
||||||
|
# print(f"the {j:05d}-th landmark")
|
||||||
|
|
||||||
|
|
||||||
|
# save
|
||||||
|
feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
|
||||||
|
if nContinue <= 2 and feat_ldmk.shape[0] == (iend-ibeg):
|
||||||
|
np.save(ipath_save_feat, feat_ldmk)
|
||||||
|
print(f"feat shape = {feat_ldmk.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
|
||||||
|
# save to animation
|
||||||
|
|
||||||
|
else:
|
||||||
|
print(f"ERROR: some landmark missing or length not same, length = {feat_ldmk.shape}/{iend-ibeg}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
idx_pos = [0, 1, 2, 5, 15, 16, 17, 18]
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
counter = 0
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# if ivideo_name != "Weekly-Address-Continuing-to-Grow-the-Economy-in-the-New-Year":
|
||||||
|
# continue
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_pose = ipath_data.joinpath("openpose")
|
||||||
|
|
||||||
|
ipath_feat_body = ipath_data.joinpath("audio/openpose_upbody_trim.npy")
|
||||||
|
ipath_feat_face = ipath_data.joinpath("audio/openpose_face_trim.npy")
|
||||||
|
|
||||||
|
if ipath_feat_body.exists() and ipath_feat_face.exists():
|
||||||
|
counter += 1
|
||||||
|
# os.remove(str(ipath_feat_body))
|
||||||
|
# os.remove(str(ipath_feat_face))
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
nContinue = 0
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load pose
|
||||||
|
feat_body = []
|
||||||
|
feat_face = []
|
||||||
|
prev_feat_body = None
|
||||||
|
prev_feat_face = None
|
||||||
|
nContinue = 0
|
||||||
|
for j in range(ibeg, iend):
|
||||||
|
|
||||||
|
# print(f"{j}-th frame, of {ibeg}, {iend}")
|
||||||
|
# if j > ibeg + 10: break
|
||||||
|
jpath_pose = ipath_pose.joinpath(f"video_orignal_{j:012d}_keypoints.json")
|
||||||
|
if not jpath_pose.exists():
|
||||||
|
print("ERROR: Missing the landmark of frame --> ", jpath_pose)
|
||||||
|
if prev_feat_body is None:
|
||||||
|
print("ERRO: The first should be a person")
|
||||||
|
nContinue = 100
|
||||||
|
break
|
||||||
|
|
||||||
|
# give two change
|
||||||
|
if nContinue <= 2:
|
||||||
|
ipose_face = prev_feat_face
|
||||||
|
ipose_body = prev_feat_body
|
||||||
|
nContinue += 1
|
||||||
|
else:
|
||||||
|
nContinue = 100
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
|
||||||
|
# load json file
|
||||||
|
with open(str(jpath_pose)) as f:
|
||||||
|
ipose = json.load(f)
|
||||||
|
|
||||||
|
# read pose and face
|
||||||
|
npid = len(ipose['people'])
|
||||||
|
if npid == 0:
|
||||||
|
print(f"ERROR: detected NO person! of the {j}-th frames")
|
||||||
|
if prev_feat_body is None:
|
||||||
|
print("ERRO: The first should be a person")
|
||||||
|
nContinue = 100
|
||||||
|
break
|
||||||
|
# give two change
|
||||||
|
if nContinue <= 2:
|
||||||
|
ipose_face = prev_feat_face
|
||||||
|
ipose_body = prev_feat_body
|
||||||
|
nContinue += 1
|
||||||
|
else:
|
||||||
|
nContinue = 100
|
||||||
|
break
|
||||||
|
|
||||||
|
elif npid > 1:
|
||||||
|
print(f"\nERROR: detected MULTI persons, should select one!, the {j}-th in ({ibeg},{iend}), ")
|
||||||
|
# print(ipose)
|
||||||
|
# select the detetected which closest to prev_feat_face
|
||||||
|
nContinue = 0
|
||||||
|
diff_center = np.zeros((npid,))
|
||||||
|
for i in range(npid):
|
||||||
|
tmp_prev = 0 if prev_feat_body is None else prev_feat_body
|
||||||
|
ipose_body = np.array(ipose['people'][i]['pose_keypoints_2d']).reshape(-1, 3)[idx_pos, :2]
|
||||||
|
diff_center[i] = np.mean(np.abs(ipose_body - tmp_prev))
|
||||||
|
|
||||||
|
idx = np.argmin(diff_center) if prev_feat_body is not None else np.argmax(diff_center)
|
||||||
|
ipose_face = np.array(ipose['people'][idx]['face_keypoints_2d']).reshape(-1, 3)[:, :2]
|
||||||
|
ipose_body = np.array(ipose['people'][idx]['pose_keypoints_2d']).reshape(-1, 3)[idx_pos, :2]
|
||||||
|
|
||||||
|
print(f"\t selected the {idx}-th pose")
|
||||||
|
|
||||||
|
else:
|
||||||
|
nContinue = 0
|
||||||
|
ipose_face = np.array(ipose['people'][0]['face_keypoints_2d']).reshape(-1, 3)[:, :2]
|
||||||
|
ipose_body = np.array(ipose['people'][0]['pose_keypoints_2d']).reshape(-1, 3)[idx_pos, :2]
|
||||||
|
|
||||||
|
|
||||||
|
if prev_feat_body is not None:
|
||||||
|
# check pose corrected
|
||||||
|
# print(f"face shpe = {ipose_face.shape}, body = {ipose_body.shape}")
|
||||||
|
for k in range(ipose_body.shape[0]):
|
||||||
|
if ipose_body[k][0] == 0 and ipose_body[k][1] == 0:
|
||||||
|
ipose_body[k, :] = prev_feat_body[k, :]
|
||||||
|
|
||||||
|
if prev_feat_face is not None:
|
||||||
|
# check landmark corrected
|
||||||
|
for k in range(ipose_face.shape[0]):
|
||||||
|
if ipose_face[k][0] == 0 and ipose_face[k][1] == 0:
|
||||||
|
ipose_face[k, :] = prev_feat_face[k, :]
|
||||||
|
|
||||||
|
# add to feat
|
||||||
|
feat_body.append(ipose_body)
|
||||||
|
feat_face.append(ipose_face)
|
||||||
|
prev_feat_body = ipose_body
|
||||||
|
prev_feat_face = ipose_face
|
||||||
|
|
||||||
|
# break
|
||||||
|
|
||||||
|
|
||||||
|
# visualize
|
||||||
|
|
||||||
|
# save
|
||||||
|
if nContinue <= 2:
|
||||||
|
# save
|
||||||
|
feat_body = np.array(feat_body)
|
||||||
|
feat_face = np.array(feat_face)
|
||||||
|
|
||||||
|
print(f"save... feat_body shape = {feat_body.shape}, feat_face shape = {feat_face.shape}")
|
||||||
|
np.save(ipath_feat_body, feat_body)
|
||||||
|
np.save(ipath_feat_face, feat_face)
|
||||||
|
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
else:
|
||||||
|
print("nContinue > 2 some landmark broken or cut-off") # (nframe, 68, 2)
|
||||||
|
|
||||||
|
|
||||||
|
# break
|
||||||
|
print(f"OVER: processing {counter} videos")
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import json
|
||||||
|
import pickle
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
|
||||||
|
from common.landmark import landmark_normalize
|
||||||
|
from common.animation import save_animation, save_animation_with_gt
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
|
||||||
|
ipath_ldmk_dlib = ipath_data.joinpath("landmk")
|
||||||
|
ipath_ldmk_pfld = ipath_data.joinpath("landmk-PFLD")
|
||||||
|
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
|
||||||
|
fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
# load landmark
|
||||||
|
vldmk_dlib, vldmk_pfld = [], []
|
||||||
|
pldmk_dlib, pldmk_pfld = None, None
|
||||||
|
nContinue_dlib, nContinue_pfld = 0, 0
|
||||||
|
|
||||||
|
|
||||||
|
for j in range(ibeg, iend):
|
||||||
|
|
||||||
|
# load Dlib
|
||||||
|
jpath_ldmk_dlib = ipath_ldmk_dlib.joinpath(f"frame-{j:05d}.txt")
|
||||||
|
jpath_ldmk_pfld = ipath_ldmk_pfld.joinpath(f"frame--{j:05d}.txt")
|
||||||
|
|
||||||
|
# add Dlib landmark
|
||||||
|
if not jpath_ldmk_dlib.exists():
|
||||||
|
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk_dlib)
|
||||||
|
if nContinue_dlib <= 2:
|
||||||
|
data_ldmk = pldmk_dlib
|
||||||
|
nContinue_dlib += 1
|
||||||
|
else:
|
||||||
|
nContinue_dlib += 1
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
data_ldmk = np.loadtxt(jpath_ldmk_dlib).astype(np.float)
|
||||||
|
data_ldmk, _, _ = landmark_normalize(data_ldmk)
|
||||||
|
|
||||||
|
pldmk_dlib = data_ldmk
|
||||||
|
nContinue_dlib = 0
|
||||||
|
vldmk_dlib.append(data_ldmk)
|
||||||
|
|
||||||
|
# add PFLD landmark
|
||||||
|
if not jpath_ldmk_pfld.exists():
|
||||||
|
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk_pfld)
|
||||||
|
if nContinue_pfld <= 2:
|
||||||
|
data_ldmk = pldmk_pfld
|
||||||
|
nContinue_pfld += 1
|
||||||
|
else:
|
||||||
|
nContinue_pfld += 1
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
data_ldmk = np.loadtxt(jpath_ldmk_pfld).astype(np.float)
|
||||||
|
data_ldmk, _, _ = landmark_normalize(data_ldmk)
|
||||||
|
|
||||||
|
pldmk_pfld = data_ldmk
|
||||||
|
nContinue_pfld = 0
|
||||||
|
vldmk_pfld.append(data_ldmk)
|
||||||
|
|
||||||
|
|
||||||
|
# if j % 100 == 0:
|
||||||
|
# print(f"the {j:05d}-th landmark")
|
||||||
|
|
||||||
|
# save
|
||||||
|
vldmk_dlib = np.array(vldmk_dlib).reshape(1, -1, 68, 2) # (N, 68, 2)
|
||||||
|
vldmk_pfld = np.array(vldmk_pfld).reshape(1, -1, 68, 2)
|
||||||
|
print(f"vldmk_dlib shape = {vldmk_dlib.shape}, vldmk_pfld shape= {vldmk_pfld.shape}") # (nframe, 68, 2)
|
||||||
|
|
||||||
|
|
||||||
|
if nContinue_pfld <= 2 and nContinue_dlib <= 2 and vldmk_dlib.shape[0] == (iend-ibeg):
|
||||||
|
# np.save(ipath_save_feat, vldmk_dlib)
|
||||||
|
|
||||||
|
# show annotation
|
||||||
|
save_animation_with_gt(vldmk_dlib, vldmk_pfld,
|
||||||
|
path_save=Path(ipath_data),
|
||||||
|
suffix=f'DLIB_PLDF',
|
||||||
|
w=256, h=256, dpi=100)
|
||||||
|
|
||||||
|
# print(f"feat shape = {vldmk_dlib.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
|
||||||
|
|
||||||
|
else:
|
||||||
|
print(f"ERROR: some landmark missing or length not same, length = {vldmk_dlib.shape}/{iend-ibeg}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
def load_video_info(path_info, verbose=True):
|
||||||
|
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
W = info["width"][0] # 1280 or 1920
|
||||||
|
H = info["height"][0] # 720 or 1080
|
||||||
|
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
if verbose: print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
return ibeg, iend, nframe_trim, W, H, info
|
||||||
|
else:
|
||||||
|
if verbose: print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
return None, None, None, W, H, info
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-no-scale-alignment') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# get mean pose
|
||||||
|
total_pose = []
|
||||||
|
total_shoulder = []
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_pose = ipath_data.joinpath("audio/openpose_upbody_trim.npy")
|
||||||
|
|
||||||
|
ibeg, iend, _, W, H, info= load_video_info(ipath_info, verbose=False)
|
||||||
|
if ibeg is None: continue
|
||||||
|
if not ipath_feat_pose.exists(): continue
|
||||||
|
|
||||||
|
idata_pose = np.load(ipath_feat_pose) # (nframes, 8, 2)
|
||||||
|
imean_pose = np.mean(idata_pose, axis=0) # (8, 2)
|
||||||
|
imean_pose = imean_pose / np.array([W, H])
|
||||||
|
|
||||||
|
imean_shoulder = np.sqrt((imean_pose[3,0]-imean_pose[2,0])**2 + (imean_pose[3,1]-imean_pose[2,1])**2)
|
||||||
|
|
||||||
|
print(f"data pose shape = {idata_pose.shape}, mean shape={imean_pose.shape}, root={imean_pose[1]}, size shoulder = {imean_shoulder}--> {ivideo_name}")
|
||||||
|
total_pose.append(imean_pose)
|
||||||
|
total_shoulder.append(imean_shoulder)
|
||||||
|
|
||||||
|
# update info
|
||||||
|
info["mean_shoulder_size"] =imean_shoulder
|
||||||
|
info["mean_pose"] = list(imean_pose.reshape(-1))
|
||||||
|
with open(str(ipath_info), 'w+') as f:
|
||||||
|
json.dump(info, f)
|
||||||
|
print(f"update video info in -> {ipath_info}")
|
||||||
|
|
||||||
|
total_pose = np.array(total_pose)
|
||||||
|
mean_pose = np.mean(total_pose, axis=0)
|
||||||
|
mean_shoulder = np.mean(total_shoulder)
|
||||||
|
print(f"total_pose shape = {total_pose.shape}, mean pose ={mean_pose.shape}, mean[1,] = {mean_pose[1,:]}, mean shoulder size = {mean_shoulder}")
|
||||||
|
# save mean
|
||||||
|
np.save(path_save.joinpath("mean_pose.npy"), mean_pose) # (8,2)
|
||||||
|
np.save(path_save.joinpath("mean_shoulder.npy"), mean_shoulder)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
# import moviepy.editor as mpy
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, "/mnt/data2/CODE/TalkingGlow")
|
||||||
|
from common.utils import smooth
|
||||||
|
from common.logger import Logger
|
||||||
|
from common.landmark import landmark_to_images
|
||||||
|
|
||||||
|
def load_video_info(path_info, verbose=True):
|
||||||
|
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
W = info["width"][0] # 1280 or 1920
|
||||||
|
H = info["height"][0] # 720 or 1080
|
||||||
|
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
if verbose: print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
return ibeg, iend, nframe_trim, W, H, info
|
||||||
|
else:
|
||||||
|
if verbose: print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
return None, None, None, W, H, info
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-no-scale-alignment') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# get mean pose
|
||||||
|
mean_pose = np.load(path_save.joinpath("mean_pose.npy")) # (8,2)
|
||||||
|
mean_shoulder = np.load(path_save.joinpath("mean_shoulder.npy")) # (1,)
|
||||||
|
print(f"mean pose = {mean_pose.shape}, root pose = {mean_pose[1]}, mean shoulder = {mean_shoulder}")
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
ncounter = 0
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# if ivideo_name != "Weekly-Address-Ensuring-Equal-Pay-for-Equal-Work":
|
||||||
|
# continue
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_ldmk = ipath_data.joinpath("audio/feat_ldmk_trim.npy")
|
||||||
|
ipath_feat_pose = ipath_data.joinpath("audio/openpose_upbody_trim.npy")
|
||||||
|
|
||||||
|
ipath_feat_ldmk_align = ipath_data.joinpath("audio/feat_ldmk_align_trim.npy")
|
||||||
|
ipath_feat_pose_align = ipath_data.joinpath("audio/openpose_upbody_align_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
if not ipath_feat_ldmk.exists() or not ipath_feat_pose.exists():
|
||||||
|
continue
|
||||||
|
elif ipath_feat_ldmk_align.exists() and ipath_feat_pose_align.exists():
|
||||||
|
ncounter += 1
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
print(f"\n processing the {ncounter}-th videp, {ivideo_name} ... ")
|
||||||
|
ncounter += 1
|
||||||
|
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
ibeg, iend, _, W, H, info = load_video_info(ipath_info)
|
||||||
|
if ibeg is None: continue
|
||||||
|
|
||||||
|
# load landmark feat
|
||||||
|
data_ldmk = np.load(ipath_feat_ldmk) # (nframe, 68, 2)
|
||||||
|
data_pose = np.load(ipath_feat_pose) # (nframe, 8, 2)
|
||||||
|
data_ldmk = data_ldmk / np.array([[[W, H]]]) # scale landmark
|
||||||
|
data_pose = data_pose / np.array([[[W, H]]]) # scale pose
|
||||||
|
|
||||||
|
print(f"data landmark shape={data_ldmk.shape}, pose shape = {data_pose.shape}")
|
||||||
|
|
||||||
|
assert data_ldmk.shape[0] == data_pose.shape[0], "nframes length should be same"
|
||||||
|
|
||||||
|
##################################
|
||||||
|
# STEP 1: get sacle and smooth scale
|
||||||
|
v_scale = []
|
||||||
|
for j in range(data_ldmk.shape[0]):
|
||||||
|
jdata_pose = data_pose[j, :, :] # (8, 2)
|
||||||
|
jshoulder = np.sqrt((jdata_pose[3,0]-jdata_pose[2,0])**2 + (jdata_pose[3,1]-jdata_pose[2,1])**2)
|
||||||
|
scale = mean_shoulder / jshoulder
|
||||||
|
v_scale.append(scale)
|
||||||
|
# if j % 100 == 0:
|
||||||
|
# print(f"\nthe {ibeg + j}-th frame!")
|
||||||
|
# print(f"pose root = {data_pose[j, 1, :]}, mean pose root = {mean_pose[1]}")
|
||||||
|
# print(f"should size = {jshoulder:.4f}, mean shoulder = {mean_shoulder:.4f}, scale = {scale:0.4f}")
|
||||||
|
v_scale = np.array(v_scale)
|
||||||
|
v_scale_smooth = smooth(v_scale, window_len=60, window='hanning')
|
||||||
|
print(f"scale shape= {v_scale.shape}, smooth = {v_scale_smooth.shape}")
|
||||||
|
# for v, s in zip(v_scale, v_scale_smooth):
|
||||||
|
# print(f"orignal {v:.4f}, smooth={s:.4f}, mean={mean_shoulder:.4f}")
|
||||||
|
|
||||||
|
|
||||||
|
##################################
|
||||||
|
# STEP 2: sacle landmark and pose
|
||||||
|
data_ldmk_scale = []
|
||||||
|
data_pose_scale = []
|
||||||
|
for j in range(data_ldmk.shape[0]):
|
||||||
|
jdata_ldmk_scale = data_ldmk[j, :, :] * v_scale_smooth[j]
|
||||||
|
jdata_pose_scale = data_pose[j, :, :] * v_scale_smooth[j]
|
||||||
|
|
||||||
|
data_ldmk_scale.append(jdata_ldmk_scale)
|
||||||
|
data_pose_scale.append(jdata_pose_scale)
|
||||||
|
|
||||||
|
# if j % 100 == 0:
|
||||||
|
# jshoulder_scale = np.sqrt((jdata_pose_scale[3,0]-jdata_pose_scale[2,0])**2 + (jdata_pose_scale[3,1]-jdata_pose_scale[2,1])**2)
|
||||||
|
# print(f"\nthe {ibeg + j}-th frame!")
|
||||||
|
# print(f"pose root = {data_pose[j, 1, :]}, scale root={jdata_pose_scale[1]}, mean pose root = {mean_pose[1]}")
|
||||||
|
# print(f"shoulder size = {jshoulder:.4f}, scale ={jshoulder_scale:.4f} mean shoulder = {mean_shoulder:.4f}, scale = {v_scale[j]:.4f}, smooth scale={v_scale_smooth[j]:.4f}")
|
||||||
|
|
||||||
|
data_ldmk_scale = np.array(data_ldmk_scale)
|
||||||
|
data_pose_scale = np.array(data_pose_scale)
|
||||||
|
|
||||||
|
##################################
|
||||||
|
# STEP 3: alignment to mean-pose
|
||||||
|
data_ldmk_align = []
|
||||||
|
data_pose_align = []
|
||||||
|
for j in range(data_ldmk.shape[0]):
|
||||||
|
|
||||||
|
jpose_root = data_pose_scale[j, 1, :] # (2, )
|
||||||
|
jmean_root = mean_pose[1, :] # (2, )
|
||||||
|
jdeta = jmean_root - jpose_root
|
||||||
|
|
||||||
|
jdata_ldmk_align = data_ldmk_scale[j, :, :] + jdeta.reshape(1, 2)
|
||||||
|
jdata_pose_align = data_pose_scale[j, :, :] + jdeta.reshape(1, 2)
|
||||||
|
|
||||||
|
data_ldmk_align.append(jdata_ldmk_align)
|
||||||
|
data_pose_align.append(jdata_pose_align)
|
||||||
|
|
||||||
|
if j % 1000 == 0:
|
||||||
|
jshoulder = np.sqrt((data_pose[j,3,0]-data_pose[j,2,0])**2 + (data_pose[j,3,1]-data_pose[j,2,1])**2)
|
||||||
|
jshoulder_scale = np.sqrt((data_pose_scale[j,3,0]-data_pose_scale[j,2,0])**2 + (data_pose_scale[j,3,1]-data_pose_scale[j,2,1])**2)
|
||||||
|
jshoulder_align = np.sqrt((jdata_pose_align[3,0]-jdata_pose_align[2,0])**2 + (jdata_pose_align[3,1]-jdata_pose_align[2,1])**2)
|
||||||
|
print(f"\nthe {ibeg + j}-th frame!")
|
||||||
|
print(f"orignal root = {data_pose[j, 1, :]}, scale={jdata_pose_scale[1]}, align = {jdata_pose_align[1]}, mean = {mean_pose[1]}")
|
||||||
|
print(f"orignal shoulder = {jshoulder:.4f}, scale ={jshoulder_scale:.4f} mean shoulder = {mean_shoulder:.4f}")
|
||||||
|
print(f"orignal scale = {v_scale[j]:.4f}, smooth scale={v_scale_smooth[j]:.4f}")
|
||||||
|
|
||||||
|
data_ldmk_align = np.array(data_ldmk_align)
|
||||||
|
data_pose_align = np.array(data_pose_align)
|
||||||
|
|
||||||
|
##################################
|
||||||
|
# STEP 4: save & visualization
|
||||||
|
np.save(ipath_feat_ldmk_align, data_ldmk_align)
|
||||||
|
np.save(ipath_feat_pose_align, data_pose_align)
|
||||||
|
print(f"align ldmk shape={data_ldmk_align.shape}, pose shape = {data_pose_align.shape}--> save to {ipath_feat_ldmk_align}")
|
||||||
|
|
||||||
|
# visualization
|
||||||
|
# images_gt = landmark_to_images(data_ldmk[::10, ...], w=128*5, h=72*5, dpi=100, norm=True, prex="GT") # (N, W, H, 3)
|
||||||
|
# images_pt = landmark_to_images(data_ldmk_align[::10, ...], w=128*5, h=72*5, dpi=100, norm=True, prex="Alignment") # (N, W, H, 3)
|
||||||
|
|
||||||
|
# print("convert to video")
|
||||||
|
# data_motion_mix = np.concatenate([images_gt, images_pt], axis=1) # (N, W, 2H, 3)
|
||||||
|
# data_motion_mix = data_motion_mix.astype(np.uint8)
|
||||||
|
# print("data shape = ", data_motion_mix.shape)
|
||||||
|
|
||||||
|
# fps = 10
|
||||||
|
# N = data_motion_mix.shape[0]
|
||||||
|
# animation = mpy.VideoClip(lambda t: data_motion_mix[int(fps * t + 0.5),...], duration= N // fps)
|
||||||
|
# animation.write_videofile("my_animation.mp4", fps=fps)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import joblib as jl
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
|
def fit_and_standardize(data):
|
||||||
|
|
||||||
|
(nseq, nWind, nfeat) = data.shape
|
||||||
|
|
||||||
|
data_reshape = data.copy().reshape(-1, nfeat)
|
||||||
|
scaler = StandardScaler().fit(data_reshape)
|
||||||
|
data_scale = scaler.transform(data_reshape).reshape(nseq, nWind, nfeat)
|
||||||
|
|
||||||
|
return data_scale, scaler
|
||||||
|
|
||||||
|
def standardize(data, scaler):
|
||||||
|
shape = data.shape
|
||||||
|
|
||||||
|
flat = data.copy().reshape((shape[0]*shape[1], shape[2]))
|
||||||
|
scaled = scaler.transform(flat).reshape(shape)
|
||||||
|
return scaled
|
||||||
|
|
||||||
|
def slice_data(data, window_size, overlap):
|
||||||
|
|
||||||
|
nframes = data.shape[0]
|
||||||
|
overlap_frames = (int)(overlap*window_size)
|
||||||
|
|
||||||
|
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
|
||||||
|
|
||||||
|
if n_sequences>0:
|
||||||
|
|
||||||
|
# extract sequences from the data
|
||||||
|
for i in range(0, n_sequences):
|
||||||
|
frameIdx = (window_size-overlap_frames) * i
|
||||||
|
sliced[i,:,:] = data[frameIdx:frameIdx+window_size,:].copy()
|
||||||
|
else:
|
||||||
|
print("WARNING: data too small for window")
|
||||||
|
|
||||||
|
return sliced
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-no-scale-alignment-2-5') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_align_trim.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 2 # 6
|
||||||
|
nwin_test_secs = 5 # 20
|
||||||
|
window_overlap = 0.2 # 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
|
||||||
|
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_align_trim.npy")
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
# width = info["width"][0] # 1280 or 1920
|
||||||
|
# height = info["height"][0] # 720 or 1080
|
||||||
|
|
||||||
|
# print("width=",width, "height=",height, "-->", ipath_data)
|
||||||
|
|
||||||
|
data_motion = np.load(ipath_feat_motion).reshape(-1, 136) # (nframe, 68, 2)
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
|
||||||
|
|
||||||
|
# data_motion = data_motion / np.array([[[width, height]]])
|
||||||
|
# data_motion = data_motion.reshape(-1, 136)
|
||||||
|
|
||||||
|
# print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
nfeat_motion = data_motion.shape[1]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_train.append(motion_sliced)
|
||||||
|
speech_train.append(speech_sliced)
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_valid.append(motion_sliced)
|
||||||
|
speech_valid.append(speech_sliced)
|
||||||
|
else:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
|
||||||
|
motion_test.append(motion_sliced)
|
||||||
|
speech_test.append(speech_sliced)
|
||||||
|
print(f"sliced motion data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
|
||||||
|
|
||||||
|
# save
|
||||||
|
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
|
||||||
|
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
|
||||||
|
_, motion_scaler = fit_and_standardize(motion_train)
|
||||||
|
_, speech_scaler = fit_and_standardize(speech_train)
|
||||||
|
# print(motion_scaler.mean_ )
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
|
||||||
|
jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
|
||||||
|
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
|
||||||
|
# motion_valid = standardize(motion_valid, motion_scaler)
|
||||||
|
# speech_valid = standardize(speech_valid, speech_scaler)
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
|
||||||
|
# motion_test = standardize(motion_test, motion_scaler)
|
||||||
|
# speech_test = standardize(speech_test, speech_scaler)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
|
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import joblib as jl
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
|
def fit_and_standardize(data):
|
||||||
|
|
||||||
|
(nseq, nWind, nfeat) = data.shape
|
||||||
|
|
||||||
|
data_reshape = data.copy().reshape(-1, nfeat)
|
||||||
|
scaler = StandardScaler().fit(data_reshape)
|
||||||
|
data_scale = scaler.transform(data_reshape).reshape(nseq, nWind, nfeat)
|
||||||
|
|
||||||
|
return data_scale, scaler
|
||||||
|
|
||||||
|
def standardize(data, scaler):
|
||||||
|
shape = data.shape
|
||||||
|
|
||||||
|
flat = data.copy().reshape((shape[0]*shape[1], shape[2]))
|
||||||
|
scaled = scaler.transform(flat).reshape(shape)
|
||||||
|
return scaled
|
||||||
|
|
||||||
|
def slice_data(data, window_size, overlap):
|
||||||
|
|
||||||
|
nframes = data.shape[0]
|
||||||
|
overlap_frames = (int)(overlap*window_size)
|
||||||
|
|
||||||
|
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
|
||||||
|
|
||||||
|
if n_sequences>0:
|
||||||
|
|
||||||
|
# extract sequences from the data
|
||||||
|
for i in range(0, n_sequences):
|
||||||
|
frameIdx = (window_size-overlap_frames) * i
|
||||||
|
sliced[i,:,:] = data[frameIdx:frameIdx+window_size,:].copy()
|
||||||
|
else:
|
||||||
|
print("WARNING: data too small for window")
|
||||||
|
|
||||||
|
return sliced
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-diff') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 2 # 6
|
||||||
|
nwin_test_secs = 5 # 20
|
||||||
|
window_overlap = 0.5 # 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
|
||||||
|
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
|
||||||
|
# load data
|
||||||
|
data_motion = np.load(ipath_feat_motion).reshape(-1, 68, 2) # (nframe, 68, 2)
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
|
||||||
|
|
||||||
|
data_direct = data_motion[1:, :, :] - data_motion[:-1, :, :] # (N-1, 68, 2)
|
||||||
|
data_tmp = data_direct * data_direct # (N-1, 68, 2)
|
||||||
|
data_tmp = np.sqrt(data_tmp[:, :, 0] + data_tmp[:, :, 1]) # (N-1, 68)
|
||||||
|
data_direct = data_direct / (data_tmp.reshape(-1, 68, 1) + 1e-8) # (N-1, 68, 2)
|
||||||
|
data_direct = np.clip(data_direct, -1.0, 1.0) # clips to (-1 ~ 1)
|
||||||
|
|
||||||
|
data_motion = data_motion[:-1, :, :] # (N-1, 68, 2)
|
||||||
|
data_speech = data_speech[:-1, :] # (N-1, 27)
|
||||||
|
|
||||||
|
data_motion = np.concatenate([data_motion, data_direct], axis=2) # (N-1, 68, 4)
|
||||||
|
print(f"data_motion concate shape = {data_motion.shape}")
|
||||||
|
|
||||||
|
data_motion = data_motion.reshape(-1, 272)
|
||||||
|
|
||||||
|
# data_motion = data_motion / np.array([[[width, height]]])
|
||||||
|
# data_motion = data_motion.reshape(-1, 136)
|
||||||
|
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
nfeat_motion = data_motion.shape[1]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_train.append(motion_sliced)
|
||||||
|
speech_train.append(speech_sliced)
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_valid.append(motion_sliced)
|
||||||
|
speech_valid.append(speech_sliced)
|
||||||
|
else:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
|
||||||
|
motion_test.append(motion_sliced)
|
||||||
|
speech_test.append(speech_sliced)
|
||||||
|
print(f"sliced motion data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
|
||||||
|
|
||||||
|
# save
|
||||||
|
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
|
||||||
|
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
|
||||||
|
|
||||||
|
# _, motion_scaler = fit_and_standardize(motion_train)
|
||||||
|
# _, speech_scaler = fit_and_standardize(speech_train)
|
||||||
|
# print(motion_scaler.mean_ )
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
|
||||||
|
# jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
|
||||||
|
# jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
|
||||||
|
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
|
||||||
|
# motion_valid = standardize(motion_valid, motion_scaler)
|
||||||
|
# speech_valid = standardize(speech_valid, speech_scaler)
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
|
||||||
|
# motion_test = standardize(motion_test, motion_scaler)
|
||||||
|
# speech_test = standardize(speech_test, speech_scaler)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
|
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import joblib as jl
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
|
def fit_and_standardize(data):
|
||||||
|
|
||||||
|
(nseq, nWind, nfeat) = data.shape
|
||||||
|
|
||||||
|
data_reshape = data.copy().reshape(-1, nfeat)
|
||||||
|
scaler = StandardScaler().fit(data_reshape)
|
||||||
|
data_scale = scaler.transform(data_reshape).reshape(nseq, nWind, nfeat)
|
||||||
|
|
||||||
|
return data_scale, scaler
|
||||||
|
|
||||||
|
def standardize(data, scaler):
|
||||||
|
shape = data.shape
|
||||||
|
|
||||||
|
flat = data.copy().reshape((shape[0]*shape[1], shape[2]))
|
||||||
|
scaled = scaler.transform(flat).reshape(shape)
|
||||||
|
return scaled
|
||||||
|
|
||||||
|
def slice_data(data, window_size, overlap):
|
||||||
|
|
||||||
|
nframes = data.shape[0]
|
||||||
|
overlap_frames = (int)(overlap*window_size)
|
||||||
|
|
||||||
|
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
|
||||||
|
|
||||||
|
if n_sequences>0:
|
||||||
|
|
||||||
|
# extract sequences from the data
|
||||||
|
for i in range(0, n_sequences):
|
||||||
|
frameIdx = (window_size-overlap_frames) * i
|
||||||
|
sliced[i,:,:] = data[frameIdx:frameIdx+window_size,:].copy()
|
||||||
|
else:
|
||||||
|
print("WARNING: data too small for window")
|
||||||
|
|
||||||
|
return sliced
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
|
||||||
|
path_save = Path('data/obama-landmark-pose-3-5-05') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 3 # 6
|
||||||
|
nwin_test_secs = 5 # 20
|
||||||
|
window_overlap = 0.5 # 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
|
||||||
|
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_ldmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
|
||||||
|
data_ldmk = np.load(ipath_feat_ldmk).reshape(-1, 136) # (nframe, 136)
|
||||||
|
data_pose = np.load(ipath_feat_pos) # (nframe, 3)
|
||||||
|
|
||||||
|
data_motion = np.concatenate([data_ldmk, data_pose], axis=1) # (nframe, 139)
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
|
||||||
|
|
||||||
|
|
||||||
|
# data_motion = data_motion / np.array([[[width, height]]])
|
||||||
|
# data_motion = data_motion.reshape(-1, 136)
|
||||||
|
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
nfeat_motion = data_motion.shape[1]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_train.append(motion_sliced)
|
||||||
|
speech_train.append(speech_sliced)
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_valid.append(motion_sliced)
|
||||||
|
speech_valid.append(speech_sliced)
|
||||||
|
else:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
|
||||||
|
motion_test.append(motion_sliced)
|
||||||
|
speech_test.append(speech_sliced)
|
||||||
|
print(f"sliced motion data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
|
||||||
|
|
||||||
|
# save
|
||||||
|
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
|
||||||
|
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
|
||||||
|
|
||||||
|
# _, motion_scaler = fit_and_standardize(motion_train)
|
||||||
|
# _, speech_scaler = fit_and_standardize(speech_train)
|
||||||
|
# print(motion_scaler.mean_ )
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
|
||||||
|
# jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
|
||||||
|
# jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
|
||||||
|
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
|
||||||
|
# motion_valid = standardize(motion_valid, motion_scaler)
|
||||||
|
# speech_valid = standardize(speech_valid, speech_scaler)
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
|
||||||
|
# motion_test = standardize(motion_test, motion_scaler)
|
||||||
|
# speech_test = standardize(speech_test, speech_scaler)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import joblib as jl
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-landmark-split-6') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if vid not in vid_test: continue
|
||||||
|
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
|
||||||
|
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_6s.npy") # feat_ldmk_trim_norm_split
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim_split_6s.npy") # feat_ldmk_trim_norm_split
|
||||||
|
|
||||||
|
data_motion = np.load(ipath_feat_motion) # (nsplit, 173, 80)
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nsplit, 60, 136)
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_train.append(data_motion)
|
||||||
|
speech_train.append(data_speech)
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
motion_valid.append(data_motion)
|
||||||
|
speech_valid.append(data_speech)
|
||||||
|
|
||||||
|
else:
|
||||||
|
motion_test.append(data_motion)
|
||||||
|
speech_test.append(data_speech)
|
||||||
|
|
||||||
|
|
||||||
|
# # save
|
||||||
|
# motion_train = np.concatenate(motion_train, axis=0) # (10612, 60, 136)
|
||||||
|
# speech_train = np.concatenate(speech_train, axis=0) # (10612, 173, 80)
|
||||||
|
# np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
# np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
|
||||||
|
# print(f"save train data motion({motion_train.shape}), speech ({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
|
||||||
|
# motion_valid = np.concatenate(motion_valid, axis=0) # (350, 60, 136)
|
||||||
|
# speech_valid = np.concatenate(speech_valid, axis=0) # (350, 173, 80)
|
||||||
|
# np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
# np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
|
||||||
|
# print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 60, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 173, 80)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
def slice_data(data, window_size, overlap):
|
||||||
|
|
||||||
|
nframes = data.shape[0]
|
||||||
|
overlap_frames = (int)(overlap*window_size)
|
||||||
|
|
||||||
|
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
|
||||||
|
|
||||||
|
if n_sequences>0:
|
||||||
|
|
||||||
|
# extract sequences from the data
|
||||||
|
for i in range(0, n_sequences):
|
||||||
|
frameIdx = (window_size-overlap_frames) * i
|
||||||
|
sliced[i,:,:] = data[frameIdx:frameIdx+window_size,:].copy()
|
||||||
|
else:
|
||||||
|
print("WARNING: data too small for window")
|
||||||
|
|
||||||
|
return sliced
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-landmark-3-5-05') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 2, 2
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 3 # 6
|
||||||
|
nwin_test_secs = 5 # 20
|
||||||
|
window_overlap = 0.5 # 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
|
||||||
|
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
|
||||||
|
data_motion = np.load(ipath_feat_motion).reshape(-1, 136) # (nframe, 68, 2)
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
|
||||||
|
|
||||||
|
# data_motion = data_motion / np.array([[[width, height]]])
|
||||||
|
# data_motion = data_motion.reshape(-1, 136)
|
||||||
|
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
# nfeat_motion = data_motion.shape[1]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_train.append(motion_sliced)
|
||||||
|
speech_train.append(speech_sliced)
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_valid.append(motion_sliced)
|
||||||
|
speech_valid.append(speech_sliced)
|
||||||
|
else:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
|
||||||
|
motion_test.append(motion_sliced)
|
||||||
|
speech_test.append(speech_sliced)
|
||||||
|
print(f"sliced motion data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
|
||||||
|
|
||||||
|
# save
|
||||||
|
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
|
||||||
|
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
|
||||||
|
|
||||||
|
# _, motion_scaler = fit_and_standardize(motion_train)
|
||||||
|
# _, speech_scaler = fit_and_standardize(speech_train)
|
||||||
|
# print(motion_scaler.mean_ )
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
|
||||||
|
# jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
|
||||||
|
# jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
|
||||||
|
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
|
||||||
|
# motion_valid = standardize(motion_valid, motion_scaler)
|
||||||
|
# speech_valid = standardize(speech_valid, speech_scaler)
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
|
||||||
|
# motion_test = standardize(motion_test, motion_scaler)
|
||||||
|
# speech_test = standardize(speech_test, speech_scaler)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
Whitespace-only changes.
@@ -0,0 +1,75 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# print(f"\n processing {ivideo_name} ... ")
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_coeff = ipath_data.joinpath("DECA_coeff")
|
||||||
|
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
|
||||||
|
|
||||||
|
if ipath_save_exp.exists() and ipath_save_pos.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not ipath_infors.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
|
||||||
|
fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
feat_exp = []
|
||||||
|
feat_pos = []
|
||||||
|
feat_idn = []
|
||||||
|
for j in range(ibeg, iend):
|
||||||
|
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:05d}.json.npy")
|
||||||
|
if not jpath_coeff.exists():
|
||||||
|
break
|
||||||
|
|
||||||
|
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
|
||||||
|
feat_exp.append(data_coeff["exp"])
|
||||||
|
feat_pos.append(data_coeff["pose"])
|
||||||
|
feat_idn.append(data_coeff["shape"])
|
||||||
|
|
||||||
|
# save
|
||||||
|
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
|
||||||
|
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
|
||||||
|
feat_idn = np.array(feat_idn) # (nframe_trim, 100)
|
||||||
|
|
||||||
|
if nframe_trim == feat_idn.shape[0]:
|
||||||
|
np.save(ipath_save_exp, feat_exp)
|
||||||
|
np.save(ipath_save_pos, feat_pos)
|
||||||
|
np.save(ipath_save_idn, feat_idn)
|
||||||
|
print(f"exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape},nframe_trim = {nframe_trim} \n save to -> {ipath_save_exp}") # (nframe, 68, 2)
|
||||||
|
# print(f"idn={feat_idn.shape},nframe_trim = {nframe_trim} \n save to -> {ipath_save_exp}") # (nframe, 68, 2)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 2 # 6, 2
|
||||||
|
overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
for ipath_data in v_dir_videos:
|
||||||
|
ivideo_name = ipath_data.stem
|
||||||
|
|
||||||
|
# print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
ipath_infors = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
ipath_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
|
||||||
|
|
||||||
|
ipath_save = ipath_data.joinpath("audio/feat_DECA_trim_split_2s.npy") # feat_mel_trim_split
|
||||||
|
|
||||||
|
if not ipath_exp.exists() or not ipath_pos.exists() or not ipath_idn.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_exp} or {ipath_pos} or {ipath_idn}" )
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"\n processing {ivideo_name} ... ")
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_infors), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
|
||||||
|
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
|
||||||
|
feat_pos = np.load(ipath_pos) # (nframe_trim, 6)
|
||||||
|
feat_3dmm = np.concatenate([feat_idn, feat_exp, feat_pos], axis=1)
|
||||||
|
|
||||||
|
|
||||||
|
if nframe_trim != feat_3dmm.shape[0]:
|
||||||
|
print(f"ERROR: nframe_trim = {nframe_trim} != feat_3dmm len {feat_3dmm.shape[0]}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# split
|
||||||
|
nsize_split = int( nwin_train_secs * fps )
|
||||||
|
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
|
||||||
|
|
||||||
|
feat_3dmm = torch.from_numpy(feat_3dmm).float()
|
||||||
|
feat_3dmm2 = feat_3dmm.unfold(dimension=0, size=nsize_split, step=nstep_split) # (nframe_trim//30, 136, 30)
|
||||||
|
feat_3dmm2 = feat_3dmm2.permute(0, 2, 1) # (nsplits, nsteps, 136)
|
||||||
|
|
||||||
|
print(f"data feat_3dmm unfold = {feat_3dmm2.shape}")
|
||||||
|
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
|
||||||
|
print(f"ldmk ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {(nframe_trim - nsize_split) // nstep_split + 1}")
|
||||||
|
|
||||||
|
# save
|
||||||
|
np.save(ipath_save, feat_3dmm2) # (nsplit, 60, 136)
|
||||||
|
print(f"feat_3dmm={feat_3dmm.shape}, feat_3dmm2={feat_3dmm2.shape}, save to -> {ipath_save}") # (nframe, 68, 2)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
def interpolate_features(features, input_rate, output_rate, output_len=None):
|
||||||
|
num_features = features.shape[1]
|
||||||
|
input_len = features.shape[0]
|
||||||
|
seq_len = input_len / float(input_rate)
|
||||||
|
|
||||||
|
if output_len is None:
|
||||||
|
output_len = int(seq_len * output_rate)
|
||||||
|
|
||||||
|
input_timestamps = np.arange(input_len) / float(input_rate)
|
||||||
|
output_timestamps = np.arange(output_len) / float(output_rate)
|
||||||
|
output_features = np.zeros((output_len, num_features))
|
||||||
|
for feat in range(num_features):
|
||||||
|
output_features[:, feat] = np.interp(output_timestamps,
|
||||||
|
input_timestamps,
|
||||||
|
features[:, feat])
|
||||||
|
return output_features
|
||||||
|
|
||||||
|
|
||||||
|
def slice_data(data, window_size, overlap):
|
||||||
|
|
||||||
|
nframes = data.shape[0]
|
||||||
|
overlap_frames = (int)(overlap*window_size)
|
||||||
|
|
||||||
|
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
|
||||||
|
|
||||||
|
if data.ndim == 2:
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
|
||||||
|
else:
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1], data.shape[2])).astype(np.float32)
|
||||||
|
|
||||||
|
if n_sequences>0:
|
||||||
|
# extract sequences from the data
|
||||||
|
for i in range(0, n_sequences):
|
||||||
|
frameIdx = (window_size-overlap_frames) * i
|
||||||
|
sliced[i] = data[frameIdx:frameIdx+window_size].copy()
|
||||||
|
else:
|
||||||
|
print("WARNING: data too small for window")
|
||||||
|
|
||||||
|
return sliced
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-dsv1-deca-5-10-08-mini8k') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 1, 1
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 5 # 6
|
||||||
|
nwin_test_secs = 10 # 20
|
||||||
|
window_overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
nwin_train = nwin_train_secs * fps # 3 * 30 = 90
|
||||||
|
nwin_test = nwin_test_secs * fps # 5 * 30 = 150
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i >= 50: continue
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
# ipath_feat_speech = ipath_data.joinpath("audio/feat_deepspeech010_trim.npy")
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_deepspeech_v1_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
if not ipath_feat_speech.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
fps = info["fps"]
|
||||||
|
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# laod motion & speech data
|
||||||
|
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
|
||||||
|
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
|
||||||
|
pos_head = data_pos[:, :3] # (nframe, 3)
|
||||||
|
pos_lips = data_pos[:, 3:] # (nframe, 3)
|
||||||
|
|
||||||
|
data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53) --> fps=30
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nframe*2, 16, 29) --> fps=60
|
||||||
|
print(f"motion = {data_motion.shape}, speech = {data_speech.shape}")
|
||||||
|
|
||||||
|
# # downsampling data_speech, 60fps --> fps
|
||||||
|
# (nseq, nwind, nfeat) = data_speech.shape # (nframe*2, 16, 29)
|
||||||
|
# data_speech = data_speech.reshape(nseq, -1) # (nframe*2, 16x29)
|
||||||
|
# data_speech = interpolate_features(data_speech, 60, fps, output_len=data_motion.shape[0])
|
||||||
|
# data_speech = data_speech.reshape(-1, nwind, nfeat)
|
||||||
|
# print(f"after motion = {data_motion.shape}, speech = {data_speech.shape}")
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_train.append(motion_sliced)
|
||||||
|
speech_train.append(speech_sliced)
|
||||||
|
|
||||||
|
if vid in vid_valid:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_valid.append(motion_sliced)
|
||||||
|
speech_valid.append(speech_sliced)
|
||||||
|
|
||||||
|
if vid in vid_test:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
|
||||||
|
motion_test.append(motion_sliced)
|
||||||
|
speech_test.append(speech_sliced)
|
||||||
|
|
||||||
|
print(f"sliced motion = {motion_sliced.shape}, speech = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)}) \n")
|
||||||
|
|
||||||
|
# save
|
||||||
|
motion_train = np.concatenate(motion_train, axis=0) # (nframe, 180, 136)
|
||||||
|
speech_train = np.concatenate(speech_train, axis=0) # (nframe, 180, 27)
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
|
||||||
|
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
|
||||||
|
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}\n")
|
||||||
|
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
def slice_data(data, window_size, overlap):
|
||||||
|
|
||||||
|
nframes = data.shape[0]
|
||||||
|
overlap_frames = (int)(overlap*window_size)
|
||||||
|
|
||||||
|
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
|
||||||
|
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
|
||||||
|
|
||||||
|
if n_sequences>0:
|
||||||
|
|
||||||
|
# extract sequences from the data
|
||||||
|
for i in range(0, n_sequences):
|
||||||
|
frameIdx = (window_size-overlap_frames) * i
|
||||||
|
sliced[i,:,:] = data[frameIdx:frameIdx+window_size,:].copy()
|
||||||
|
else:
|
||||||
|
print("WARNING: data too small for window")
|
||||||
|
|
||||||
|
return sliced
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-deca-5-10-08') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 1, 1
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
# set windows
|
||||||
|
nwin_train_secs = 5 # 6
|
||||||
|
nwin_test_secs = 10 # 20
|
||||||
|
window_overlap = 0.8
|
||||||
|
fps = 30
|
||||||
|
|
||||||
|
nwin_train = nwin_train_secs * fps # 3 * 30 = 90
|
||||||
|
nwin_test = nwin_test_secs * fps # 5 * 30 = 150
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
motion_train, motion_valid, motion_test = [], [], []
|
||||||
|
speech_train, speech_valid, speech_test = [], [], []
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
# if i >= 5: continue
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# laod motion & speech data
|
||||||
|
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
|
||||||
|
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
|
||||||
|
pos_head = data_pos[:, :3] # (nframe, 3)
|
||||||
|
pos_lips = data_pos[:, 3:] # (nframe, 3)
|
||||||
|
|
||||||
|
data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53)
|
||||||
|
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
|
||||||
|
|
||||||
|
print(f"data_exp data = {data_exp.shape},data_pos = {data_pos.shape}, \n motion = {data_motion.shape}, speech = {data_speech.shape}")
|
||||||
|
assert data_exp.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_train.append(motion_sliced)
|
||||||
|
speech_train.append(speech_sliced)
|
||||||
|
|
||||||
|
if vid in vid_valid:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
|
||||||
|
motion_valid.append(motion_sliced)
|
||||||
|
speech_valid.append(speech_sliced)
|
||||||
|
|
||||||
|
if vid in vid_test:
|
||||||
|
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
|
||||||
|
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
|
||||||
|
motion_test.append(motion_sliced)
|
||||||
|
speech_test.append(speech_sliced)
|
||||||
|
|
||||||
|
print(f"sliced motion data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
|
||||||
|
|
||||||
|
# save
|
||||||
|
motion_train = np.concatenate(motion_train, axis=0) # (nframe, 180, 136)
|
||||||
|
speech_train = np.concatenate(speech_train, axis=0) # (nframe, 180, 27)
|
||||||
|
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
|
||||||
|
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
|
||||||
|
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
|
||||||
|
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
|
||||||
|
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
|
||||||
|
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
|
||||||
|
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
|
||||||
|
|
||||||
|
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
|
||||||
|
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
|
||||||
|
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
|
||||||
|
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
|
||||||
|
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
|
||||||
|
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import librosa
|
||||||
|
import numpy as np
|
||||||
|
from pathlib2 import Path
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
|
||||||
|
path_save = Path('data/obama-deca-mel') # processing
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
|
||||||
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
|
||||||
|
vids = [ipath.stem for ipath in v_dir_videos]
|
||||||
|
|
||||||
|
nv_total = len(v_dir_videos)
|
||||||
|
nv_valid, nv_test = 1, 1
|
||||||
|
nv_train = nv_total - (nv_valid + nv_test)
|
||||||
|
|
||||||
|
vid_test = vids[:nv_test]
|
||||||
|
vid_valid = vids[nv_test:nv_test+nv_valid]
|
||||||
|
vid_train = vids[nv_test+nv_valid:]
|
||||||
|
print("vid_test = ", vid_test)
|
||||||
|
|
||||||
|
|
||||||
|
# for each video
|
||||||
|
data_train, data_valid, data_test = {}, {}, {}
|
||||||
|
|
||||||
|
for i, ipath_data in enumerate(v_dir_videos):
|
||||||
|
vid = ipath_data.stem
|
||||||
|
|
||||||
|
if i % 50 == 0:
|
||||||
|
print(f"\n processing the {i}-th video {vid} ... ")
|
||||||
|
|
||||||
|
ipath_info = ipath_data.joinpath("video/info.json")
|
||||||
|
ipath_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
|
||||||
|
ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
|
||||||
|
ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if not ipath_speech.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_speech}" )
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not ipath_exp.exists() or not ipath_pos.exists():
|
||||||
|
print(f"ERROR: NOT Exist {ipath_pos} or {ipath_exp}" )
|
||||||
|
continue
|
||||||
|
|
||||||
|
# check existing
|
||||||
|
if not ipath_speech.exists() or not ipath_info.exists():
|
||||||
|
msg = "ERROR: NOT exsiting "
|
||||||
|
if not ipath_info.exists():
|
||||||
|
msg += f"\n\t {ipath_info} "
|
||||||
|
if not ipath_speech.exists():
|
||||||
|
msg += f"\n\t {ipath_speech} "
|
||||||
|
|
||||||
|
print(msg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load video info
|
||||||
|
with open(str(ipath_info), "r") as f:
|
||||||
|
info = json.load(f)
|
||||||
|
width = info["width"][0] # 1280 or 1920
|
||||||
|
height = info["height"][0] # 720 or 1080
|
||||||
|
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
|
||||||
|
|
||||||
|
# fps = info["fps"]
|
||||||
|
if len(info["active_frames"]) == 2:
|
||||||
|
ibeg = info["active_frames"][0]
|
||||||
|
iend = info["active_frames"][1]
|
||||||
|
nframe_trim = iend - ibeg
|
||||||
|
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
|
||||||
|
else:
|
||||||
|
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# load data
|
||||||
|
# feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
|
||||||
|
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
|
||||||
|
feat_pos = np.load(ipath_pos) # (nframe_trim, 6) # (N, 6)
|
||||||
|
data_motion = np.concatenate([feat_exp, feat_pos[:, 3:6]], axis=1) # (N, 53)
|
||||||
|
data_speech = np.load(ipath_speech) # (M, 80) please note that M != N
|
||||||
|
|
||||||
|
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
|
||||||
|
# assert data_motion.shape[0] == data_speech.shape[0]
|
||||||
|
|
||||||
|
if vid in vid_train:
|
||||||
|
data_train[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech,
|
||||||
|
}
|
||||||
|
|
||||||
|
elif vid in vid_valid:
|
||||||
|
data_valid[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech,
|
||||||
|
}
|
||||||
|
|
||||||
|
else:
|
||||||
|
data_test[vid] = {
|
||||||
|
"W": width, "H": height, "FPS": info["fps"],
|
||||||
|
"nframe": nframe_trim, "trim": [ibeg, iend],
|
||||||
|
"data_motion": data_motion,
|
||||||
|
"data_speech": data_speech,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
|
||||||
|
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
|
||||||
|
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
|
||||||
|
print(f"save data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)}) --> {path_save}")
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import moviepy
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from moviepy.editor import *
|
||||||
|
|
||||||
|
STEP_VIDEO = False
|
||||||
|
STEP_CONCATE = True
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
video_name = "test_video"
|
||||||
|
path_root = Path("/mnt/data/CODE/Audio2Expression")
|
||||||
|
#path_data = path_root.joinpath(f"data/processing/{video_name}")
|
||||||
|
path_data = path_root.joinpath(f"data/processing/{video_name}/result-weight-3000")
|
||||||
|
|
||||||
|
# # to video
|
||||||
|
# if STEP_VIDEO:
|
||||||
|
# path_image = path_data.joinpath("frames_crop")
|
||||||
|
# path_image_save = path_data.joinpath("images.mp4")
|
||||||
|
# clip_image = ImageSequenceClip(path_image, fps=25, load_images=True)
|
||||||
|
# clip_image.write_videofile(str(path_image_save), fps=25)
|
||||||
|
|
||||||
|
# path_frame = path_data.joinpath("render")
|
||||||
|
# path_frame_save = path_data.joinpath("render.mp4")
|
||||||
|
# clip_render = ImageSequenceClip(path_frame, fps=25, load_images=True)
|
||||||
|
# clip_render.write_videofile(str(path_frame_save), fps=25)
|
||||||
|
|
||||||
|
# path_frame = path_data.joinpath("render_pt")
|
||||||
|
# path_frame_save = path_data.joinpath("render_pt.mp4")
|
||||||
|
# clip_render_pt = ImageSequenceClip(path_frame, fps=25, load_images=True)
|
||||||
|
# clip_render_pt.write_videofile(str(path_frame_save), fps=25)
|
||||||
|
|
||||||
|
# path_frame = path_data.joinpath("render_pt_fix_idn")
|
||||||
|
# path_frame_save = path_data.joinpath("render_pt_fix_idn.mp4")
|
||||||
|
# clip_render_pt2 = ImageSequenceClip(path_frame, fps=25, load_images=True)
|
||||||
|
# clip_render_pt2.write_videofile(str(path_frame_save), fps=25)
|
||||||
|
|
||||||
|
|
||||||
|
# concate
|
||||||
|
if STEP_CONCATE:
|
||||||
|
|
||||||
|
# image
|
||||||
|
clip_image = VideoFileClip(str(path_data.joinpath("images.mp4"))).margin(10)
|
||||||
|
clip_text = TextClip("Crop Image", fontsize = 14, color = 'white', stroke_width=3)
|
||||||
|
clip_text = clip_text.set_pos((0.4, 0.9), relative=True).set_duration(clip_image.duration)
|
||||||
|
clip_image = CompositeVideoClip([clip_image, clip_text])
|
||||||
|
|
||||||
|
# render
|
||||||
|
clip_render = VideoFileClip(str(path_data.joinpath("render.mp4"))).margin(10)
|
||||||
|
clip_text = TextClip("Render GT", fontsize = 14, color = 'white', stroke_width=3)
|
||||||
|
clip_text = clip_text.set_pos((0.4,0.9), relative=True).set_duration(clip_render.duration)
|
||||||
|
clip_render = CompositeVideoClip([clip_render, clip_text])
|
||||||
|
|
||||||
|
# render with specific identiy
|
||||||
|
clip_render2 = VideoFileClip(str(path_data.joinpath("render_pt.mp4"))).margin(10)
|
||||||
|
clip_text = TextClip("Render PT fix identity", fontsize = 14, color = 'white', stroke_width=3)
|
||||||
|
clip_text = clip_text.set_pos((0.2,0.9), relative=True).set_duration(clip_render2.duration)
|
||||||
|
clip_render2 = CompositeVideoClip([clip_render2, clip_text])
|
||||||
|
|
||||||
|
# # render with specific identiy
|
||||||
|
# clip_render3 = VideoFileClip(str(path_data.joinpath("render_pt_fix_idn.mp4"))).margin(10)
|
||||||
|
# # clip_text = TextClip("Render PT with fixed identity", fontsize = 14, color = 'red')
|
||||||
|
# # clip_text = clip_text.set_pos("center", "top").set_duration(clip_render3.duration)
|
||||||
|
# # clip_render3 = CompositeVideoClip([clip_render3, clip_text])
|
||||||
|
|
||||||
|
|
||||||
|
# audio
|
||||||
|
path_audio = path_data.joinpath("../audio/test_video.wav")
|
||||||
|
clip_audio = AudioFileClip(str(path_audio))
|
||||||
|
|
||||||
|
# concate
|
||||||
|
# concate_clips = clips_array([[clip_image, clip_render],
|
||||||
|
# [clip_render2, clip_render3]])
|
||||||
|
concate_clips = clips_array([[clip_image, clip_render, clip_render2]])
|
||||||
|
|
||||||
|
concate_clips = concate_clips.set_audio(clip_audio)
|
||||||
|
|
||||||
|
# save
|
||||||
|
path_concate_save = path_data.joinpath("concate4.mp4")
|
||||||
|
#concate_clips = concate_clips.resize(width=720)
|
||||||
|
|
||||||
|
concate_clips.write_videofile(str(path_concate_save), fps=25)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import cv2
|
||||||
|
|
||||||
|
import math
|
||||||
|
import numpy as np
|
||||||
|
from pathlib import Path
|
||||||
|
from PIL import Image
|
||||||
|
import librosa
|
||||||
|
import python_speech_features
|
||||||
|
|
||||||
|
from reconstruction import Reconstruction
|
||||||
|
from face_alignment import FaceAlignment, LandmarksType
|
||||||
|
|
||||||
|
STEP_EXTRACT_FRAMES = False
|
||||||
|
STEP_EXTRACT_LANDMK = False
|
||||||
|
STEP_EXTRACT_MFCC = True
|
||||||
|
STEP_EXTRACT_3DMM = True
|
||||||
|
|
||||||
|
def select_ldmk(ladmks):
|
||||||
|
|
||||||
|
ladmks = np.array(ladmks)
|
||||||
|
area = []
|
||||||
|
for i in range(ladmks.shape[0]):
|
||||||
|
lands = ladmks[i, ...]
|
||||||
|
|
||||||
|
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
|
||||||
|
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
|
||||||
|
area.append((xmax - xmin) * (ymax-ymin))
|
||||||
|
|
||||||
|
|
||||||
|
print("area = ", area, "select = ", np.argmax(area))
|
||||||
|
return ladmks[np.argmax(area), :, :]
|
||||||
|
|
||||||
|
def splited_by_windows(data, wind_stride, wind_length, padding=True):
|
||||||
|
"""
|
||||||
|
data: seq_len1 x dim1
|
||||||
|
return: seq_len2 x wind_length x dim1
|
||||||
|
where seq_len2 = (L + 2p - k) // wind_stride + 1
|
||||||
|
"""
|
||||||
|
|
||||||
|
seq_len1, dim1 = data.shape
|
||||||
|
|
||||||
|
seq_len2 = seq_len1 // wind_stride + 1
|
||||||
|
|
||||||
|
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
|
||||||
|
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
|
||||||
|
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
|
||||||
|
|
||||||
|
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
|
||||||
|
|
||||||
|
for i in range(seq_len2):
|
||||||
|
ibeg = i * wind_stride
|
||||||
|
iend = i * wind_stride + wind_length
|
||||||
|
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
|
||||||
|
|
||||||
|
return data_output
|
||||||
|
|
||||||
|
def get_rect(lands):
|
||||||
|
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
|
||||||
|
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
|
||||||
|
|
||||||
|
length = 1.2 * math.sqrt((xmax - xmin) * (xmax - xmin) + (ymax - ymin) * (ymax - ymin))
|
||||||
|
left = (xmax + xmin) / 2 - length / 2
|
||||||
|
top = (ymax + ymin) / 2 - length / 2
|
||||||
|
rect = np.array([left, top, length], dtype=np.float)
|
||||||
|
|
||||||
|
return rect
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_root = Path("/mnt/data/CODE/Audio2Expression")
|
||||||
|
path_data = path_root.joinpath("data")
|
||||||
|
|
||||||
|
path_audio = path_data.joinpath('input/test_video.wav') # 03Fsi1201.wav,5_00006,03Fsi1201
|
||||||
|
path_video = path_data.joinpath('input/test_video.mp4') # 31.mp4 ken
|
||||||
|
|
||||||
|
video_name = path_video.stem
|
||||||
|
audio_name = path_audio.stem
|
||||||
|
|
||||||
|
path_save = path_data.joinpath(f"processing/{video_name}")
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# ======================================
|
||||||
|
# STEP 1: extract frames
|
||||||
|
# ======================================
|
||||||
|
path_frames = path_save.joinpath("frames")
|
||||||
|
path_frames.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
if STEP_EXTRACT_FRAMES:
|
||||||
|
print("STEP 1: extract frames...")
|
||||||
|
count = 0
|
||||||
|
cap = cv2.VideoCapture(str(path_video))
|
||||||
|
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
while True:
|
||||||
|
success, image = cap.read()
|
||||||
|
if not success:
|
||||||
|
break
|
||||||
|
|
||||||
|
ipath_frame = path_frames.joinpath(f"frame-{count:04d}.jpg")
|
||||||
|
cv2.imwrite(str(ipath_frame), image)
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
print(f"--> Extract video, have {length}/{count} frames, {path_video}")
|
||||||
|
|
||||||
|
|
||||||
|
# ======================================
|
||||||
|
# STEP 2: extract landmark
|
||||||
|
# ======================================
|
||||||
|
path_landmk = path_save.joinpath("landmk")
|
||||||
|
path_landmk.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
if STEP_EXTRACT_LANDMK:
|
||||||
|
print("STEP 2: extract landmark...")
|
||||||
|
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
|
||||||
|
v_path_frames = sorted(path_frames.glob("*.jpg"))
|
||||||
|
|
||||||
|
for k, kpath_frame in enumerate(v_path_frames):
|
||||||
|
frame_id = int(kpath_frame.stem[-4:])
|
||||||
|
ipath_landmk_frame = path_landmk.joinpath(f"frame-{frame_id:04d}.txt")
|
||||||
|
|
||||||
|
if not ipath_landmk_frame.exists():
|
||||||
|
|
||||||
|
# detect image
|
||||||
|
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
|
||||||
|
|
||||||
|
ldmk_pred = model.get_landmarks(np.array(image))
|
||||||
|
if ldmk_pred is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# select the first one or the bigger one face
|
||||||
|
if len(ldmk_pred) > 1:
|
||||||
|
ldmk_pred = select_ldmk(ldmk_pred)
|
||||||
|
else:
|
||||||
|
ldmk_pred = ldmk_pred[0]
|
||||||
|
|
||||||
|
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
|
||||||
|
|
||||||
|
# ======================================
|
||||||
|
# STEP 3: extract mfcc
|
||||||
|
# ======================================
|
||||||
|
if STEP_EXTRACT_MFCC:
|
||||||
|
print("STEP 3: extract mfcc...")
|
||||||
|
path_save_audio = path_save.joinpath("audio")
|
||||||
|
path_save_audio.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
path_feat = path_save_audio.joinpath("mfcc_feat.npy")
|
||||||
|
path_feat_align = path_save_audio.joinpath("mfcc_feat_align.npy")
|
||||||
|
|
||||||
|
# extarct mfcc feature
|
||||||
|
audio, sr = librosa.load(str(path_audio), sr=16000) # 16000, (69760, )
|
||||||
|
mfcc = python_speech_features.mfcc(audio, 16000, winstep=0.01) # seqlen1 x 13
|
||||||
|
np.save(path_feat, mfcc)
|
||||||
|
|
||||||
|
|
||||||
|
# splited by windows (to fit video frame with fps 25)
|
||||||
|
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
|
||||||
|
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
|
||||||
|
## seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
|
||||||
|
mfcc_align = splited_by_windows(mfcc, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
|
||||||
|
np.save(path_feat_align, mfcc_align)
|
||||||
|
|
||||||
|
print(f"audio shape={audio.shape}, mfcc shape={mfcc.shape}, mfcc_align = {mfcc_align.shape} duration={len(audio) / sr}")
|
||||||
|
|
||||||
|
|
||||||
|
# ======================================
|
||||||
|
# STEP 4: extract 3dmm
|
||||||
|
# ======================================
|
||||||
|
path_coeffs = path_save.joinpath("coeff")
|
||||||
|
path_coeffs.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
if STEP_EXTRACT_3DMM:
|
||||||
|
print("STEP 4: extract 3dmm...")
|
||||||
|
model = Reconstruction()
|
||||||
|
|
||||||
|
vpath_frames = sorted(path_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
|
||||||
|
for ik, ipath_frame in enumerate(vpath_frames):
|
||||||
|
fid = int(ipath_frame.stem[-4:])
|
||||||
|
ipath_ladmk = path_landmk.joinpath(f"frame-{fid:04d}.txt") # get landmark path
|
||||||
|
if not ipath_ladmk.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# read image and landmark
|
||||||
|
image = Image.open(str(ipath_frame)).convert('RGB') # (h, w, 3)
|
||||||
|
ladmk = np.loadtxt(ipath_ladmk, dtype=int) # (68, 2)
|
||||||
|
bbox = get_rect(ladmk)
|
||||||
|
|
||||||
|
# reconstruction
|
||||||
|
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=path_save)
|
||||||
|
|
||||||
|
if ik % 100 == 99:
|
||||||
|
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
import moviepy.editor as mpy
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
path_TalkingGlow1 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100/video_25fps')
|
||||||
|
path_TalkingGlow2 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100-1/video_25fps')
|
||||||
|
path_TalkingGlow3 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100-2/video_25fps')
|
||||||
|
path_TalkingGlow4 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100-3/video_25fps')
|
||||||
|
|
||||||
|
path_audio = Path('/mnt/data/CODE/Audio2Expression/data/paper_gt/audio_wav')
|
||||||
|
|
||||||
|
path_save = Path('/mnt/data/CODE/Audio2Expression/data/paper/stack_video_diverse')
|
||||||
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
for i in range(43):
|
||||||
|
clip_A = mpy.VideoFileClip(str(path_TalkingGlow1.joinpath(f"clips_{i:03d}.mp4")))
|
||||||
|
clip_B = mpy.VideoFileClip(str(path_TalkingGlow2.joinpath(f"clips_{i:03d}.mp4")))
|
||||||
|
clip_C = mpy.VideoFileClip(str(path_TalkingGlow3.joinpath(f"clips_{i:03d}.mp4")))
|
||||||
|
clip_D = mpy.VideoFileClip(str(path_TalkingGlow4.joinpath(f"clips_{i:03d}.mp4")))
|
||||||
|
|
||||||
|
audio = mpy.AudioFileClip(str(path_audio.joinpath(f"clips_{i:03d}.wav")))
|
||||||
|
|
||||||
|
# align to clipGT
|
||||||
|
duration = clip_A.duration
|
||||||
|
clip_B = clip_B.set_duration(duration)
|
||||||
|
clip_C = clip_C.set_duration(duration)
|
||||||
|
clip_D = clip_D.set_duration(duration)
|
||||||
|
audio = audio.set_duration(duration)
|
||||||
|
|
||||||
|
# stack
|
||||||
|
video = mpy.clips_array([[clip_A, clip_B, clip_C, clip_D]])
|
||||||
|
video = video.set_audio(audio) # audd audio
|
||||||
|
|
||||||
|
# save
|
||||||
|
ipath_save = path_save.joinpath(f"clips_{i:03d}.mp4")
|
||||||
|
video.write_videofile(str(ipath_save), fps=25, logger=None)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Whitespace-only changes.
+310
@@ -0,0 +1,310 @@
|
|||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from easydict import EasyDict as edict
|
||||||
|
|
||||||
|
config = edict()
|
||||||
|
|
||||||
|
config.OUTPUT_DIR = ''
|
||||||
|
config.LOG_DIR = ''
|
||||||
|
config.LOG_PREFIX = ''
|
||||||
|
config.GPUS = '1'
|
||||||
|
config.WORKERS = 8
|
||||||
|
config.DEBUG = False
|
||||||
|
|
||||||
|
# pxxxx
|
||||||
|
config.isTrain = True
|
||||||
|
config.preprocess = ''
|
||||||
|
config.verbose = True
|
||||||
|
|
||||||
|
# frequence
|
||||||
|
config.FREQ = edict()
|
||||||
|
config.FREQ.batch_save = 20
|
||||||
|
config.FREQ.batch_print = 1
|
||||||
|
config.FREQ.batch_display = 100
|
||||||
|
config.FREQ.batch_test = 100000
|
||||||
|
|
||||||
|
config.FREQ.epoch_save = 1
|
||||||
|
config.FREQ.epoch_print = 1
|
||||||
|
config.FREQ.epoch_display = 10
|
||||||
|
config.FREQ.epoch_valid = 1
|
||||||
|
config.FREQ.epoch_test = 1
|
||||||
|
|
||||||
|
config.FREQ.update_html = 1
|
||||||
|
|
||||||
|
|
||||||
|
# visual
|
||||||
|
config.VISUAL = edict()
|
||||||
|
config.VISUAL.use_HTML = True
|
||||||
|
config.VISUAL.use_visdom = True
|
||||||
|
|
||||||
|
config.VISUAL.vsdm_id = 0
|
||||||
|
config.VISUAL.vsdm_wsize = 256
|
||||||
|
config.VISUAL.vsdm_port = 8098
|
||||||
|
config.VISUAL.vsdm_ncol = 3
|
||||||
|
config.VISUAL.vsdm_server = "http://localhost"
|
||||||
|
config.VISUAL.vsdm_env = "main-2"
|
||||||
|
|
||||||
|
# cudnn related params
|
||||||
|
config.CUDNN = edict()
|
||||||
|
config.CUDNN.benchmark = True
|
||||||
|
config.CUDNN.deterministic = True
|
||||||
|
config.CUDNN.enable = True
|
||||||
|
|
||||||
|
|
||||||
|
##########################
|
||||||
|
# model related params
|
||||||
|
config.MODEL = edict()
|
||||||
|
config.MODEL.name = "LandmarkAE"
|
||||||
|
config.MODEL.name_netG = "MLP"
|
||||||
|
config.MODEL.dropout = 0.1
|
||||||
|
|
||||||
|
# load & init model
|
||||||
|
config.MODEL.pretrain = False
|
||||||
|
config.MODEL.path_pretrained = ""
|
||||||
|
config.MODEL.path_checkpoint = ""
|
||||||
|
config.MODEL.load_epoch = 0
|
||||||
|
|
||||||
|
# for MOGLOW
|
||||||
|
config.MODEL.dim_motion = 0
|
||||||
|
config.MODEL.dim_speech = 0
|
||||||
|
config.MODEL.dim_hidden = 0
|
||||||
|
|
||||||
|
config.MODEL.n_lookprevs_motion = 3
|
||||||
|
config.MODEL.n_lookprevs_speech = 3
|
||||||
|
|
||||||
|
config.MODEL.n_lookahead_motion = 7
|
||||||
|
config.MODEL.n_lookahead_speech = 7
|
||||||
|
|
||||||
|
config.MODEL.n_layer_lstm = 2
|
||||||
|
|
||||||
|
|
||||||
|
# # for wavenet
|
||||||
|
# config.MODEL.n_early_every = 0
|
||||||
|
# config.MODEL.n_early_size = 0
|
||||||
|
# config.MODEL.n_layer_wave = 0
|
||||||
|
# config.MODEL.kernel_size = 0
|
||||||
|
|
||||||
|
# # for transformer
|
||||||
|
# config.MODEL.n_src_vocab = 0
|
||||||
|
# config.MODEL.n_tgt_vocab = 0
|
||||||
|
# config.MODEL.src_pad_idx = 0
|
||||||
|
# config.MODEL.tgt_pad_idx = 0
|
||||||
|
# config.MODEL.d_input = 68*2
|
||||||
|
# config.MODEL.d_output = 68*2
|
||||||
|
# config.MODEL.d_embed = 512
|
||||||
|
# config.MODEL.d_model = 512
|
||||||
|
# config.MODEL.d_latent = 256
|
||||||
|
# config.MODEL.d_inner = 2048
|
||||||
|
# config.MODEL.d_k = 64
|
||||||
|
# config.MODEL.d_v = 64
|
||||||
|
# config.MODEL.n_head = 8
|
||||||
|
# config.MODEL.n_layers = 6
|
||||||
|
# config.MODEL.max_position = 200
|
||||||
|
|
||||||
|
# In section 3.4 of paper "Attention Is All You Need", there is such detail:
|
||||||
|
# "In our model, we share the same weight matrix between the two
|
||||||
|
# embedding layers and the pre-softmax linear transformation...
|
||||||
|
# In the embedding layers, we multiply those weights by \sqrt{d_model}".
|
||||||
|
# Options here:
|
||||||
|
# 'emb': multiply \sqrt{d_model} to embedding output
|
||||||
|
# 'prj': multiply (\sqrt{d_model} ^ -1) to linear projection output
|
||||||
|
# 'none': no multiplication
|
||||||
|
# config.MODEL.scale_emb_or_prj = 'prj'
|
||||||
|
# config.MODEL.scale_emb = False
|
||||||
|
# config.MODEL.trg_emb_prj_weight_sharing = True
|
||||||
|
# config.MODEL.emb_src_trg_weight_sharing = True
|
||||||
|
|
||||||
|
|
||||||
|
##########################
|
||||||
|
# dataset related params
|
||||||
|
config.DATASET = edict()
|
||||||
|
config.DATASET.name = 'ravdess'
|
||||||
|
config.DATASET.type = '' # "clips" | "frame" | "none"
|
||||||
|
config.DATASET.root = "../data/"
|
||||||
|
|
||||||
|
# from dataset iteratiion
|
||||||
|
config.DATASET.nwind_second_train = 0
|
||||||
|
config.DATASET.nwind_second_valid = 0
|
||||||
|
config.DATASET.nwind_second_test = 0
|
||||||
|
|
||||||
|
# for data smooth
|
||||||
|
config.DATASET.filter = '' # "gaussian" | "savgol"
|
||||||
|
|
||||||
|
# augmentation
|
||||||
|
config.DATASET.flip = False
|
||||||
|
|
||||||
|
#############################
|
||||||
|
# Trainning related parameter
|
||||||
|
config.TRAIN = edict()
|
||||||
|
|
||||||
|
config.TRAIN.apply_validation = False
|
||||||
|
config.TRAIN.apply_testing = False
|
||||||
|
config.TRAIN.apply_update_parameters = False
|
||||||
|
|
||||||
|
config.TRAIN.lr = 0.001
|
||||||
|
config.TRAIN.lr_step = [50, 100]
|
||||||
|
config.TRAIN.lr_factor = 0.1
|
||||||
|
config.TRAIN.beta1 = 0.5
|
||||||
|
config.TRAIN.beta2 = 0.999
|
||||||
|
config.TRAIN.lambda1 = 100
|
||||||
|
config.TRAIN.lr_policy = ''
|
||||||
|
config.TRAIN.lr_decay_iters = 0
|
||||||
|
config.TRAIN.lr_milestones = [10,100,1000]
|
||||||
|
config.TRAIN.grad_clip_norm = False
|
||||||
|
config.TRAIN.max_grad_clip = 0
|
||||||
|
config.TRAIN.max_grad_norm = 0
|
||||||
|
|
||||||
|
# for motionVAE
|
||||||
|
config.TRAIN.p_use_pt = 0.5
|
||||||
|
|
||||||
|
config.TRAIN.reset_lr = False
|
||||||
|
config.TRAIN.resume = False
|
||||||
|
config.TRAIN.resume_suffix = ""
|
||||||
|
config.TRAIN.checkpoints = ""
|
||||||
|
config.TRAIN.batch_size = 24
|
||||||
|
config.TRAIN.shuffle = True
|
||||||
|
config.TRAIN.epoch_begin = 0
|
||||||
|
config.TRAIN.epoch_end = 100
|
||||||
|
config.TRAIN.niter = 0
|
||||||
|
config.TRAIN.niter_decay = 100
|
||||||
|
config.TRAIN.load_iter = 0
|
||||||
|
config.TRAIN.epoch = 0
|
||||||
|
|
||||||
|
# for cyclical schedule
|
||||||
|
config.TRAIN.n_cycle = 5
|
||||||
|
config.TRAIN.ratio = 0.8
|
||||||
|
config.TRAIN.beta_start= 0.0
|
||||||
|
config.TRAIN.beta_stop = 1.0
|
||||||
|
|
||||||
|
config.TRAIN.optimizer = 'adam'
|
||||||
|
config.TRAIN.momentum = 0.9
|
||||||
|
config.TRAIN.weight_decay = 0.0001
|
||||||
|
config.TRAIN.nesterov = False
|
||||||
|
config.TRAIN.gamma1 = 0.99
|
||||||
|
config.TRAIN.gamma2 = 0.0
|
||||||
|
|
||||||
|
###############################
|
||||||
|
# loss related params
|
||||||
|
config.LOSS = edict()
|
||||||
|
config.LOSS.names = ["all", "L1"]
|
||||||
|
config.LOSS.lambda_rec = 1
|
||||||
|
config.LOSS.lambda_kld = 0
|
||||||
|
config.LOSS.lambda_dif = 0
|
||||||
|
config.LOSS.lambda_cyc = 0
|
||||||
|
config.LOSS.lambda_trp = 0
|
||||||
|
config.LOSS.lambda_geo = 0
|
||||||
|
config.LOSS.lambda_rec_smooth = 0
|
||||||
|
config.LOSS.lambda_geo_smooth = 0
|
||||||
|
config.LOSS.lambda_logp = 0
|
||||||
|
config.LOSS.lambda_logdet = 0
|
||||||
|
|
||||||
|
#############################
|
||||||
|
# TEST related params
|
||||||
|
config.TEST = edict()
|
||||||
|
config.TEST.batch_size = 24
|
||||||
|
config.TEST.path_input = ""
|
||||||
|
config.TEST.path_save = ""
|
||||||
|
|
||||||
|
#############################
|
||||||
|
# INFER related params
|
||||||
|
config.INFER = edict()
|
||||||
|
config.INFER.batch_size = 24
|
||||||
|
config.INFER.path_input = ""
|
||||||
|
config.INFER.path_save = ""
|
||||||
|
|
||||||
|
#############################
|
||||||
|
# DEBUG related params
|
||||||
|
config.DEBUG = edict()
|
||||||
|
config.DEBUG.debug = False
|
||||||
|
config.DEBUG.save_batch_image_gt = False
|
||||||
|
config.DEBUG.save_batch_image_pred = False
|
||||||
|
config.DEBUG.save_heatmaps_gt = False
|
||||||
|
config.DEBUG.save_heatmaps_pred = False
|
||||||
|
|
||||||
|
|
||||||
|
def update_index_exp(index_exp):
|
||||||
|
# prepare index
|
||||||
|
str_ids = index_exp.split(',')
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for i in range(int(len(str_ids) / 2)):
|
||||||
|
start = int(str_ids[ 2*i])
|
||||||
|
end = int(str_ids[2*i + 1])
|
||||||
|
|
||||||
|
if end > start:
|
||||||
|
result += range(start, end)
|
||||||
|
|
||||||
|
# print('indexes', result)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _update_dict(k, v):
|
||||||
|
if k == 'DATASET':
|
||||||
|
if 'MEAN' in v and v['MEAN']:
|
||||||
|
v['MEAN'] = np.array([eval(x) if isinstance(x, str) else x for x in v['MEAN']])
|
||||||
|
if 'STD' in v and v['STD']:
|
||||||
|
v['STD'] = np.array([eval(x) if isinstance(x, str) else x for x in v['STD']])
|
||||||
|
|
||||||
|
# if "expression_indx" in v and v['expression_indx']:
|
||||||
|
# v['expression_indx'] = update_index_exp(v['expression_indx'])
|
||||||
|
|
||||||
|
if k == 'MODEL':
|
||||||
|
if 'EXTRA' in v and 'HEATMAP_SIZE' in v['EXTRA']:
|
||||||
|
if isinstance(v['EXTRA']['HEATMAP_SIZE'], int):
|
||||||
|
v['EXTRA']['HEATMAP_SIZE'] = np.array(
|
||||||
|
[v['EXTRA']['HEATMAP_SIZE'], v['EXTRA']['HEATMAP_SIZE']])
|
||||||
|
else:
|
||||||
|
v['EXTRA']['HEATMAP_SIZE'] = np.array(v['EXTRA']['HEATMAP_SIZE'])
|
||||||
|
|
||||||
|
if 'IMAGE_SIZE' in v:
|
||||||
|
if isinstance(v['IMAGE_SIZE'], int):
|
||||||
|
v['IMAGE_SIZE'] = np.array([v['IMAGE_SIZE'], v['IMAGE_SIZE']])
|
||||||
|
else:
|
||||||
|
v['IMAGE_SIZE'] = np.array(v['IMAGE_SIZE'])
|
||||||
|
|
||||||
|
for vk, vv in v.items():
|
||||||
|
if vk in config[k]:
|
||||||
|
config[k][vk] = vv
|
||||||
|
else:
|
||||||
|
raise ValueError("{}.{} not exist in config.py".format(k, vk))
|
||||||
|
|
||||||
|
|
||||||
|
def update_config(config_file):
|
||||||
|
exp_config = None
|
||||||
|
with open(config_file) as f:
|
||||||
|
exp_config = edict(yaml.safe_load(f))
|
||||||
|
|
||||||
|
for k, v in exp_config.items():
|
||||||
|
|
||||||
|
if k in config:
|
||||||
|
if isinstance(v, dict):
|
||||||
|
_update_dict(k, v)
|
||||||
|
else:
|
||||||
|
if k == 'SCALES':
|
||||||
|
config[k][0] = (tuple(v))
|
||||||
|
else:
|
||||||
|
config[k] = v
|
||||||
|
else:
|
||||||
|
raise ValueError("{} not exist in config.py".format(k))
|
||||||
|
|
||||||
|
# update some config item
|
||||||
|
config.GPUS = [int(i) for i in config.GPUS.split(',')]
|
||||||
|
|
||||||
|
|
||||||
|
def gen_config(config_file):
|
||||||
|
cfg = dict(config)
|
||||||
|
for k, v in cfg.items():
|
||||||
|
if isinstance(v, edict):
|
||||||
|
cfg[k] = dict(v)
|
||||||
|
|
||||||
|
with open(config_file, 'w') as f:
|
||||||
|
yaml.dump(dict(cfg), f, default_flow_style=False)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import sys
|
||||||
|
gen_config(sys.argv[1])
|
||||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user