Compare commits

...
10 Commits
149 changed files with 0 additions and 15363 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
*.onnx filter=lfs diff=lfs merge=lfs -text
data/mesh/** filter=lfs diff=lfs merge=lfs -text
-148
View File
@@ -1,148 +0,0 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
### VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
**/.vscode
# JetBrains
.idea/
# Lightning-Hydra-Template
configs/local/default.yaml
data/
logs/
wandb/
.env
.autoenv
-1449
View File
File diff suppressed because it is too large. Load diff
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:db2b7960f9237693bc449f11e56a48d716070a33ec146698c75f39ec2b38148d
size 24683986
View File
Whitespace-only changes.
-343
View File
@@ -1,343 +0,0 @@
import moviepy.editor as mpy
import numpy as np
import os
import cv2
import sys
# sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.landmark import landmark_to_images
import tempfile
from scipy.io import wavfile
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)
# close
animation.close()
# def write_videos(images, raw_speech, path_save, fps=50):
def write_video(list_images, raw_speech, path_video, fps=50, sr=16000):
""" convert images_pt to .mp4 animation
list_images, shape len=N list [512, 512, 3], or [1080, 1920, 3]
raw_speech, shape = (nsegmet, )
"""
num_frame = len(list_images)
H, W = list_images[0].shape[:2]
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=sr, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (W, H), True)
for i in range(num_frame):
writer.write(list_images[i])
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
# close tmp file
file_audio.close()
file_video.close()
def write_video_with_gt(images_pt, images_gt, raw_speech, path_video, fps=50, sr=16000):
""" convert images_pt to .mp4 animation
images_pt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3]
images_gt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3]
raw_speech, shape = (nsegmet, )
"""
num_frame = len(images_pt)
H, W = images_pt[0].shape[:2]
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=sr, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (2*W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True)
for i in range(num_frame):
concate_image = np.concatenate((images_pt[i], images_gt[i]), axis=1) # (H, 2*W, 3)
writer.write(concate_image)
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
# close tmp file
file_audio.close()
file_video.close()
def save_images_with_audio(images, path_audio, path_save, fps=50):
""" 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)
duration = N / fps
audioclip = mpy.AudioFileClip(str(path_audio))
print(f"\naudio clip duration = {audioclip.duration}, N={N}, fps={fps}, duration_N/fps={duration}")
if audioclip.duration + 0.0001 < duration:
print("\n\n\n ERROR: ")
# assert audioclip.duration + 0.0001 < duration,
audioclip = audioclip.set_duration(duration)
# add video
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"animation duration={animation.duration}, > save to = {path_save}")
# close
audioclip.close()
animation.close()
# add
path_save2 = str(path_save).replace(".mp4", "2.mp4")
cmd = f"ffmpeg -y -i {str(path_save)} -i {str(path_audio)} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest {str(path_save2)}"
os.system(cmd)
# del
cmd = f"rm {str(path_save)}"
os.system(cmd)
def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audio=None, start_time=None, end_time=None):
""" 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 = fps if fps else 50
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]])
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):
print(f"subclip clips {start_time}:{end_time}")
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)
animation.write_videofile(str(path_save), fps=fps)
# close
animation_pt.close()
animation_gt.close()
animation.close()
def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30):
""" convert data_motion to .mp4 animation
data_motion, shape [B, N, 68, 2]
data_motion_gt, shape [B, N, 68, 2]
"""
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)
# close
animation_pt.close()
animation_gt.close()
animation.close()
-9
View File
@@ -1,9 +0,0 @@
def debug(opt=None, msg="", verbose=False):
if opt is None or verbose:
print(msg)
if opt.DEBUG or verbose:
print(msg)
-135
View File
@@ -1,135 +0,0 @@
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
-121
View File
@@ -1,121 +0,0 @@
"""
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
-41
View File
@@ -1,41 +0,0 @@
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)
-254
View File
@@ -1,254 +0,0 @@
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
-87
View File
@@ -1,87 +0,0 @@
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)
if postfix is None:
postfix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}"
# make dir & set filename
if path_config is not None:
basename = path_config.name.split(".")[0]
self.path_output = Path(path_output).joinpath(basename, postfix)
self.path_output.mkdir(parents=True, exist_ok=True)
filename = self.path_output.joinpath(f"logger.log")
shutil.copyfile(src=path_config, dst=self.path_output.joinpath(path_config.name))
else:
self.path_output = Path(path_output)
self.path_output.mkdir(parents=True, exist_ok=True)
filename = self.path_output.joinpath(postfix + ".log")
# add file hander
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)
-39
View File
@@ -1,39 +0,0 @@
import numpy as np
from scipy import interpolate
def resample_by_nsteps(feat, nsteps_tgt):
"""
feat, (nframes, ... ) (with source_fps)
"""
nsteps_src = feat.shape[0]
data_idx = np.arange(0, nsteps_src, 1)
samp_idx = np.arange(0, nsteps_src-1, (nsteps_src - 1) / nsteps_tgt)
# print(f"data_idx = {list(data_idx)} \nsmap_idx = {list(samp_idx)}")
# sample function
func = interpolate.interp1d(data_idx, y=feat, axis=0)
data_interpolate = func(samp_idx)
return data_interpolate
def convert_fps(data, source_fps = 30, target_fps=25):
"""
data, (nframes, ... ) (with source_fps)
"""
nsize = data.shape[0]
data_idx = np.arange(0, nsize, 1)
samp_idx = np.arange(0, nsize-1, 1.0*source_fps/target_fps)
func = interpolate.interp1d(data_idx, data=data, axis=0)
data_interpolate = func(samp_idx)
if source_fps < target_fps:
data_interpolate = np.concatenate([data_interpolate, data[-1:]])
return data_interpolate
# def
-516
View File
@@ -1,516 +0,0 @@
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
-313
View File
@@ -1,313 +0,0 @@
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)
-372
View File
@@ -1,372 +0,0 @@
import os
from django import conf
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
config.FLAME = edict()
config.FLAME.flame_model_path = "./data/mesh/generic_model.pkl"
config.FLAME.flame_lmk_embedding_path = "./data/mesh/landmark_embedding.npy"
config.FLAME.n_shape = 100
config.FLAME.n_tex = 50
config.FLAME.n_exp = 50
config.FLAME.n_cam = 3
config.FLAME.n_pose = 6
config.FLAME.n_light = 27
# texture
config.FLAME.use_tex = False
config.FLAME.tex_type = 'BFM' # BFM, FLAME, albedoMM
config.FLAME.tex_path = "./data/mesh/FLAME_albedo_from_BFM.npz"
config.FLAME.flame_tex_path = ""
config.RENDER = edict()
config.RENDER.rasterizer_type = 'pytorch3d'
config.RENDER.image_size = 512
config.RENDER.uv_size = 256
config.RENDER.topology_path = './data/mesh/head_template.obj'
# 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 = False
config.VISUAL.use_visdom = False
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.name_header = "resnet50"
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
config.MODEL.dim_motion = 0
config.MODEL.dim_speech = 0
config.MODEL.dim_hidden = 0
config.MODEL.num_vertices = 0 # 5023
config.MODEL.n_lookprevs_motion = 0
config.MODEL.n_lookprevs_speech = 0
config.MODEL.n_lookahead_motion = 0
config.MODEL.n_lookahead_speech = 0
config.MODEL.n_layer_lstm = 0
# for MOGLOW
config.MODEL.n_flowstep = 0
config.MODEL.n_early_every = 0
config.MODEL.n_early_size = 0
config.MODEL.n_layer_wave = 0
config.MODEL.kernel_size = 0
config.MODEL.lambda_std = []
config.MODEL.fix_dims = []
# # 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.fps = 30
config.DATASET.sr = 16000
config.DATASET.name = 'ravdess'
config.DATASET.name_train = 'train_dataset'
config.DATASET.name_valid = "valid_dataset"
config.DATASET.type = '' # "clips" | "frame" | "none"
config.DATASET.root = "../data/"
config.DATASET.root_raw = "/data/lsen/DATA/xxxx/processing"
config.DATASET.path_mean_dict = "./data/xxxx_mean.npy"
# from dataset iteratiion
config.DATASET.nwind_second_train = 0
config.DATASET.nwind_second_valid = 0
config.DATASET.nwind_second_test = 0
config.DATASET.speech_extractor = ''
# for data smooth
config.DATASET.filter = '' # "gaussian" | "savgol"
# augmentation
config.DATASET.flip = False
config.DATASET.shifting_speed = 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.apply_lr_scheduler = 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_step_gamma = 0.1
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_period = 50
# for scheular sampling
config.TRAIN.epoch_teacher = 0
config.TRAIN.epoch_sampling = 0
config.TRAIN.optimizer = 'adam'
config.TRAIN.momentum = 0.9
config.TRAIN.weight_decay = 0 #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_rec_smooth = 0
config.LOSS.lambda_rec_exp = 0
config.LOSS.lambda_rec_pos = 0
config.LOSS.lambda_rec_geo = 0
config.LOSS.lambda_rec_syn = 0
config.LOSS.lambda_vel_exp = 0
config.LOSS.lambda_vel_pos = 0
config.LOSS.lambda_vel_geo = 0
config.LOSS.lambda_vel_syn = 0
config.LOSS.lambda_closure = 0
config.LOSS.lambda_rec_code = 0
config.LOSS.lambda_rec_ldmk = 0
config.LOSS.lambda_closure_x = 0
config.LOSS.lambda_closure_y = 0
# for Flow
config.LOSS.lambda_logp = 0
config.LOSS.lambda_logdet = 0
# for vae
config.LOSS.lambda_kl = 0
config.LOSS.lambda_vel = 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])
@@ -1,36 +0,0 @@
model_checkpoint:
_target_: pytorch_lightning.callbacks.ModelCheckpoint
monitor: "val/best" # name of the logged metric which determines when model is improving
mode: "min" # "max" means higher metric value is better, can be also "min"
save_top_k: 3 # save k best models (determined by above metric)
save_last: False # additionaly always save model from last epoch
verbose: False
every_n_epochs: 1
save_weights_only: True
dirpath: "checkpoints/"
filename: "epoch_{epoch:03d}"
auto_insert_metric_name: False
early_stopping:
_target_: pytorch_lightning.callbacks.EarlyStopping
monitor: "val/best" # name of the logged metric which determines when model is improving
mode: "max" # "max" means higher metric value is better, can be also "min"
patience: 10 # how many validation epochs of not improving until training stops
min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement
model_summary:
_target_: pytorch_lightning.callbacks.RichModelSummary
max_depth: 2
rich_progress_bar:
# _target_: pytorch_lightning.callbacks.TQDMProgressBar
_target_: pytorch_lightning.callbacks.RichProgressBar
leave: True
# save_test_video:
# _target_: src.modles.callbacks.audio2mesh_callback.Audio2MeshCallback
# path_data_raw: "/yrfs/lsen/DATA/LuoXData/processing2/"
# fps: 50.0
@@ -1,36 +0,0 @@
model_checkpoint:
_target_: pytorch_lightning.callbacks.ModelCheckpoint
monitor: "val/best" # name of the logged metric which determines when model is improving
mode: "min" # "max" means higher metric value is better, can be also "min"
save_top_k: 3 # save k best models (determined by above metric)
save_last: False # additionaly always save model from last epoch
verbose: False
every_n_epochs: 1
save_weights_only: True
dirpath: "checkpoints/"
filename: "epoch_{epoch:03d}"
auto_insert_metric_name: False
early_stopping:
_target_: pytorch_lightning.callbacks.EarlyStopping
monitor: "val/best" # name of the logged metric which determines when model is improving
mode: "max" # "max" means higher metric value is better, can be also "min"
patience: 10 # how many validation epochs of not improving until training stops
min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement
model_summary:
_target_: pytorch_lightning.callbacks.RichModelSummary
max_depth: 2
rich_progress_bar:
# _target_: pytorch_lightning.callbacks.TQDMProgressBar
_target_: pytorch_lightning.callbacks.RichProgressBar
leave: True
# save_test_video:
# _target_: src.modles.callbacks.audio2mesh_callback.Audio2MeshCallback
# path_data_raw: "/yrfs/lsen/DATA/LuoXData/processing2/"
# fps: 50.0
-25
View File
@@ -1,25 +0,0 @@
model_checkpoint:
_target_: pytorch_lightning.callbacks.ModelCheckpoint
monitor: "val/acc" # name of the logged metric which determines when model is improving
mode: "max" # "max" means higher metric value is better, can be also "min"
save_top_k: 1 # save k best models (determined by above metric)
save_last: True # additionaly always save model from last epoch
verbose: False
dirpath: "checkpoints/"
filename: "epoch_{epoch:03d}"
auto_insert_metric_name: False
early_stopping:
_target_: pytorch_lightning.callbacks.EarlyStopping
monitor: "val/acc" # name of the logged metric which determines when model is improving
mode: "max" # "max" means higher metric value is better, can be also "min"
patience: 100 # how many validation epochs of not improving until training stops
min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement
model_summary:
_target_: pytorch_lightning.callbacks.RichModelSummary
max_depth: -1
rich_progress_bar:
_target_: pytorch_lightning.callbacks.RichProgressBar
View File
Whitespace-only changes.
-6
View File
@@ -1,6 +0,0 @@
_target_: src.datasets.minist_datamodule.MNISTDataModule
data_dir: ${data_dir} # data_dir is specified in config.yaml
batch_size: 64
num_workers: 4
pin_memory: False
-35
View File
@@ -1,35 +0,0 @@
_target_: src.datasets.motion_datamodule.MotionDataModule
batch_size_train: 128
batch_size_test: 32
num_workers: 8
pin_memory: False
dataset_train:
_target_: src.datasets.components.motion_train.MotionTrainDataset
path_data: xxx/data_train.npz
fps: 50
sr: 16000
num_windows: 3
filter: "savgol"
flip: False
shifting_speed: False
dataset_valid:
_target_: src.datasets.components.motion_eval.MotionEvalDataset
path_data: xxx/data_valid.npz
fps: 50
sr: 16000
num_windows: 3
filter: "savgol"
dataset_test:
_target_: src.datasets.components.motion_eval.MotionEvalDataset
path_data: xxx/data_test.npz
fps: 50
sr: 16000
num_windows: 15
filter: "savgol"
-32
View File
@@ -1,32 +0,0 @@
_target_: src.datasets.motion_datamodule.MotionDataModule
batch_size_train: 128
batch_size_test: 32
num_workers: 8
pin_memory: False
dataset_train:
_target_: src.datasets.components.motion_render_train.MotionRenderTrainDataset
path_data: xxx/data_train.npz
fps: 50
sr: 16000
num_second_wind: 1
filter: "savgol"
dataset_valid:
_target_: src.datasets.components.motion_render_train.MotionRenderTrainDataset
path_data: xxx/data_valid.npz
fps: 50
sr: 16000
num_second_wind: 1
filter: "savgol"
dataset_test:
_target_: src.datasets.components.motion_render_train.MotionRenderTrainDataset
path_data: xxx/data_test.npz
fps: 50
sr: 16000
num_second_wind: 1
filter: "savgol"
-28
View File
@@ -1,28 +0,0 @@
# @package _global_
# default debugging setup, runs 1 full epoch
# other debugging configs can inherit from this one
defaults:
- override /log_dir: debug.yaml
trainer:
max_epochs: 1
gpus: 0 # debuggers don't like gpus
detect_anomaly: true # raise exception if NaN or +/-inf is detected in any tensor
track_grad_norm: 2 # track gradient norm with loggers
datamodule:
num_workers: 0 # debuggers don't like multiprocessing
pin_memory: False # disable gpu memory pin
# sets level of all command line loggers to 'DEBUG'
# https://hydra.cc/docs/tutorials/basic/running_your_app/logging/
hydra:
verbose: True
# use this to set level of only chosen command line loggers to 'DEBUG':
# verbose: [src.train, src.utils]
# config is already printed by hydra when `hydra/verbose: True`
print_config: False
-12
View File
@@ -1,12 +0,0 @@
# @package _global_
# uses only 1% of the training data and 5% of validation/test data
defaults:
- default.yaml
trainer:
max_epochs: 3
limit_train_batches: 0.01
limit_val_batches: 0.05
limit_test_batches: 0.05
-10
View File
@@ -1,10 +0,0 @@
# @package _global_
# overfits to 3 batches
defaults:
- default.yaml
trainer:
max_epochs: 20
overfit_batches: 3
-12
View File
@@ -1,12 +0,0 @@
# @package _global_
# runs with execution time profiling
defaults:
- default.yaml
trainer:
max_epochs: 1
profiler: "simple"
# profiler: "advanced"
# profiler: "pytorch"
-9
View File
@@ -1,9 +0,0 @@
# @package _global_
# runs 1 train, 1 validation and 1 test step
defaults:
- default.yaml
trainer:
fast_dev_run: true
-9
View File
@@ -1,9 +0,0 @@
# @package _global_
# runs only test epoch
defaults:
- default.yaml
train: False
test: True
@@ -1,41 +0,0 @@
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
isTrain: False
MODEL:
# name: 'audio2mesh'
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220315-16H55M15S"
# load_epoch: 35
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220315-16H46M54S"
# load_epoch: 75
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H11M43S"
# load_epoch: 65
# 5h, 1:10, epoch 25
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S"
load_epoch: 25
DATASET:
fps: 50
sr: 16000
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
TRAIN:
apply_testing: True
apply_validation: True
@@ -1,45 +0,0 @@
# @package _global_
# to execute this experiment run:
# python train.py experiment=example
defaults:
- override /datamodule: motion.yaml
- override /model: audio2mesh_CN.yaml
- override /callbacks: audio2mesh_callback.yaml
- override /logger: tensorboard.yaml
- override /trainer: default.yaml
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
# name of the run determines folder name in logs
name: "audio2mesh"
seed: 12345
trainer:
gpus: [9,]
min_epochs: 50
max_epochs: 200
gradient_clip_val: 0.5
num_sanity_val_steps: 0
check_val_every_n_epoch: 5
enable_checkpointing: True
log_every_n_steps: 20
model:
lr: 0.0001
netG:
_target_: src.models.components.audio2mesh.Audio2Mesh
num_vertices: 5023
nc_condit: 1024
datamodule:
batch_size: 128
batch_size_test: 32
# data_dir: "./data/LuoXData-raw-8h"
@@ -1,62 +0,0 @@
# @package _global_
# to execute this experiment run:
# python train.py experiment=audio2mesh/train_audio2mesh_CN_20220425.yaml
defaults:
- override /dataset: data_actor4.yaml
- override /model: model_audio2mesh.yaml
- override /callbacks: callback_audio2mesh.yaml
- override /logger: tensorboard.yaml
- override /trainer: ddp.yaml
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
# name of the run determines folder name in logs
name: "audio2mesh"
seed: 12345
path_data: /ssdata1/lsen/CODE/Audio2Motion/data/Actor4
specifict_folder: Actor4-raw-1h
trainer:
gpus: [2, 3, 4, 5]
min_epochs: 300
max_epochs: 300
gradient_clip_val: 0.5
num_sanity_val_steps: 0
check_val_every_n_epoch: 1
enable_checkpointing: True
log_every_n_steps: 20
model:
lr: 0.0001
opt:
path_mean_dict: ${path_data}/DECA_Actor4_mean.npy
netG:
_target_: src.models.components.audio2mesh.Audio2Mesh
num_vertices: 5023
nc_condit: 1024
dataset:
batch_size_train: 128
batch_size_test: 32
dataset_train:
path_data: ${path_data}/${specifict_folder}/data_train.npz
dataset_valid:
path_data: ${path_data}/${specifict_folder}/data_valid.npz
dataset_test:
path_data: ${path_data}/${specifict_folder}/data_test.npz
# data_dir: "./data/LuoXData-raw-8h"
@@ -1,62 +0,0 @@
# @package _global_
# to execute this experiment run:
# python train.py experiment=audio2mesh/train_audio2mesh_CN_20220425.yaml
defaults:
- override /dataset: motion.yaml
- override /model: model_audio2mesh.yaml
- override /callbacks: callback_audio2mesh.yaml
- override /logger: tensorboard.yaml
- override /trainer: ddp.yaml
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
# name of the run determines folder name in logs
name: "audio2mesh"
seed: 12345
path_data: /ssdata1/lsen/CODE/Audio2Motion/data/Actor5
specifict_folder: Actor5-raw-3h
trainer:
gpus: [1, 4, 8]
min_epochs: 100
max_epochs: 300
gradient_clip_val: 0.5
num_sanity_val_steps: 0
check_val_every_n_epoch: 1
enable_checkpointing: True
log_every_n_steps: 20
model:
lr: 0.0001
opt:
path_mean_dict: ${path_data}/DECA_Actor5_mean_smile.npy
netG:
_target_: src.models.components.audio2mesh.Audio2Mesh
num_vertices: 5023
nc_condit: 1024
dataset:
batch_size_train: 128
batch_size_test: 32
dataset_train:
path_data: ${path_data}/${specifict_folder}/data_train.npz
dataset_valid:
path_data: ${path_data}/${specifict_folder}/data_valid.npz
dataset_test:
path_data: ${path_data}/${specifict_folder}/data_test.npz
# data_dir: "./data/LuoXData-raw-8h"
@@ -1,60 +0,0 @@
# @package _global_
# to execute this experiment run:
# python train.py experiment=audio2mesh/train_audio2mesh_CN_20220425.yaml
defaults:
- override /dataset: motion_audio2render.yaml
- override /model: model_audio2render.yaml
- override /callbacks: callback_audio2render.yaml
- override /logger: tensorboard.yaml
- override /trainer: ddp.yaml
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
# name of the run determines folder name in logs
name: "audio2render"
seed: 12345
path_data: ${path_cwd}/data/Actor5
specifict_folder: data-list-smile-1h
trainer:
gpus: [0,1,2]
min_epochs: 100
max_epochs: 300
gradient_clip_val: 0.5
num_sanity_val_steps: 0
check_val_every_n_epoch: 1
enable_checkpointing: True
log_every_n_steps: 1
model:
lr: 0.0001
opt:
path_mean_dict: ${path_data}/DECA_Actor5_mean_smile.npy
netG:
_target_: src.models.components.audio2motion.Audio2Motion
nc_motion: 53
nc_condit: 1024
dataset:
batch_size_train: 1
batch_size_test: 16
num_workers: 4
dataset_train:
path_data: ${path_data}/${specifict_folder}/data_train.npz
dataset_valid:
path_data: ${path_data}/${specifict_folder}/data_valid.npz
dataset_test:
path_data: ${path_data}/${specifict_folder}/data_test.npz
-38
View File
@@ -1,38 +0,0 @@
# @package _global_
# to execute this experiment run:
# python train.py experiment=example
defaults:
- override /datamodule: mnist.yaml
- override /model: mnist.yaml
- override /callbacks: default.yaml
- override /logger: tensorboard.yaml
- override /trainer: ddp.yaml
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
# name of the run determines folder name in logs
name: "simple_dense_net"
seed: 12345
trainer:
min_epochs: 10
max_epochs: 100
gradient_clip_val: 0.5
model:
lr: 0.002
net:
lin1_size: 128
lin2_size: 256
lin3_size: 64
datamodule:
batch_size: 64
logger:
wandb:
tags: ["mnist", "${name}"]
-60
View File
@@ -1,60 +0,0 @@
# @package _global_
# example hyperparameter optimization of some experiment with Optuna:
# python train.py -m hparams_search=mnist_optuna experiment=example
defaults:
- override /hydra/sweeper: optuna
# choose metric which will be optimized by Optuna
# make sure this is the correct name of some metric logged in lightning module!
optimized_metric: "val/acc_best"
# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator
# docs: https://hydra.cc/docs/next/plugins/optuna_sweeper
hydra:
sweeper:
_target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
# storage URL to persist optimization results
# for example, you can use SQLite if you set 'sqlite:///example.db'
storage: null
# name of the study to persist optimization results
study_name: null
# number of parallel workers
n_jobs: 1
# 'minimize' or 'maximize' the objective
direction: maximize
# total number of runs that will be executed
n_trials: 25
# choose Optuna hyperparameter sampler
# docs: https://optuna.readthedocs.io/en/stable/reference/samplers.html
sampler:
_target_: optuna.samplers.TPESampler
seed: 12345
n_startup_trials: 10 # number of random sampling runs before optimization starts
# define range of hyperparameters
search_space:
datamodule.batch_size:
type: categorical
choices: [32, 64, 128]
model.lr:
type: float
low: 0.0001
high: 0.2
model.net.lin1_size:
type: categorical
choices: [32, 64, 128, 256, 512]
model.net.lin2_size:
type: categorical
choices: [32, 64, 128, 256, 512]
model.net.lin3_size:
type: categorical
choices: [32, 64, 128, 256, 512]
View File
Whitespace-only changes.
-8
View File
@@ -1,8 +0,0 @@
# @package _global_
hydra:
run:
dir: logs/debugs/runs/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
sweep:
dir: logs/debugs/multiruns/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
subdir: ${hydra.job.num}
-8
View File
@@ -1,8 +0,0 @@
# @package _global_
hydra:
run:
dir: logs/experiments/runs/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
sweep:
dir: logs/experiments/multiruns/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
subdir: ${hydra.job.num}
-8
View File
@@ -1,8 +0,0 @@
# @package _global_
hydra:
run:
dir: logs/evaluations/runs/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
sweep:
dir: logs/evaluations/multiruns/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
subdir: ${hydra.job.num}
-7
View File
@@ -1,7 +0,0 @@
# https://www.comet.ml
comet:
_target_: pytorch_lightning.loggers.comet.CometLogger
api_key: ${oc.env:COMET_API_TOKEN} # api key is loaded from environment variable
project_name: "template-tests"
experiment_name: ${name}
-7
View File
@@ -1,7 +0,0 @@
# csv logger built in lightning
csv:
_target_: pytorch_lightning.loggers.csv_logs.CSVLogger
save_dir: "."
name: "csv/"
prefix: ""
-9
View File
@@ -1,9 +0,0 @@
# train with many loggers at once
defaults:
# - comet.yaml
- csv.yaml
# - mlflow.yaml
# - neptune.yaml
- tensorboard.yaml
- wandb.yaml
-10
View File
@@ -1,10 +0,0 @@
# https://mlflow.org
mlflow:
_target_: pytorch_lightning.loggers.mlflow.MLFlowLogger
experiment_name: ${name}
tracking_uri: null
tags: null
save_dir: ./mlruns
prefix: ""
artifact_location: null
-11
View File
@@ -1,11 +0,0 @@
# https://neptune.ai
neptune:
_target_: pytorch_lightning.loggers.neptune.NeptuneLogger
api_key: ${oc.env:NEPTUNE_API_TOKEN} # api key is loaded from environment variable
project_name: your_name/template-tests
close_after_fit: True
offline_mode: False
experiment_name: ${name}
experiment_id: null
prefix: ""
-10
View File
@@ -1,10 +0,0 @@
# https://www.tensorflow.org/tensorboard/
tensorboard:
_target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger
save_dir: "tensorboard/"
name: null
version: ${name}
log_graph: False
default_hp_metric: True
prefix: ""
-15
View File
@@ -1,15 +0,0 @@
# https://wandb.ai
wandb:
_target_: pytorch_lightning.loggers.wandb.WandbLogger
project: "template-tests"
# name: ${name}
save_dir: "."
offline: False # set True to store all logs only locally
id: null # pass correct id to resume experiment!
# entity: "" # set to name of your wandb team
log_model: False
prefix: ""
job_type: "train"
group: ""
tags: []
-16
View File
@@ -1,16 +0,0 @@
_target_: src.models.mnist_module.MNISTLitModule
opt:
speech_extractor: wav2vec
AA: ss
BB: 22
lr: 0.001
weight_decay: 0.0005
net:
_target_: src.models.components.simple_dense_net.SimpleDenseNet
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 256
output_size: 10
-48
View File
@@ -1,48 +0,0 @@
_target_: src.models.module_audio2mesh.Audio2MeshModel
lr: 0.001
weight_decay: 0.0005
opt:
speech_extractor: wav2vec
sr: 16000
fps: 50
num_vertices: 5023
lambda_rec_geo: 1
lambda_vel_geo: 10
path_mean_dict: xxx/DECA_actor_mean.npy
path_init_expression_basis: ${path_cwd}/checkpoints/init_expression_basis.npy
opt_LOSS:
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 0
lambda_closure_x: 0
lambda_closure_y: 0
opt_netF:
n_shape: 100
n_exp: 50
flame_model_path: ${path_cwd}/data/mesh/generic_model.pkl
flame_lmk_embedding_path: ${path_cwd}/data/mesh/landmark_embedding.npy
opt_netR:
rasterizer_type: pytorch3d
image_size: 512
uv_size: 256
topology_path: ${path_cwd}/data/mesh/head_template.obj
opt_netW:
path_ckpt_wav2vec: ${path_cwd}/checkpoints/wav2vec2
netG:
_target_: src.models.components.audio2mesh.Audio2Mesh
num_vertices: 5023
nc_condit: 1024
-57
View File
@@ -1,57 +0,0 @@
_target_: src.models.module_audio2render.Audio2RenderModel
lr: 0.001
weight_decay: 0.0005
opt:
speech_extractor: wav2vec
sr: 16000
fps: 50
num_vertices: 5023
path_mean_dict: xxx/DECA_actor_mean.npy
path_init_expression_basis: ${path_cwd}/checkpoints/init_expression_basis.npy
opt_loss:
useSeg: True
lambda_lmk: 1
lambda_eyed: 1
lambda_lipd: 1
lambda_photo: 1
lambda_reg: 0.01
opt_netF:
n_shape: 100
n_exp: 50
flame_model_path: ${path_cwd}/data/mesh/generic_model.pkl
flame_lmk_embedding_path: ${path_cwd}/data/mesh/landmark_embedding.npy
opt_netT:
tex_type: 'BFM'
tex_path: ${path_cwd}/data/mesh/FLAME_albedo_from_BFM.npz
n_tex: 50
opt_netR:
rasterizer_type: pytorch3d
image_size: 512
uv_size: 512 #256
topology_path: ${path_cwd}/data/mesh/head_template.obj
face_mask_path: ${path_cwd}/data/mesh/uv_face_mask.png
face_eye_mask_path: ${path_cwd}/data/mesh/uv_face_eye_mask.png
mean_tex_path: ${path_cwd}/data/mesh/mean_texture.jpg
opt_netW:
path_ckpt_wav2vec: ${path_cwd}/checkpoints/wav2vec2
netG:
_target_: src.models.components.audio2motion.Audio2Motion
nc_motion: 53
nc_condit: 1024
-32
View File
@@ -1,32 +0,0 @@
# @package _global_
# specify here default evaluation configuration
defaults:
- _self_
- datamodule: mnist.yaml # choose the datamodule for evaluation
- model: mnist.yaml
- callbacks: null
- logger: null
- trainer: default.yaml
- log_dir: evaluation.yaml
- experiment: null
# enable color logging
- override hydra/hydra_logging: colorlog
- override hydra/job_logging: colorlog
path_cwd: ${hydra:runtime.cwd}
data_dir: ${path_cwd}/data/
print_config: True
ignore_warnings: True
seed: null
name: "default"
# passing checkpoint path is necessary
ckpt_path: ???
-59
View File
@@ -1,59 +0,0 @@
# @package _global_
# specify here default training configuration
defaults:
- _self_
- dataset: mnist.yaml
- model: mnist.yaml
- callbacks: default.yaml
- logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
- trainer: default.yaml
- log_dir: default.yaml
# experiment configs allow for version control of specific configurations
# e.g. best hyperparameters for each combination of model and datamodule
- experiment: example.yaml
# debugging config (enable through command line, e.g. `python train.py debug=default)
- debug: null
# config for hyperparameter optimization
- hparams_search: null
# optional local config for machine/user specific settings
# it's optional since it doesn't need to exist and is excluded from version control
- optional local: default.yaml
# enable color logging
- override hydra/hydra_logging: colorlog
- override hydra/job_logging: colorlog
# path to original working directory
# hydra hijacks working directory by changing it to the new log directory
# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
path_cwd: ${hydra:runtime.cwd}
# path to folder with data
# data_dir: ${path_cwd}/data/
# pretty print config at the start of the run using Rich library
print_config: True
# disable python warnings if they annoy you
ignore_warnings: True
# set False to skip model training
train: True
# evaluate on test set, using best model weights achieved during training
# lightning chooses best weights based on the metric specified in checkpoint callback
test: True
# seed for random number generators in pytorch, numpy and python.random
seed: null
# default name for the experiment, determines logging folder path
# (you can overwrite this name in experiment configs)
name: "default"
-6
View File
@@ -1,6 +0,0 @@
defaults:
- default.yaml
gpus: [2,3,6]
strategy: ddp
sync_batchnorm: True
-13
View File
@@ -1,13 +0,0 @@
_target_: pytorch_lightning.Trainer
# gpus: [2,3,6]
gpus: [9,]
min_epochs: 1
max_epochs: 10
# number of validation steps to execute at the beginning of the training
# num_sanity_val_steps: 0
# ckpt path
resume_from_checkpoint: null
View File
Whitespace-only changes.
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:6f9ca787c95ec56f3a090498514c3335c75eb9b7d88bb36eed6b585dfe220f99
size 19260
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:efee38e24c9f9f7cc01120a5a48201a787e97e6e20af455747fd60f3dc06eb68
size 53023716
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:5a996eaca4b56b03a0c2907f7dfa3a92680d965fd190d345a7e588f6fa017d1b
size 53023716
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7e9f619962488f9d99315c2adec65dc64510e549e955536a64da44ec9972ab2a
size 1258291694
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e714ed293054cba5eea9c96bd3b6b57880074cd84b3fd00d606cbaf0bee7c5c2
size 434142943
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:296d01113d67bdaace6f6fe741f7d855e58dc0707f0bb113758520ffa5d8cb93
size 524416
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:efcd14cc4a69f3a3d9af8ded80146b5b6b50df3bd74cf69108213b144eba725b
size 53023716
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:dd5bfbce75adb99b1963f43bca7ec3557bd4a7321f8fc515f4100599e80d99f2
size 563358
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8095348eeafce5a02f6bd8765146307f9567a3f03b316d788a2e47336d667954
size 31292
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:34364c02dec9dfb30580d1575b375553c6cd8d5da5caa6ac5a611ce65b91f529
size 53722
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8563919927a2bc2ea7343d0ceef35254105d21a1947f00e5ca39e01d6ed1f9f1
size 6677908
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a5069d8ffaf020008ae92d5062c4e98600f723aac4eb869731f190e4630467b5
size 11522
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:bbf570444e3dddcdc54eaab7eeece97fe87d61cc3761e2c8b22ef495905e56fa
size 12112
View File
Whitespace-only changes.
-16
View File
@@ -1,16 +0,0 @@
#!/usr/bin/env bash
# This script allows to quickly change into the latest log dir of a specific kind.
# Should be executed from project root folder.
#
# Go to latest log dir from 'runs' folder:
# cd $(logs/latest logs/runs)
#
# Go to latest log dir from 'experiments' folder:
# cd $(logs/latest logs/experiments)
set -e
set -o pipefail
find "$1" -maxdepth 2 -type d | sort -r | head -n 1
-582
View File
@@ -1,582 +0,0 @@
import numpy as np
from collections import OrderedDict
import torch
import torch.nn as nn
from pathlib import Path
from src.models.info import flame_mouth_idx
from src.models.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
from src.utils import util
# common
from common.animation import write_video, write_video_with_gt
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2MeshModel(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
# init last layer
init_exp_weight = np.load("./data/init_expression_basis.npy")
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50]
if isinstance(self.netG, torch.nn.DataParallel):
self.netG.module.decoder_mesh.weight.data = init_exp_weight
else:
self.netG.decoder_mesh.weight.data = init_exp_weight
print(f"init_exp_weight shape = {init_exp_weight.shape}")
self.netF = define_FLAME(opt, self.device)
self.netR = define_render(opt, self.device)
self.processor, self.extractor = define_extractor(opt, self.device)
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
path_deca_mean = self.opt.DATASET.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
# get template
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
# self.temp_verts_specific = np.load("/ssdata1/lsen/CODE/audio-to-motion/data/Actor4/template_meiyan2.npy") # (5023, 3)
# self.temp_verts_specific = self.temp_verts_specific.reshape(1, 1, 5023, 3)
# self.temp_verts_specific = torch.from_numpy(self.temp_verts_specific).to(self.device)
# save to
# loss function
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none")
self.names_loss = opt.LOSS.names
# define loss weight
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
if self.isTrain:
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
@torch.no_grad()
def set_input(self, batch_input):
""" """
# motion data
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data
cond = None
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
pad_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False)
inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt")
cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# unfold speech data
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
# setup
self.cond = cond
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
data = data[:, 7:7+self.nsteps, :]
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
# cut audio clips
idx_beg = int(7 * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5)
idx_end = int((7 + self.nsteps) * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5)
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
def forward(self, batch_input):
self.set_input(batch_input)
# forward
pred = self.netG(self.cond)
debug(self.opt, f"traing pred = {pred.shape}", verbose=False)
return pred
def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model
self.set_input(batch_input)
# forward
self.pred = self.netG(self.cond)
self.pred += self.temp_verts
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
# loss
loss, loss_dict = self.eval_losses(self.pred, self.vert)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss_dict
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
pred = self.netG(self.cond)
pred += self.temp_verts
loss, loss_dict = self.eval_losses(pred, self.vert)
return loss_dict
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True):
self.eval()
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
data = batch_data.float().to(self.device) # (B, nframe, 53)
vert, ldmk2d, ldmk3d = self.get_vertices(data)
# add a dimensions
if batch_speech.dims == 1:
batch_speech = batch_speech.unsqueeze(0) # (B, nsegmt)
with torch.no_grad():
batch_pdt_geo = self.netG(cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
# render & and save
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, vert, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix,vis_landmarks=False)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pose = torch.zeros(1, 6).to(self.device)
if mean_dict is not None:
batch_shape = self.mean_dict["shape"].reshape(1, 100)
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
else:
batch_shape = torch.zeros(1, 100).to(self.device)
with torch.no_grad():
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
print(f"template verts reshape = {verts.shape}")
return verts, ldmk2d, ldmk3d
def get_vertices(self, batch_motion):
"""
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos_mouth
with torch.no_grad():
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
return verts, ldmk2d, ldmk3d
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = OrderedDict()
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
if self.opt.LOSS.lambda_vel_geo > 0:
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# landmarks loss
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
if self.opt.LOSS.lambda_rec_ldmk > 0:
loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk
# mouth closure_x loss (left/right mouth)
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_x"] = loss_closure_x.mean().detach()
if self.opt.LOSS.lambda_closure_x > 0:
loss += loss_closure_x.mean() * self.opt.LOSS.lambda_closure_x
# mouth closure_y loss (upper/lower mouth)
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_y"] = loss_closure_y.mean().detach()
if self.opt.LOSS.lambda_closure_y > 0:
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
# total loss
loss_dict["all"] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
# batch_pdt_pos, [B x N x dim_motion]
# batch_speech, [B x N*sr/fps ]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...]
v_render_pt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# write video
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, batch_speech, ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}")
@torch.no_grad()
def render_geometry(self, verts, cam=None, device=None):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_geo, [B x N x 5023 x 3]
# batch_tgt_geo, [B x N x 5023 x 3]
# batch_speech, [B x N*sr/fps ]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# save animation
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
#########################################
def tensor2image(tensor):
# image = tensor.detach().cpu().numpy()
image = tensor.numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2mesh":
from src.nn.audio2mesh import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_voca":
from src.nn.audio2mesh_voca import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_resnet":
from src.nn.audio2mesh_resnet import Audio2Mesh
netG = Audio2Mesh(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
if len(opt.GPUS) > 1:
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_FLAME(opt, device):
from src.nn.FLAME import FLAME
model = FLAME(opt.FLAME).to(device)
return model
def define_render(opt, device):
from src.utils.renderer import SRenderY, set_rasterizer
set_rasterizer(opt.RENDER.rasterizer_type)
model = SRenderY(opt.RENDER.image_size,
obj_filename=opt.RENDER.topology_path,
uv_size=opt.RENDER.uv_size,
rasterizer_type=opt.RENDER.rasterizer_type
).to(device)
return model
def define_extractor(opt, device):
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
View File
Whitespace-only changes.
-48
View File
@@ -1,48 +0,0 @@
"""This script is the data preparation script for Deep3DFaceRecon_pytorch
"""
import os
import numpy as np
import argparse
from .detect_lm68 import detect_68p, load_lm_graph
from .skin_mask import get_skin_mask
from .generate_list import check_list, write_list
import warnings
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', type=str, default='datasets', help='root directory for training data')
parser.add_argument('--img_folder', nargs="+", required=True, help='folders of training images')
parser.add_argument('--mode', type=str, default='train', help='train or val')
opt = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
def data_prepare(folder_list, mode):
lm_sess,input_op,output_op = load_lm_graph('./checkpoints/lm_model/68lm_detector.pb') # load a tensorflow version 68-landmark detector
for img_folder in folder_list:
detect_68p(img_folder,lm_sess, input_op, output_op) # detect landmarks for images
get_skin_mask(img_folder) # generate skin attention mask for images
# create files that record path to all training data
msks_list = []
for img_folder in folder_list:
path = os.path.join(img_folder, 'mask')
msks_list += ['/'.join([img_folder, 'mask', i]) for i in sorted(os.listdir(path)) if 'jpg' in i or
'png' in i or 'jpeg' in i or 'PNG' in i]
imgs_list = [i.replace('mask/', '') for i in msks_list]
lms_list = [i.replace('mask', 'landmarks') for i in msks_list]
lms_list = ['.'.join(i.split('.')[:-1]) + '.txt' for i in lms_list]
lms_list_final, imgs_list_final, msks_list_final = check_list(lms_list, imgs_list, msks_list) # check if the path is valid
write_list(lms_list_final, imgs_list_final, msks_list_final, mode=mode) # save files
if __name__ == '__main__':
print('Datasets:',opt.img_folder)
data_prepare([os.path.join(opt.data_root,folder) for folder in opt.img_folder],opt.mode)
-108
View File
@@ -1,108 +0,0 @@
import os
import cv2
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
from .preprocess import align_for_lm
from shutil import move
mean_face = np.loadtxt('util/test_mean_face.txt')
mean_face = mean_face.reshape([68, 2])
def save_label(labels, save_path):
np.savetxt(save_path, labels)
def draw_landmarks(img, landmark, save_name):
landmark = landmark
lm_img = np.zeros([img.shape[0], img.shape[1], 3])
lm_img[:] = img.astype(np.float32)
landmark = np.round(landmark).astype(np.int32)
for i in range(len(landmark)):
for j in range(-1, 1):
for k in range(-1, 1):
if img.shape[0] - 1 - landmark[i, 1]+j > 0 and \
img.shape[0] - 1 - landmark[i, 1]+j < img.shape[0] and \
landmark[i, 0]+k > 0 and \
landmark[i, 0]+k < img.shape[1]:
lm_img[img.shape[0] - 1 - landmark[i, 1]+j, landmark[i, 0]+k,
:] = np.array([0, 0, 255])
lm_img = lm_img.astype(np.uint8)
cv2.imwrite(save_name, lm_img)
def load_data(img_name, txt_name):
return cv2.imread(img_name), np.loadtxt(txt_name)
# create tensorflow graph for landmark detector
def load_lm_graph(graph_filename):
with tf.gfile.GFile(graph_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name='net')
img_224 = graph.get_tensor_by_name('net/input_imgs:0')
output_lm = graph.get_tensor_by_name('net/lm:0')
lm_sess = tf.Session(graph=graph)
return lm_sess,img_224,output_lm
# landmark detection
def detect_68p(img_path, sess, input_op, output_op):
print('detecting landmarks......')
names = [i for i in sorted(os.listdir(
img_path)) if 'jpg' in i or 'png' in i or 'jpeg' in i or 'PNG' in i]
vis_path = os.path.join(img_path, 'vis')
remove_path = os.path.join(img_path, 'remove')
save_path = os.path.join(img_path, 'landmarks')
if not os.path.isdir(vis_path):
os.makedirs(vis_path)
if not os.path.isdir(remove_path):
os.makedirs(remove_path)
if not os.path.isdir(save_path):
os.makedirs(save_path)
for i in range(0, len(names)):
name = names[i]
print('%05d' % (i), ' ', name)
full_image_name = os.path.join(img_path, name)
txt_name = '.'.join(name.split('.')[:-1]) + '.txt'
full_txt_name = os.path.join(img_path, 'detections', txt_name) # 5 facial landmark path for each image
# if an image does not have detected 5 facial landmarks,
# remove it from the training list
if not os.path.isfile(full_txt_name):
move(full_image_name, os.path.join(remove_path, name))
continue
# load data
img, five_points = load_data(full_image_name, full_txt_name)
input_img, scale, bbox = align_for_lm(img, five_points) # align for 68 landmark detection
# if the alignment fails, remove corresponding image from the training list
if scale == 0:
move(full_txt_name, os.path.join(remove_path, txt_name))
move(full_image_name, os.path.join(remove_path, name))
continue
# detect landmarks
input_img = np.reshape(input_img, [1, 224, 224, 3]).astype(np.float32)
landmark = sess.run(output_op, feed_dict={input_op: input_img})
# transform back to original image coordinate
landmark = landmark.reshape([68, 2]) + mean_face
landmark[:, 1] = 223 - landmark[:, 1]
landmark = landmark / scale
landmark[:, 0] = landmark[:, 0] + bbox[0]
landmark[:, 1] = landmark[:, 1] + bbox[1]
landmark[:, 1] = img.shape[0] - 1 - landmark[:, 1]
if i % 100 == 0:
draw_landmarks(img, landmark, os.path.join(vis_path, name))
save_label(landmark, os.path.join(save_path, txt_name))
-34
View File
@@ -1,34 +0,0 @@
"""This script is to generate training list files for Deep3DFaceRecon_pytorch
"""
import os
# save path to training data
def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''):
save_path = os.path.join(save_folder, mode)
if not os.path.isdir(save_path):
os.makedirs(save_path)
with open(os.path.join(save_path, save_name + 'landmarks.txt'), 'w') as fd:
fd.writelines([i + '\n' for i in lms_list])
with open(os.path.join(save_path, save_name + 'images.txt'), 'w') as fd:
fd.writelines([i + '\n' for i in imgs_list])
with open(os.path.join(save_path, save_name + 'masks.txt'), 'w') as fd:
fd.writelines([i + '\n' for i in msks_list])
# check if the path is valid
def check_list(rlms_list, rimgs_list, rmsks_list):
lms_list, imgs_list, msks_list = [], [], []
for i in range(len(rlms_list)):
flag = 'false'
lm_path = rlms_list[i]
im_path = rimgs_list[i]
msk_path = rmsks_list[i]
if os.path.isfile(lm_path) and os.path.isfile(im_path) and os.path.isfile(msk_path):
flag = 'true'
lms_list.append(rlms_list[i])
imgs_list.append(rimgs_list[i])
msks_list.append(rmsks_list[i])
print(i, rlms_list[i], flag)
return lms_list, imgs_list, msks_list
-237
View File
@@ -1,237 +0,0 @@
"""This script contains the image preprocessing code for Deep3DFaceRecon_pytorch
"""
import numpy as np
from scipy.io import loadmat
from PIL import Image
import cv2
import os
from skimage import transform as trans
import torch
import warnings
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
# calculating least square problem for image alignment
def POS(xp, x):
npts = xp.shape[1]
A = np.zeros([2*npts, 8])
A[0:2*npts-1:2, 0:3] = x.transpose()
A[0:2*npts-1:2, 3] = 1
A[1:2*npts:2, 4:7] = x.transpose()
A[1:2*npts:2, 7] = 1
b = np.reshape(xp.transpose(), [2*npts, 1])
k, _, _, _ = np.linalg.lstsq(A, b)
R1 = k[0:3]
R2 = k[4:7]
sTx = k[3]
sTy = k[7]
s = (np.linalg.norm(R1) + np.linalg.norm(R2))/2
t = np.stack([sTx, sTy], axis=0)
return t, s
# bounding box for 68 landmark detection
# to 224 x 224, rect bbox
def BBRegression(points, params):
w1 = params['W1']
b1 = params['B1']
w2 = params['W2']
b2 = params['B2']
data = points.copy().reshape([5, 2])
# data - data_mean
data_mean = np.mean(data, axis=0) # (2,)
x_mean,y_mean = data_mean[0], data_mean[1]
data[:, 0] = data[:, 0] - x_mean
data[:, 1] = data[:, 1] - y_mean
# (data - data_mean) / variance
rms = np.sqrt(np.sum(data ** 2)/5)
data = data / rms
data = data.reshape([1, 10])
data = np.transpose(data)
inputs = np.matmul(w1, data) + b1
inputs = 2 / (1 + np.exp(-2 * inputs)) - 1
inputs = np.matmul(w2, inputs) + b2
inputs = np.transpose(inputs)
x = inputs[:, 0] * rms + x_mean
y = inputs[:, 1] * rms + y_mean
w = 224/inputs[:, 2] * rms
rects = [x, y, w, w]
return np.array(rects).reshape([4])
# utils for landmark detection
def img_padding(img, box):
success = True
bbox = box.copy()
res = np.zeros([2*img.shape[0], 2*img.shape[1], 3])
res[img.shape[0] // 2: img.shape[0] + img.shape[0] //
2, img.shape[1] // 2: img.shape[1] + img.shape[1]//2] = img
bbox[0] = bbox[0] + img.shape[1] // 2
bbox[1] = bbox[1] + img.shape[0] // 2
if bbox[0] < 0 or bbox[1] < 0:
success = False
return res, bbox, success
# utils for landmark detection
def crop(img, bbox):
padded_img, padded_bbox, flag = img_padding(img, bbox)
if flag:
crop_img = padded_img[padded_bbox[1]: padded_bbox[1] +
padded_bbox[3], padded_bbox[0]: padded_bbox[0] + padded_bbox[2]]
crop_img = cv2.resize(crop_img.astype(np.uint8),
(224, 224), interpolation=cv2.INTER_CUBIC)
scale = 224 / padded_bbox[3]
return crop_img, scale
else:
return padded_img, 0
# utils for landmark detection
def scale_trans(img, lm, t, s):
imgw = img.shape[1]
imgh = img.shape[0]
M_s = np.array([[1, 0, -t[0] + imgw//2 + 0.5], [0, 1, -imgh//2 + t[1]]],
dtype=np.float32)
img = cv2.warpAffine(img, M_s, (imgw, imgh))
w = int(imgw / s * 100)
h = int(imgh / s * 100)
img = cv2.resize(img, (w, h))
lm = np.stack([lm[:, 0] - t[0] + imgw // 2, lm[:, 1] -
t[1] + imgh // 2], axis=1) / s * 100
left = w//2 - 112
up = h//2 - 112
bbox = [left, up, 224, 224]
cropped_img, scale2 = crop(img, bbox)
assert(scale2!=0)
t1 = np.array([bbox[0], bbox[1]])
# back to raw img s * crop + s * t1 + t2
t1 = np.array([w//2 - 112, h//2 - 112])
scale = s / 100
t2 = np.array([t[0] - imgw/2, t[1] - imgh / 2])
inv = (scale/scale2, scale * t1 + t2.reshape([2]))
return cropped_img, inv
# utils for landmark detection
def align_for_lm(img, five_points):
five_points = np.array(five_points).reshape([1, 10])
params = loadmat('util/BBRegressorParam_r.mat')
bbox = BBRegression(five_points, params)
assert(bbox[2] != 0)
bbox = np.round(bbox).astype(np.int32)
crop_img, scale = crop(img, bbox)
return crop_img, scale, bbox
# resize and crop images for face reconstruction
def resize_n_crop_img(img, lm, t, s, target_size=224., mask=None):
w0, h0 = img.size
w = (w0*s).astype(np.int32)
h = (h0*s).astype(np.int32)
left = (w/2 - target_size/2 + float((t[0] - w0/2)*s)).astype(np.int32)
right = left + target_size
up = (h/2 - target_size/2 + float((h0/2 - t[1])*s)).astype(np.int32)
below = up + target_size
img = img.resize((w, h), resample=Image.BICUBIC)
img = img.crop((left, up, right, below))
if mask is not None:
mask = mask.resize((w, h), resample=Image.BICUBIC)
mask = mask.crop((left, up, right, below))
lm = np.stack([lm[:, 0] - t[0] + w0/2, lm[:, 1] -
t[1] + h0/2], axis=1)*s
lm = lm - np.reshape(
np.array([(w/2 - target_size/2), (h/2-target_size/2)]), [1, 2])
return img, lm, mask
# utils for face reconstruction
def extract_5p(lm):
lm_idx = np.array([31, 37, 40, 43, 46, 49, 55]) - 1
lm5p = np.stack([lm[lm_idx[0], :], np.mean(lm[lm_idx[[1, 2]], :], 0), np.mean(
lm[lm_idx[[3, 4]], :], 0), lm[lm_idx[5], :], lm[lm_idx[6], :]], axis=0)
lm5p = lm5p[[1, 2, 0, 3, 4], :]
return lm5p
# utils for face reconstruction
def align_img(img, lm, lm3D, mask=None, target_size=224., rescale_factor=102.):
"""
Return:
transparams --numpy.array (raw_W, raw_H, scale, tx, ty)
img_new --PIL.Image (target_size, target_size, 3)
lm_new --numpy.array (68, 2), y direction is opposite to v direction
mask_new --PIL.Image (target_size, target_size)
Parameters:
img --PIL.Image (raw_H, raw_W, 3)
lm --numpy.array (68, 2), y direction is opposite to v direction
lm3D --numpy.array (5, 3)
mask --PIL.Image (raw_H, raw_W, 3)
"""
w0, h0 = img.size
if lm.shape[0] != 5:
lm5p = extract_5p(lm)
else:
lm5p = lm
# calculate translation and scale factors using 5 facial landmarks
# and standard landmarks of a 3D face
t, s = POS(lm5p.transpose(), lm3D.transpose())
s = rescale_factor/s
# processing the image
img_new, lm_new, mask_new = resize_n_crop_img(img, lm, t, s, target_size=target_size, mask=mask)
trans_params = np.array([w0, h0, s, t[0], t[1]])
return trans_params, img_new, lm_new, mask_new
# utils for face recognition model
def estimate_norm(lm_68p, H):
# from https://github.com/deepinsight/insightface/blob/c61d3cd208a603dfa4a338bd743b320ce3e94730/recognition/common/face_align.py#L68
"""
Return:
trans_m --numpy.array (2, 3)
Parameters:
lm --numpy.array (68, 2), y direction is opposite to v direction
H --int/float , image height
"""
lm = extract_5p(lm_68p)
lm[:, -1] = H - 1 - lm[:, -1]
tform = trans.SimilarityTransform()
src = np.array(
[[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366],
[41.5493, 92.3655], [70.7299, 92.2041]],
dtype=np.float32)
tform.estimate(lm, src)
M = tform.params
if np.linalg.det(M) == 0:
M = np.eye(3)
return M[0:2, :]
def estimate_norm_torch(lm_68p, H):
lm_68p_ = lm_68p.detach().cpu().numpy()
M = []
for i in range(lm_68p_.shape[0]):
M.append(estimate_norm(lm_68p_[i], H))
M = torch.tensor(np.array(M), dtype=torch.float32).to(lm_68p.device)
return M
-129
View File
@@ -1,129 +0,0 @@
"""This script is to generate skin attention mask for Deep3DFaceRecon_pytorch
"""
import math
import numpy as np
import os
import cv2
class GMM:
def __init__(self, dim, num, w, mu, cov, cov_det, cov_inv):
self.dim = dim # feature dimension
self.num = num # number of Gaussian components
self.w = w # weights of Gaussian components (a list of scalars)
self.mu= mu # mean of Gaussian components (a list of 1xdim vectors)
self.cov = cov # covariance matrix of Gaussian components (a list of dimxdim matrices)
self.cov_det = cov_det # pre-computed determinet of covariance matrices (a list of scalars)
self.cov_inv = cov_inv # pre-computed inverse covariance matrices (a list of dimxdim matrices)
self.factor = [0]*num
for i in range(self.num):
self.factor[i] = (2*math.pi)**(self.dim/2) * self.cov_det[i]**0.5
def likelihood(self, data):
assert(data.shape[1] == self.dim)
N = data.shape[0]
lh = np.zeros(N)
for i in range(self.num):
data_ = data - self.mu[i]
tmp = np.matmul(data_,self.cov_inv[i]) * data_
tmp = np.sum(tmp,axis=1)
power = -0.5 * tmp
p = np.array([math.exp(power[j]) for j in range(N)])
p = p/self.factor[i]
lh += p*self.w[i]
return lh
def _rgb2ycbcr(rgb):
m = np.array([[65.481, 128.553, 24.966],
[-37.797, -74.203, 112],
[112, -93.786, -18.214]])
shape = rgb.shape
rgb = rgb.reshape((shape[0] * shape[1], 3))
ycbcr = np.dot(rgb, m.transpose() / 255.)
ycbcr[:, 0] += 16.
ycbcr[:, 1:] += 128.
return ycbcr.reshape(shape)
def _bgr2ycbcr(bgr):
rgb = bgr[..., ::-1]
return _rgb2ycbcr(rgb)
gmm_skin_w = [0.24063933, 0.16365987, 0.26034665, 0.33535415]
gmm_skin_mu = [np.array([113.71862, 103.39613, 164.08226]),
np.array([150.19858, 105.18467, 155.51428]),
np.array([183.92976, 107.62468, 152.71820]),
np.array([114.90524, 113.59782, 151.38217])]
gmm_skin_cov_det = [5692842.5, 5851930.5, 2329131., 1585971.]
gmm_skin_cov_inv = [np.array([[0.0019472069, 0.0020450759, -0.00060243998],[0.0020450759, 0.017700525, 0.0051420014],[-0.00060243998, 0.0051420014, 0.0081308950]]),
np.array([[0.0027110141, 0.0011036990, 0.0023122299],[0.0011036990, 0.010707724, 0.010742856],[0.0023122299, 0.010742856, 0.017481629]]),
np.array([[0.0048026871, 0.00022935172, 0.0077668377],[0.00022935172, 0.011729696, 0.0081661865],[0.0077668377, 0.0081661865, 0.025374353]]),
np.array([[0.0011989699, 0.0022453172, -0.0010748957],[0.0022453172, 0.047758564, 0.020332102],[-0.0010748957, 0.020332102, 0.024502251]])]
gmm_skin = GMM(3, 4, gmm_skin_w, gmm_skin_mu, [], gmm_skin_cov_det, gmm_skin_cov_inv)
gmm_nonskin_w = [0.12791070, 0.31130761, 0.34245777, 0.21832393]
gmm_nonskin_mu = [np.array([99.200851, 112.07533, 140.20602]),
np.array([110.91392, 125.52969, 130.19237]),
np.array([129.75864, 129.96107, 126.96808]),
np.array([112.29587, 128.85121, 129.05431])]
gmm_nonskin_cov_det = [458703648., 6466488., 90611376., 133097.63]
gmm_nonskin_cov_inv = [np.array([[0.00085371657, 0.00071197288, 0.00023958916],[0.00071197288, 0.0025935620, 0.00076557708],[0.00023958916, 0.00076557708, 0.0015042332]]),
np.array([[0.00024650150, 0.00045542428, 0.00015019422],[0.00045542428, 0.026412144, 0.018419769],[0.00015019422, 0.018419769, 0.037497383]]),
np.array([[0.00037054974, 0.00038146760, 0.00040408765],[0.00038146760, 0.0085505722, 0.0079136286],[0.00040408765, 0.0079136286, 0.010982352]]),
np.array([[0.00013709733, 0.00051228428, 0.00012777430],[0.00051228428, 0.28237113, 0.10528370],[0.00012777430, 0.10528370, 0.23468947]])]
gmm_nonskin = GMM(3, 4, gmm_nonskin_w, gmm_nonskin_mu, [], gmm_nonskin_cov_det, gmm_nonskin_cov_inv)
prior_skin = 0.8
prior_nonskin = 1 - prior_skin
# calculate skin attention mask
def skinmask(imbgr):
im = _bgr2ycbcr(imbgr)
data = im.reshape((-1,3))
lh_skin = gmm_skin.likelihood(data)
lh_nonskin = gmm_nonskin.likelihood(data)
tmp1 = prior_skin * lh_skin
tmp2 = prior_nonskin * lh_nonskin
post_skin = tmp1 / (tmp1+tmp2) # posterior probability
post_skin = post_skin.reshape((im.shape[0],im.shape[1]))
post_skin = np.round(post_skin*255)
post_skin = post_skin.astype(np.uint8)
post_skin = np.tile(np.expand_dims(post_skin,2),[1,1,3]) # reshape to H*W*3
return post_skin
def get_skin_mask(img_path):
print('generating skin masks......')
names = [i for i in sorted(os.listdir(
img_path)) if 'jpg' in i or 'png' in i or 'jpeg' in i or 'PNG' in i]
save_path = os.path.join(img_path, 'mask')
if not os.path.isdir(save_path):
os.makedirs(save_path)
for i in range(0, len(names)):
name = names[i]
print('%05d' % (i), ' ', name)
full_image_name = os.path.join(img_path, name)
img = cv2.imread(full_image_name).astype(np.float32)
skin_img = skinmask(img)
cv2.imwrite(os.path.join(save_path, name), skin_img.astype(np.uint8))
-31
View File
@@ -1,31 +0,0 @@
# --------- pytorch --------- #
torch>=1.10.0
torchvision>=0.11.0
pytorch-lightning>=1.5.10
torchmetrics>=0.7.0
# --------- hydra --------- #
hydra-core>=1.1.0
hydra-colorlog>=1.1.0
hydra-optuna-sweeper>=1.1.0
# --------- loggers --------- #
# wandb
# neptune-client
# mlflow
# comet-ml
# tensorboard
# --------- linters --------- #
pre-commit # hooks for applying linters on commit
black # code formatting
isort # import sorting
flake8 # code analysis
nbstripout # remove output from jupyter notebooks
# --------- others --------- #
python-dotenv # loading env variables from .env file
rich # beautiful text formatting in terminal
pytest # tests
sh # for running bash commands in some tests
pudb # debugger
-82
View File
@@ -1,82 +0,0 @@
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
from zmq import device
class ImagesDataset(Dataset):
def __init__(self, path_folder:Path):
self.path_folder = path_folder
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
def __len__(self):
return len(self.list_image)
def __getitem__(self, idx):
path_frame = self.list_image[idx]
image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
image = np.asarray(image)
return {"image_name": path_frame.stem, "image": image}
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:7"
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
print(f"load FaceAlignment model in {device}")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos[16:]):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
# check
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
if num_frame == num_ladmk:
print(f"\n Skip: have already done!")
continue
dataset = ImagesDataset(ipath_frame)
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
for k, ibatch in enumerate(dloader):
ibatch_name = ibatch["image_name"]
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
if k%100 == 0:
print(f"batching {k}/{len(dloader)} ... ")
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
# save landmarks
for jldmk, jname in zip(pred, ibatch_name):
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
# break
-175
View File
@@ -1,175 +0,0 @@
import cv2
import numpy as np
from pathlib2 import Path
from skimage.transform import estimate_transform, warp
from torch.utils.data import Dataset, DataLoader
class ImagesDataset(Dataset):
def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=224, scale=1.25, roation_image=False):
'''
path_frames: folder, vpath_image, image path, video path
'''
self.path_frames = Path(path_frames)
self.path_landmk = Path(path_landmk)
self.vpath_image = sorted(self.path_frames.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
print(f'--> total have {len(self.vpath_image)} images, top: \n{self.vpath_image[:3]}')
self.scale = scale # 1.25
self.crop_size = crop_size # 224
self.roation_image =roation_image
def bbox2point(self, left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
def __len__(self):
return len(self.vpath_image)
def __getitem__(self, index):
ipath_frame = self.vpath_image[index]
image_name = ipath_frame.stem # (frame-0000)
# print(f"load ipath_frame --> {ipath_frame}")
ipath_ldmk = self.path_landmk.joinpath(image_name + ".txt")
if not ipath_ldmk.exists():
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
# load orignal image & landmarks
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
# reverse H&W
if self.roation_image:
image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2)
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68')
# crop transform
size = int(old_size * self.scale)
src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top)
[center[0] - size/2, center[1] + size/2], # (left, bottom)
[center[0] + size/2, center[1] - size/2]]) # (right, top)
DST_PTS = np.array([[0, 0], # (left-top-corner)
[0, self.crop_size - 1], # (left-botton corner)
[self.crop_size - 1, 0]]) # (right-top corner)
# tform_params dytpe = float64, shape = (3, 3)
tform = estimate_transform('similarity', src_pts, DST_PTS)
# image = image/255.
# (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2]
# cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1
if cropped_ldmk.shape[0] > 68:
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
cropped_ldmk = cropped_ldmk[:68, :]
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
# cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
# print(f"image dytpe = {image.dtype}, shape = {image.shape} ")
# print(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
# print(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
# print(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
# # print(f"jbatch_ldmks ={cropped_ldmk}")
return {'image_name': ipath_frame.stem,
'image': image,
'cropped_imag': cropped_imag,
'tform_params': tform.params,
'cropped_ldmk': cropped_ldmk,
}
if __name__ == "__main__":
sub_folder = "processing" # processing, body, smile
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{sub_folder}")
vpath_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame
roation_image = True if sub_folder == "body" else False
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_fcrop = ipath_item.joinpath("frames_crop_512")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512")
ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512")
ipath_fcrop.mkdir(parents=True, exist_ok=True)
ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True)
# check
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
if num_frame == num_fcrop:
print(f"\n Skip: have already done!")
continue
# only whole body image, need set roation_image=True
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5, roation_image=roation_image)
dloader = DataLoader(dataset, batch_size=64, num_workers=4, shuffle=False)
for j, jbatch in enumerate(dloader):
# print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}")
if j%100 == 0:
print(f"batching {j}/{len(dloader)} ... ")
jbatch_name = jbatch["image_name"]
jbatch_crop = (255*jbatch["cropped_imag"]).numpy().astype(np.uint8)
jbatch_tfrom = jbatch["tform_params"].numpy()
jbatch_ldmks = jbatch["cropped_ldmk"].numpy()
# print(f"jbatch_crop dytpe = {jbatch_crop.dtype}, shape = {jbatch_crop.shape} ")
# print(f"jbatch_tfrom dytpe = {jbatch_tfrom.dtype}, shape = {jbatch_tfrom.shape} ")
# print(f"jbatch_ldmks dytpe = {jbatch_ldmks.dtype}, shape = {jbatch_ldmks.shape}, max={jbatch_ldmks.max()}, min={jbatch_ldmks.min()} ")
# save data
for k,kname in enumerate(jbatch_name):
kpath_fcrop = ipath_fcrop.joinpath(kname + ".jpg")
kpath_tfrom = ipath_tfrom.joinpath(kname + ".npy")
kpath_lcrop = ipath_lcrop.joinpath(kname + ".txt")
if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
continue
np.save(kpath_tfrom, jbatch_tfrom[k])
np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d")
cv2.imwrite(str(kpath_fcrop), jbatch_crop[k])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# break
-81
View File
@@ -1,81 +0,0 @@
from torch.utils.data import Dataset, DataLoader
import cv2
import torch
import numpy as np
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
from zmq import device
class ImagesDataset(Dataset):
def __init__(self, path_folder:Path):
self.path_folder = path_folder
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
def __len__(self):
return len(self.list_image)
def __getitem__(self, idx):
path_frame = self.list_image[idx]
# image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
# image = np.asarray(image)
image = cv2.imread(str(path_frame)).astype(np.float32)
return {"image_name": path_frame.stem, "image": image}
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:7"
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
print(f"load FaceAlignment model in {device}")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos[16:]):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_frame = ipath_item.joinpath("frames")
ipath_mask = ipath_item.joinpath("skin_mask")
ipath_mask.mkdir(parents=True, exist_ok=True)
# check
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_mask = len(list(ipath_mask.glob("*.jpg")))
if num_frame == num_mask:
print(f"\n Skip: have already done!")
continue
vframe_frame = list(ipath_frame.glob("*.jpg"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
for k, kpath_ in enumerate(dloader):
ibatch_name = ibatch["image_name"]
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
if k%100 == 0:
print(f"batching {k}/{len(dloader)} ... ")
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
# save landmarks
for jldmk, jname in zip(pred, ibatch_name):
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
# break
-31
View File
@@ -1,31 +0,0 @@
import os
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
vpath_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_fcrop = ipath_item.joinpath("frames_crop")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform")
if ipath_fcrop.exists():
cmd = f"rm -rf {str(ipath_fcrop)}"
print("RUN: ", cmd)
os.system(cmd)
if ipath_tfrom.exists():
cmd = f"rm -rf {str(ipath_tfrom)}"
print("RUN: ", cmd)
os.system(cmd)
-100
View File
@@ -1,100 +0,0 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
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_frame = ipath_data.joinpath("frames")
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():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
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)
# # pad one
# feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge")
# feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge")
# feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge")
if nframes == 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"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
@@ -1,159 +0,0 @@
import json
import numpy as np
from pathlib2 import Path
import torchaudio
if __name__ == "__main__":
# path_data = Path("/mfs/lsen/DATA/Actor4/smile")
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
path_save = Path('data/Actor5/Actor5-raw-3h') # processing
# path_save = Path('data/Actor5/Actor5-smile-1h') # 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 = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
# # actor5 raw
vid_test = set(["4R3A0063", "4R3A0071"])
vid_valid = set(["4R3A0063", "4R3A0071"])
vid_train = vids - vid_test - vid_valid
# actor5 smile
# vid_test = set(["4R3A0071"])
# vid_valid = set(["4R3A0071"])
# vid_train = set(["4R3A0070", "4R3A0072", "4R3A0073", "4R3A0074", "4R3A0075"])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
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_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
print(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# ####################################
# # clips 4min
# nclip = 4
# nframes = nclip * 60 * 50 # min * 60s * fps
# nsegmts = nclip * 60 * 16000 # min * 60s * sr
# data_motion = data_motion[:nframes]
# audio_raw = audio_raw[:nsegmts]
# data_idn = data_idn[:nframes]
# ####################################
if vid in vid_train:
durations_train += nframes/fps
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
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"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})")
# print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
@@ -1,159 +0,0 @@
import json
from loguru import logger
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
subfolder = "processing" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{subfolder}")
path_save = Path(f'data/Actor5/data-list-{subfolder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save)
# get files
v_dir_videos = sorted(path_data.glob("*"))
logger.info(f"Have {len(v_dir_videos)} dir files")
vids = set([ipath.stem for ipath in v_dir_videos])
logger.info(f"vids total= {vids}")
# # # actor5 raw
# vid_test = set(["4R3A0063", "4R3A0071"])
# vid_valid = set(["4R3A0063", "4R3A0071"])
# vid_train = vids - vid_test - vid_valid
# actor5 smile
if subfolder == "smile":
vid_test = set(["4R3A0071"])
vid_valid = set(["4R3A0071"])
vid_train = set(["4R3A0070", "4R3A0072", "4R3A0073", "4R3A0074", "4R3A0075", "4R3A0076"])
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0063", "4R3A0071"])
vid_valid = set(["4R3A0063", "4R3A0071"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_test = [], [], []
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
logger.info(f"\n\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512
ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
ipath_parse = ipath_data.joinpath("frames_crop_parse_512") # cropped mask
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") # audio path
# check info existing
if not ipath_info.exists():
logger.info(f"NOT existing {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
assert fps == 50, "fps should be 50"
logger.info(f"info={info}, duration = {nframes/fps}")
# check files total exists
num_coeff = len(list(ipath_coeff.glob("*.npy")))
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
num_parse = len(list(ipath_parse.glob("*.npy")))
if (num_coeff != nframes) or (num_frame != nframes) or (num_ldmks != nframes) or (num_parse != nframes):
logger.info(f"num of ipath_coeff ({num_coeff}) shoud be {nframes} > {ipath_coeff}")
logger.info(f"num of ipath_frame ({num_frame}) shoud be {nframes} > {ipath_frame}")
logger.info(f"num of ipath_ldmks ({num_ldmks}) shoud be {nframes} > {ipath_ldmks}")
logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}")
continue
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
if vid in vid_train:
durations_train += nframes/fps
list_train.append(vid)
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_speech": audio_raw,
"path_data": str(ipath_data)
}
if vid in vid_valid:
durations_valid += nframes/fps
list_valid.append(vid)
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_speech": audio_raw,
"path_data": str(ipath_data)
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_speech": audio_raw,
"path_data": str(ipath_data)
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_test} ")
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)
logger.info(f"--> {path_save}")
-7
View File
@@ -1,7 +0,0 @@
#!/bin/bash
# Shedule execution of many runs
# Run from root folder with: bash scripts/schedule.sh
python train.py trainer.max_epochs=5
python train.py trainer.max_epochs=10 logger=csv
-36
View File
@@ -1,36 +0,0 @@
[isort]
line_length = 99
profile = black
filter_files = True
[flake8]
max_line_length = 99
show_source = True
format = pylint
ignore =
F401 # Module imported but unused
W504 # Line break occurred after a binary operator
F841 # Local variable name is assigned to but never used
E501 # Line too long
exclude =
.git
__pycache__
data/*
tests/*
notebooks/*
logs/*
[tool:pytest]
testpaths = tests/
log_cli = True
markers =
slow
addopts =
--durations=0
--strict-markers
--doctest-modules
filterwarnings =
ignore::DeprecationWarning
ignore::UserWarning
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
-99
View File
@@ -1,99 +0,0 @@
import numpy as np
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
import logging
class MotionEvalDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(
self,
path_data = "./data_valid.npz", # opt.DATASET.root
fps = 50, # opt.DATASET.fps
sr = 16000, # opt.DATASET.sr
num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
filter = "savgol",
):
super(MotionEvalDataset, self).__init__()
logging.info(f"load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.overlap = 0.5
self.filter = filter
self.nsteps_frame = num_windows * fps
self.nsteps_segmt = num_windows * sr
self.annodb_accums = self.count_annotations()
logging.info(f'''num_pid={self.num_pid}, niters={self.annodb_accums[-1]}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
return self.annodb_accums[-1]
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, ikey in enumerate(self.annodb):
acc += self.annodb[ikey]["data_motion"].shape[0] // (self.nsteps_frame * (1-self.overlap)) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
for i, iacc in enumerate(self.annodb_accums):
if idx > iacc -1 and idx < self.annodb_accums[i+1]:
pid, new_idx = i, idx - iacc
break
# logging.info(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}")
# return item
vid = self.pids[pid]
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
beg_frame = new_idx
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# logging.info(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
# logging.info(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}")
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
}
return result
@@ -1,181 +0,0 @@
import time
import logging
from pathlib import Path
import numpy as np
from skimage.io import imread
from torch.utils.data import Dataset
from scipy.signal import savgol_filter
class MotionRenderTrainDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(
self,
path_data = "../data_train.npz", # opt.DATASET.root
fps = 50, # opt.DATASET.fps
sr = 16000, # opt.DATASET.sr
num_second_wind = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
filter = "savgol",
):
super(MotionRenderTrainDataset, self).__init__()
logging.info(f"load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.image_size = 512
self.filter = filter
self.nsteps_frame = num_second_wind * fps
self.nsteps_segmt = num_second_wind * sr
self.overlap = 0.2
self.annodb_accums = self.count_annotations()
logging.info(f'''num_pid={self.num_pid}, niters={self.__len__()}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
# return self.annodb_accums[-1]
return 20000
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, ikey in enumerate(self.annodb):
# logging.info(f"i = {i}, ikey={ikey}, nframe = {self.annodb[ikey]["nframe"]}")
acc += self.annodb[ikey]["nframe"] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_speech = data["data_speech"] # (nsegemts, )
nframe = data["nframe"] # nframe of this video
nsegmt = data_speech.shape[0] # nsegmt of correspoding audio
path_data = Path(data["path_data"]) # "xxx/xxx/Actor5/processing/4R3A0073"
path_coeff = path_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
path_frame = path_data.joinpath("frames_crop_512") # cropped image 512x512
path_ldmks = path_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
path_parse = path_data.joinpath("frames_crop_parse_512") # cropped mask
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# logging.info(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
# load image & landmark & mask
data_frame, data_ldmk, data_mask, data_coeff = [], [], [], []
for iframe in range(beg_frame, end_frame):
ipath_frame = path_frame.joinpath(f"frame-{iframe:06d}.jpg")
ipath_ldmks = path_ldmks.joinpath(f"frame-{iframe:06d}.txt")
ipath_parse = path_parse.joinpath(f"frame-{iframe:06d}.npy")
ipath_coeff = path_coeff.joinpath(f"frame-{iframe:06d}.json.npy")
idata_frame = imread(str(ipath_frame)) / 255 # (512, 512, 3), normalize to 0-1
idata_ldmk = np.loadtxt(ipath_ldmks)[:, :2] # (68, 2)
idata_mask = self.load_mask(ipath_parse) # (512, 512)
idata_coeff = self.load_coeff(ipath_coeff) # (256, )
# normalized kpt, why ?
idata_ldmk = idata_ldmk / self.image_size * 2 - 1
# add to list
data_frame.append(idata_frame.transpose(2,0,1)) # (3, 512, 512)
data_ldmk.append(idata_ldmk) # (68, 2)
data_mask.append(idata_mask) # (512, 512)
data_coeff.append(idata_coeff) # (236, )
# concate to numpy
data_frame = np.array(data_frame).astype(np.float32) # (nsteps_frame, 3, 512, 512)
data_ldmk = np.array(data_ldmk).astype(np.float32) # (nsteps_frame, 68, 2)
data_mask = np.array(data_mask).astype(np.float32) # (nsteps_frame, 512, 512)
data_coeff = np.array(data_coeff).astype(np.float32) # (nsteps_frame, 236)
# logging.info(f"data_frame = {data_frame.shape}, dtype={data_frame.dtype}")
# logging.info(f"data_ldmk = {data_ldmk.shape}, dtype={data_ldmk.dtype}")
# logging.info(f"data_mask = {data_mask.shape}, dtype={data_mask.dtype}")
# logging.info(f"data_coeff = {data_coeff.shape}, dtype={data_coeff.dtype}")
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.filter == "savgol":
data_coeff = savgol_filter(data_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
data_ldmk = savgol_filter(data_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: shuffle speed
result = {
"data_audio": data_speech, # (nsteps_frame, dim_speech)
"data_frame": data_frame, # (nsteps_frame, 3, 512, 512)
"data_mask": data_mask, # (nsteps_frame, 512, 512)
"data_ldmk": data_ldmk, # (nsteps_frame, 68, 2)
"data_coeff": data_coeff, # (nsteps_frame, 236)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def load_coeff(self, path_coeff):
codedict = np.load(path_coeff, allow_pickle=True).item() # dict of {}
params = ['shape', 'tex', 'exp', 'pose', 'cam', 'light']
# dim of shape = 100, tex = 50, exp = 50, pose = 6, cam = 3, light = 27
coeff = []
for ikey in params:
coeff += list(codedict[ikey].reshape(-1))
# assert len(coeff) == 236, f"coeff len = {len(coeff)} should be 236 !"
return np.array(coeff)
def load_mask(self, path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno) # (512, 512)
atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
atts_selected = ['skin', 'l_brow', 'r_brow', 'nose', 'u_lip', 'l_lip']
class_contains = np.unique(parsing_anno)
for iclass, iatt in enumerate(atts, 1):
if (iatt in atts_selected) and (iclass in class_contains):
index = np.where(parsing_anno == iclass)
mask[index[0], index[1]] = 1
return mask
-157
View File
@@ -1,157 +0,0 @@
import numpy as np
import time
import random
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
import logging
# common
from src.utils.resampling import resample_by_nsteps
class MotionTrainDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(
self,
path_data = "../data_train.npz", # opt.DATASET.root
fps = 50, # opt.DATASET.fps
sr = 16000, # opt.DATASET.sr
num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
filter = "savgol",
flip = False,
shifting_speed = False,
):
super(MotionTrainDataset, self).__init__()
logging.info(f"load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.filter = filter
self.nsteps_frame = num_windows * fps
self.nsteps_segmt = num_windows * sr
# others augments
self.flip = flip
self.shifting_speed = shifting_speed
self.overlap = 0.2
self.annodb_accums = self.count_annotations()
# logging.info(f'''num_pid={self.num_pid}, niters={self.annodb_accums[-1]}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''')
logging.info(f'''num_pid={self.num_pid}, niters={self.__len__()}, nsteps_frame={self.nsteps_frame}, nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
# return self.annodb_accums[-1]
return 20000
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, ikey in enumerate(self.annodb):
# logging.info(f"i = {i}, ikey={ikey}, shape = {self.annodb[ikey]['data_motion'].shape}")
acc += self.annodb[ikey]["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
if self.shifting_speed and random.random() < 0.3:
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5)
end_frame = beg_frame + int(self.nsteps_frame * speed)
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + int(self.nsteps_segmt * speed)
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
# logging.info(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
# resample to same nsteps
data_motion = resample_by_nsteps(data_motion, nsteps_tgt=self.nsteps_frame)
data_speech = resample_by_nsteps(data_speech, nsteps_tgt=self.nsteps_segmt)
# logging.info(f"resampling > data_speech shape={data_speech.shape} data_motion shape={data_motion.shape} \n")
else:
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# logging.info(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: reverse
if self.flip:
data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3)
# logging.info(f"flip: data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# random augments: shuffle speed
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def make_auguments_flip(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1].copy()
data_speech = data_speech[::-1].copy()
return data_motion, data_speech
-232
View File
@@ -1,232 +0,0 @@
import os
import torch
import numpy as np
from skimage.io import imread
from skimage.transform import estimate_transform, warp
from torch.utils.data import Dataset
class VGGFace2Dataset(Dataset):
def __init__(self, K, image_size, scale, trans_scale = 0, isTemporal=False, isEval=False, isSingle=False):
'''
K must be less than 6
'''
self.K = K
self.image_size = image_size
self.imagefolder = '/ps/scratch/face2d3d/train'
self.kptfolder = '/ps/scratch/face2d3d/train_annotated_torch7'
self.segfolder = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_seg/test_crop_size_400_batch'
# hq:
# datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_bbx_size_bigger_than_400_train_list_max_normal_100_ring_5_1_serial.npy'
datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_train_list_max_normal_100_ring_5_1_serial.npy'
if isEval:
datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_val_list_max_normal_100_ring_5_1_serial.npy'
self.data_lines = np.load(datafile).astype('str')
self.isTemporal = isTemporal
self.scale = scale #[scale_min, scale_max]
self.trans_scale = trans_scale #[dx, dy]
self.isSingle = isSingle
if isSingle:
self.K = 1
def __len__(self):
return len(self.data_lines)
def __getitem__(self, idx):
images_list = [];
kpt_list = [];
mask_list = []
random_ind = np.random.permutation(5)[:self.K]
for i in random_ind:
name = self.data_lines[idx, i]
image_path = os.path.join(self.imagefolder, name + '.jpg')
seg_path = os.path.join(self.segfolder, name + '.npy')
kpt_path = os.path.join(self.kptfolder, name + '.npy')
image = imread(image_path)/255.
kpt = np.load(kpt_path)[:,:2]
mask = self.load_mask(seg_path, image.shape[0], image.shape[1])
### crop information
tform = self.crop(image, kpt)
## crop
cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_mask = warp(mask, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
# normalized kpt
cropped_kpt[:,:2] = cropped_kpt[:,:2]/self.image_size * 2 - 1
images_list.append(cropped_image.transpose(2,0,1))
kpt_list.append(cropped_kpt)
mask_list.append(cropped_mask)
###
images_array = torch.from_numpy(np.array(images_list)).type(dtype = torch.float32) # (K, 224, 224, 3)
kpt_array = torch.from_numpy(np.array(kpt_list)).type(dtype = torch.float32) # (K, 68, 2)
mask_array = torch.from_numpy(np.array(mask_list)).type(dtype = torch.float32) # (K, 224, 224, 3)
if self.isSingle:
images_array = images_array.squeeze()
kpt_array = kpt_array.squeeze()
mask_array = mask_array.squeeze()
data_dict = {
'image': images_array,
'landmark': kpt_array,
'mask': mask_array
}
return data_dict
def crop(self, image, kpt):
left = np.min(kpt[:,0]); right = np.max(kpt[:,0]);
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
h, w, _ = image.shape
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top) / 2.0 ])#+ old_size*0.1])
# translate center
trans_scale = (np.random.rand(2)*2 -1) * self.trans_scale # 0
center = center + trans_scale*old_size # 0.5
scale = np.random.rand() * (self.scale[1] - self.scale[0]) + self.scale[0]
size = int(old_size*scale)
# crop image
src_pts = np.array([[center[0]-size/2, center[1]-size/2], [center[0] - size/2, center[1]+size/2], [center[0]+size/2, center[1]-size/2]])
DST_PTS = np.array([[0,0], [0,self.image_size - 1], [self.image_size - 1, 0]])
tform = estimate_transform('similarity', src_pts, DST_PTS)
# cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
# # change kpt accordingly
# cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
return tform
def load_mask(self, maskpath, h, w):
# print(maskpath)
if os.path.isfile(maskpath):
vis_parsing_anno = np.load(maskpath)
# atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
mask = np.zeros_like(vis_parsing_anno)
# for i in range(1, 16):
mask[vis_parsing_anno>0.5] = 1.
else:
mask = np.ones((h, w))
return mask
class VGGFace2HQDataset(Dataset):
def __init__(self, K, image_size, scale, trans_scale = 0, isTemporal=False, isEval=False, isSingle=False):
'''
K must be less than 6
'''
self.K = K
self.image_size = image_size
self.imagefolder = '/ps/scratch/face2d3d/train'
self.kptfolder = '/ps/scratch/face2d3d/train_annotated_torch7'
self.segfolder = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_seg/test_crop_size_400_batch'
# hq:
# datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_bbx_size_bigger_than_400_train_list_max_normal_100_ring_5_1_serial.npy'
datafile = '/ps/scratch/face2d3d/texture_in_the_wild_code/VGGFace2_cleaning_codes/ringnetpp_training_lists/second_cleaning/vggface2_bbx_size_bigger_than_400_train_list_max_normal_100_ring_5_1_serial.npy'
self.data_lines = np.load(datafile).astype('str')
self.isTemporal = isTemporal
self.scale = scale #[scale_min, scale_max]
self.trans_scale = trans_scale #[dx, dy]
self.isSingle = isSingle
if isSingle:
self.K = 1
def __len__(self):
return len(self.data_lines)
def __getitem__(self, idx):
images_list = []; kpt_list = []; mask_list = []
for i in range(self.K):
name = self.data_lines[idx, i]
image_path = os.path.join(self.imagefolder, name + '.jpg')
seg_path = os.path.join(self.segfolder, name + '.npy')
kpt_path = os.path.join(self.kptfolder, name + '.npy')
image = imread(image_path)/255.
kpt = np.load(kpt_path)[:,:2]
mask = self.load_mask(seg_path, image.shape[0], image.shape[1])
### crop information
tform = self.crop(image, kpt)
## crop
cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_mask = warp(mask, tform.inverse, output_shape=(self.image_size, self.image_size))
cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
# normalized kpt
cropped_kpt[:,:2] = cropped_kpt[:,:2]/self.image_size * 2 - 1
images_list.append(cropped_image.transpose(2,0,1))
kpt_list.append(cropped_kpt)
mask_list.append(cropped_mask)
###
images_array = torch.from_numpy(np.array(images_list)).type(dtype = torch.float32) #K,224,224,3
kpt_array = torch.from_numpy(np.array(kpt_list)).type(dtype = torch.float32) #K,224,224,3
mask_array = torch.from_numpy(np.array(mask_list)).type(dtype = torch.float32) #K,224,224,3
if self.isSingle:
images_array = images_array.squeeze()
kpt_array = kpt_array.squeeze()
mask_array = mask_array.squeeze()
data_dict = {
'image': images_array,
'landmark': kpt_array,
'mask': mask_array
}
return data_dict
def crop(self, image, kpt):
left = np.min(kpt[:,0]); right = np.max(kpt[:,0]);
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
h, w, _ = image.shape
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0, bottom - (bottom - top) / 2.0 ])#+ old_size*0.1])
# translate center
trans_scale = (np.random.rand(2)*2 -1) * self.trans_scale
center = center + trans_scale*old_size # 0.5
scale = np.random.rand() * (self.scale[1] - self.scale[0]) + self.scale[0]
size = int(old_size*scale)
# crop image
src_pts = np.array([[center[0]-size/2, center[1]-size/2], [center[0] - size/2, center[1]+size/2], [center[0]+size/2, center[1]-size/2]])
DST_PTS = np.array([[0,0], [0,self.image_size - 1], [self.image_size - 1, 0]])
tform = estimate_transform('similarity', src_pts, DST_PTS)
# cropped_image = warp(image, tform.inverse, output_shape=(self.image_size, self.image_size))
# # change kpt accordingly
# cropped_kpt = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # np.linalg.inv(tform.params)
return tform
def load_mask(self, maskpath, h, w):
# print(maskpath)
if os.path.isfile(maskpath):
vis_parsing_anno = np.load(maskpath)
# atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
mask = np.zeros_like(vis_parsing_anno)
# for i in range(1, 16):
mask[vis_parsing_anno>0.5] = 1.
else:
mask = np.ones((h, w))
return mask
-101
View File
@@ -1,101 +0,0 @@
from typing import Optional, Tuple
import torch
from pytorch_lightning import LightningDataModule
from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
from torchvision.datasets import MNIST
from torchvision.transforms import transforms
class MNISTDataModule(LightningDataModule):
"""
Example of LightningDataModule for MNIST dataset.
A DataModule implements 5 key methods:
- prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)
- setup (things to do on every accelerator in distributed mode)
- train_dataloader (the training dataloader)
- val_dataloader (the validation dataloader(s))
- test_dataloader (the test dataloader(s))
This allows you to share a full dataset without explaining how to download,
split, transform and process the data.
Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html
"""
def __init__(
self,
data_dir: str = "data/",
train_val_test_split: Tuple[int, int, int] = (55_000, 5_000, 10_000),
batch_size: int = 64,
num_workers: int = 0,
pin_memory: bool = False,
):
super().__init__()
# this line allows to access init params with 'self.hparams' attribute
self.save_hyperparameters(logger=False)
# data transformations
self.transforms = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
)
self.data_train: Optional[Dataset] = None
self.data_val: Optional[Dataset] = None
self.data_test: Optional[Dataset] = None
@property
def num_classes(self) -> int:
return 10
def prepare_data(self):
"""Download data if needed. This method is called only from a single GPU.
Do not use it to assign state (self.x = y)."""
MNIST(self.hparams.data_dir, train=True, download=True)
MNIST(self.hparams.data_dir, train=False, download=True)
def setup(self, stage: Optional[str] = None):
"""Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
This method is called by lightning twice for `trainer.fit()` and `trainer.test()`, so be careful if you do a random split!
The `stage` can be used to differentiate whether it's called before trainer.fit()` or `trainer.test()`."""
# load datasets only if they're not loaded already
if not self.data_train and not self.data_val and not self.data_test:
trainset = MNIST(self.hparams.data_dir, train=True, transform=self.transforms)
testset = MNIST(self.hparams.data_dir, train=False, transform=self.transforms)
dataset = ConcatDataset(datasets=[trainset, testset])
self.data_train, self.data_val, self.data_test = random_split(
dataset=dataset,
lengths=self.hparams.train_val_test_split,
generator=torch.Generator().manual_seed(42),
)
def train_dataloader(self):
return DataLoader(
dataset=self.data_train,
batch_size=self.hparams.batch_size,
num_workers=self.hparams.num_workers,
pin_memory=self.hparams.pin_memory,
shuffle=True,
)
def val_dataloader(self):
return DataLoader(
dataset=self.data_val,
batch_size=self.hparams.batch_size,
num_workers=self.hparams.num_workers,
pin_memory=self.hparams.pin_memory,
shuffle=False,
)
def test_dataloader(self):
return DataLoader(
dataset=self.data_test,
batch_size=self.hparams.batch_size,
num_workers=self.hparams.num_workers,
pin_memory=self.hparams.pin_memory,
shuffle=False,
)
-76
View File
@@ -1,76 +0,0 @@
from typing import Optional
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader, Dataset
class MotionDataModule(LightningDataModule):
"""
Example of LightningDataModule for MNIST dataset.
A DataModule implements 5 key methods:
- prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)
- setup (things to do on every accelerator in distributed mode)
- train_dataloader (the training dataloader)
- val_dataloader (the validation dataloader(s))
- test_dataloader (the test dataloader(s))
This allows you to share a full dataset without explaining how to download,
split, transform and process the data.
Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html
"""
def __init__(
self,
batch_size_train: int = 128,
batch_size_test: int = 32,
num_workers: int = 0,
pin_memory: bool = False,
dataset_train: Optional[Dataset] = None,
dataset_valid: Optional[Dataset] = None,
dataset_test : Optional[Dataset] = None,
):
super().__init__()
# this line allows to access init params with 'self' attribute
# self.save_hyperparameters(logger=False)
self.batch_size_train = batch_size_train
self.batch_size_test = batch_size_test
self.num_workers = num_workers
self.pin_memory = pin_memory
self.dataset_train = dataset_train
self.dataset_valid = dataset_valid
self.dataset_test = dataset_test
def train_dataloader(self):
return DataLoader(
dataset=self.dataset_train,
batch_size=self.batch_size_train,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
drop_last=False,
shuffle=True,
)
def val_dataloader(self):
return DataLoader(
dataset=self.dataset_valid,
batch_size=self.batch_size_train,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
drop_last=False,
shuffle=False,
)
def test_dataloader(self):
return DataLoader(
dataset=self.dataset_test,
batch_size=self.batch_size_test,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
drop_last=False,
shuffle=False,
)
-87
View File
@@ -1,87 +0,0 @@
# -*- 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:
iname_full = f"lambda_{iname}"
if iname_full in opt.LOSS.keys() and opt.LOSS[iname_full] > 0:
self.weight[ "loss_"+iname ] = opt.LOSS[iname_full]
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())
-12
View File
@@ -1,12 +0,0 @@
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"
]
View File
Whitespace-only changes.
-115
View File
@@ -1,115 +0,0 @@
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
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more