From b4c197a8ac4fda4177bc8e7c0b74ecc92fee3af0 Mon Sep 17 00:00:00 2001 From: liangsen Date: Sat, 14 May 2022 23:20:55 +0800 Subject: [PATCH] beta add render --- common/__init__.py | 0 common/animation.py | 343 ++++++++++++ common/debug.py | 9 + common/functions.py | 135 +++++ common/geometry.py | 121 ++++ common/image.py | 41 ++ common/landmark.py | 254 +++++++++ common/logger.py | 87 +++ common/resampling.py | 39 ++ common/utils.py | 516 ++++++++++++++++++ common/vis.py | 313 +++++++++++ configs/callbacks/callback_audio2render.yaml | 36 ++ configs/dataset/motion_audio2render.yaml | 32 ++ .../train_audio2render_20220513.yaml | 61 +++ configs/model/model_audio2render.yaml | 60 ++ scripts/Actor5Data/run-21-features-3dmm.py | 100 ++++ .../run-41-train-dict-data-raw-deca.py | 159 ++++++ .../run-42-train-split-data-list.py | 159 ++++++ .../components/motion_render_train.py | 181 ++++++ src/datasets/components/vggface.py | 232 ++++++++ src/datasets/motion_datamodule.py | 1 - src/losses/lossfunc.py | 43 +- src/mesh/FLAME.py | 47 +- src/mesh/renderer.py | 25 +- src/mesh/util.py | 12 + src/models/__init__.py | 15 +- src/models/components/audio2coeff.py | 72 --- src/models/components/audio2motion.py | 89 +++ ..._audio2coeff.py => module_audio2render.py} | 261 ++++----- src/utils/debug.py | 2 +- 30 files changed, 3210 insertions(+), 235 deletions(-) create mode 100644 common/__init__.py create mode 100644 common/animation.py create mode 100644 common/debug.py create mode 100644 common/functions.py create mode 100644 common/geometry.py create mode 100644 common/image.py create mode 100644 common/landmark.py create mode 100644 common/logger.py create mode 100644 common/resampling.py create mode 100644 common/utils.py create mode 100644 common/vis.py create mode 100644 configs/callbacks/callback_audio2render.yaml create mode 100644 configs/dataset/motion_audio2render.yaml create mode 100644 configs/experiment/audio2render/train_audio2render_20220513.yaml create mode 100644 configs/model/model_audio2render.yaml create mode 100644 scripts/Actor5Data/run-21-features-3dmm.py create mode 100644 scripts/Actor5Data/run-41-train-dict-data-raw-deca.py create mode 100644 scripts/Actor5Data/run-42-train-split-data-list.py create mode 100644 src/datasets/components/motion_render_train.py create mode 100644 src/datasets/components/vggface.py delete mode 100644 src/models/components/audio2coeff.py create mode 100644 src/models/components/audio2motion.py rename src/models/{module_audio2coeff.py => module_audio2render.py} (72%) diff --git a/common/__init__.py b/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/common/animation.py b/common/animation.py new file mode 100644 index 0000000..5364dcc --- /dev/null +++ b/common/animation.py @@ -0,0 +1,343 @@ +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() + + diff --git a/common/debug.py b/common/debug.py new file mode 100644 index 0000000..13c72cb --- /dev/null +++ b/common/debug.py @@ -0,0 +1,9 @@ + +def debug(opt=None, msg="", verbose=False): + + if opt is None or verbose: + print(msg) + + if opt.DEBUG or verbose: + print(msg) + diff --git a/common/functions.py b/common/functions.py new file mode 100644 index 0000000..f598abd --- /dev/null +++ b/common/functions.py @@ -0,0 +1,135 @@ +import torch + + +# target, torch.Tensor, (Bx2x16, 68, 2) +def get_mouth_width(landmark): + """ Get mouth width between L48 and L54 + Params: + landmark: torch, (N, 68, 2) + Return: + tensor, (N,) + """ + + WM = (landmark[:, 48, :] - landmark[:, 54, :]) * (landmark[:, 48, :] - landmark[:, 54, :]) # (N, 2) + WM = torch.sqrt(WM[:, 0] + WM[:, 1]) + + return WM + +def get_mouth_open_param(landmark, eps=1e-6): + """ Get mouth open distance and rate + Params: + landmark: torch, (N, 68, 2) + Return: + two tensors: lip distance and open rate (N,), (N, ) + """ + up = 0.5 * (landmark[:, 50, :] + landmark[:, 52, :]) + dw = 0.5 * (landmark[:, 56, :] + landmark[:, 58, :]) + + distance = (up - dw) * (up -dw) # (N, 2) + distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, ) + width = get_mouth_width(landmark) + rate = distance / (width + eps) + rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1 + + # assert torch.any(torch.isnan(rate)), f"rate have nan" + + # if torch.any(torch.isnan(rate)) or torch.any(torch.isinf(rate)) : + # # print("KKKKKK,",rate) + # for i, item in enumerate(rate): + # if torch.isnan(item) or torch.isinf(item): + # print(f"error mouth nan, item = {item} distance = {distance[i]}, width={width[i]}, data = {landmark[i, [50,52,56,58]]}") + + + return distance, rate + + +def get_eye_width(landmark): + """ Get left eye width between L36 and L39, and right eye width between L42 and L45 + Params: + landmark: torch, (N, 68, 2) + Return: + two tensor of left and right eye width , (N,), (N,) + """ + return get_left_eye_width(landmark), get_right_eye_width(landmark) + +def get_left_eye_width(landmark): + """ Get left eye width between L36 and L39, and right eye width between L42 and L45 + Params: + landmark: torch, (N, 68, 2) + Return: + two tensor of left and right eye width , (N,), (N,) + """ + + WL = (landmark[:, 36, :] - landmark[:, 39, :]) * (landmark[:, 36, :] - landmark[:, 39, :]) # (N, 2) + WL = torch.sqrt(WL[:, 0] + WL[:, 1]) + + return WL + + +def get_right_eye_width(landmark): + """ Get left eye width between L36 and L39, and right eye width between L42 and L45 + Params: + landmark: torch, (N, 68, 2) + Return: + two tensor of left and right eye width , (N,), (N,) + """ + WR = (landmark[:, 42, :] - landmark[:, 45, :]) * (landmark[:, 42, :] - landmark[:, 45, :]) # (N, 2) + WR = torch.sqrt(WR[:, 0] + WR[:, 1]) + + return WR + + +def get_eye_open_param(landmark): + """ Get left/right eye open distance and rate + Params: + landmark: torch, (N, 68, 2) + Return: + four tensors: left/right eye distance and open rate (N,), (N, ) + """ + L_dist, L_rate = get_left_eye_open_param(landmark) + R_dist, R_rate = get_right_eye_open_param(landmark) + + return L_dist, L_rate, R_dist, R_rate + +def get_left_eye_open_param(landmark, eps=1e-6): + """ Get left eye open distance and rate + Params: + landmark: torch, (N, 68, 2) + Return: + four tensors: left eye distance and open rate (N,), (N, ) + """ + up = 0.5 * (landmark[:, 37, :] + landmark[:, 38, :]) + dw = 0.5 * (landmark[:, 40, :] + landmark[:, 41, :]) + + distance = (up - dw) * (up -dw) # (N, 2) + distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, ) + width = get_left_eye_width(landmark) + + rate = distance / (width + eps) + rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1 + + # if torch.any(torch.isnan(rate)) or torch.any(torch.isinf(rate)) : + # # print("KKKKKK,",rate) + # for i, item in enumerate(rate): + # if torch.isnan(item) or torch.isinf(item): + # print(f"error eye nan, item = {item} distance = {distance[i]}, width={width[i]}, data = {landmark[i, 37:42]}") + + return distance, rate + + +def get_right_eye_open_param(landmark, eps = 1e-6): + """ Get left eye open distance and rate + Params: + landmark: torch, (N, 68, 2) + Return: + four tensors: left eye distance and open rate (N,), (N, ) + """ + up = 0.5 * (landmark[:, 43, :] + landmark[:, 44, :]) + dw = 0.5 * (landmark[:, 46, :] + landmark[:, 47, :]) + + distance = (up - dw) * (up -dw) # (N, 2) + distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, ) + rate = distance / (get_left_eye_width(landmark) + eps) + rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1 + + return distance, rate \ No newline at end of file diff --git a/common/geometry.py b/common/geometry.py new file mode 100644 index 0000000..064d309 --- /dev/null +++ b/common/geometry.py @@ -0,0 +1,121 @@ +""" +This utils for geometry transform and carera projection +""" +import torch +import torch.nn as nn +import numpy as np + +import render_util + +def euler2rot(euler): + """Convert euler to rotation matrix + params: + euler: torch.Tensor, (nbatch, 3) + return: + rotation matrix, torch.Tensor, (nbtach, 3, 3) + """ + batch_size = euler.shape[0] + theta = euler[:, 0].reshape(-1, 1, 1) + phi = euler[:, 1].reshape(-1, 1, 1) + psi = euler[:, 2].reshape(-1, 1, 1) + ones = torch.ones((batch_size, 1, 1), dtype=torch.float32, device=euler.device) + zero = torch.zeros((batch_size, 1, 1), dtype=torch.float32, device=euler.device) + + rot_x = torch.cat(( # (nbatch, 3, 3) + torch.cat((ones, zero, zero), 1), #(nbatch, 3, 1) + torch.cat((zero, theta.cos(), theta.sin()), 1), #(nbatch, 3, 1) + torch.cat((zero, -theta.sin(), theta.cos()), 1), #(nbatch, 3, 1) + ), 2) + + rot_y = torch.cat(( + torch.cat((phi.cos(), zero, -phi.sin()), 1), + torch.cat((zero, ones, zero), 1), + torch.cat((phi.sin(), zero, phi.cos()), 1), + ), 2) + + rot_z = torch.cat(( + torch.cat((psi.cos(), -psi.sin(), zero), 1), + torch.cat((psi.sin(), psi.cos(), zero), 1), + torch.cat((zero, zero, ones), 1) + ), 2) + + rot = torch.bmm(rot_x, torch.bmm(rot_y, rot_z)) # (nbatch, 3, 3) + + return rot + + +def geo_rotation_transfrom(geo, rot, trans=None): + """ rotation geometry and trans + params: + geo: geometry, torch.Tensor, (nbatch, N, 3) + rot: rotation matrix, torch.Tensor, (nbatch, 3, 3) + trans: transform matrix, torch.Tensor, (nbtach, 3) + return: + geometry, torch.Tensor, (nbatch, N, 3) + """ + # rotation + geo = torch.bmm(rot, geo.permute(0, 2, 1)) # (nbatch, 3, N) + + # transform + if trans is not None: + geo += trans.view(-1, 3, 1) + + geo = geo.permute(0, 2, 1) + return geo + + +def geo_projection(geo, param_camera): + """project geo to 2D plane + params: + geo, geometry, torch.Tensor, (nbatch, N, 3) + param_camera: torch.Tensor, (nbatch, 4) + return: + geometry, torch.Tensor, (nbatch, N, 3) + """ + + fx, fy = param_camera[:, 0], param_camera[:, 1] # (nbatch, ) + cx, cy = param_camera[:, 2], param_camera[:, 3] # (nbatch, ) + + X, Y, Z = geo[:, :, 0], geo[:, :, 1], geo[:, :, 2] # (nbatch, N) + + fxX = fx[:, None] * X # (nbatch, N) + fyY = fy[:, None] * Y # (nbatch, N) + + proj_x = -fxX / Z + cx[:, None] # (nbatch, N) + proj_y = fyY / Z + cy[:, None] + + geo_pro = torch.cat([proj_x, proj_y, Z], 2) + + return geo_pro + + +def landmark_projection(geo, ldmk_info, ldmk_num=68): + """Landmark Projection + + params: + geo, geometry, torch.Tensor, (nbatch, N, 3) + ldmk_info, torch.Tensor, (68,) + ldmk_num, int, the number of landmarks, default=68 + + return: + projection landmark, (nbatch, 68, 2) + """ + n_points = geo.shape[0] + + rot_tri_normal = compute_tri_normal(geo_rot, self.tris) + rot_ver_normal = torch.index_select(rot_tri_normal, 1, self.vert_tris) + + + is_visible = -torch.bmm(rot_ver_normal.reshape(-1, 1, 3), geo_rot.reshape(-1, 3, 1)) + is_visible = is_visible.reshape(-1, n_points) + + + ldmk_idx = render_util.update_contour(ldmk_info, is_visible, ldmk_num) + print(f"DEBUG: landmark projection, ldmk_num={ldmk_num}, update contour, ldmk_idx len={ldmk_idx.shape}, should be (Nbatch * 68)") + + ldmk_pro = torch.index_select(geo.reshape(-1, 3), 0, ldmk_idx) # (len(ldmk_idx), 3) + ldmk_pro = ldmk_pro[:, :2].reshape(-1, ldmk_num, 2) # (nbatch, ldmk_num, 2) + + return ldmk_pro + + \ No newline at end of file diff --git a/common/image.py b/common/image.py new file mode 100644 index 0000000..4a9c026 --- /dev/null +++ b/common/image.py @@ -0,0 +1,41 @@ +import os +import torch +import numpy as np +from PIL import Image + +def tensor2im(input_image, imtype=np.uint8): + """"Converts a Tensor array into a numpy image array. + + Parameters: + input_image (tensor) -- the input image tensor array + imtype (type) -- the desired type of the converted numpy array + """ + + if not isinstance(input_image, np.ndarray): + if isinstance(input_image, torch.Tensor): # get the data from a variable + image_tensor = input_image.data + else: + return input_image + + image_numpy = image_tensor[0].cpu().float().numpy() # convert it into a numpy array + + if image_numpy.shape[0] == 1: # grayscale to RGB + image_numpy = np.tile(image_numpy, (3, 1, 1)) + + image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 # post-processing: tranpose and scaling + + else: # if it is a numpy array, do nothing + image_numpy = input_image + + return image_numpy.astype(imtype) + + +def save_image(image_numpy, image_path): + """Save a numpy image to the disk + + Parameters: + image_numpy (numpy array) -- input numpy array + image_path (str) -- the path of the image + """ + image_pil = Image.fromarray(image_numpy) + image_pil.save(image_path) \ No newline at end of file diff --git a/common/landmark.py b/common/landmark.py new file mode 100644 index 0000000..f818c26 --- /dev/null +++ b/common/landmark.py @@ -0,0 +1,254 @@ +import os +import cv2 +import torch +import numpy as np +from pathlib import Path +from matplotlib import pyplot as plt +plt.rcParams['axes.facecolor'] = 'black' + +def landmark_normalize(ldmk): + # ldmk shape = (68, 2) + + pos_mean = np.mean(ldmk, axis=0) # (2, ) + pos_max = np.max(ldmk, axis=0) # (2, ) + pos_min = np.min(ldmk, axis=0) # (2, ) + + side = int(1.5 * np.max(pos_max - pos_min)) # (1, ) + # print(f"landmarks = {ldmk[::10, :]}, \n mean={pos_mean}, max={pos_max}, min={pos_min}, side={side}") + + tran = pos_mean - 0.5 * side # (2, ) + ldmk_tran = ldmk - tran[np.newaxis, :] # (68, 2) + ldmk_norm = ldmk_tran / side # (68, 2) + # print(f"ldmk_tran = {ldmk_tran[::10, :]}, \n ldmk_tran = {ldmk_norm[::10, :]}") + + return ldmk_norm, pos_mean, side + + +def landmark_normalize_by_param(ldmk, params): + # ldmk shape = (B, 68, 2) + # params shape = (B, 3) + + pos_mean = params[:, 0:2 ] # (B, 2) + pos_mean = pos_mean[:, np.newaxis, :] # (B, 1, 2) + side = params[:, 2:] # (B, 2) + side = side[:, np.newaxis, :] # (B, 1, 2) + + tran = pos_mean - 0.5 * side # (B, 1, 2) + ldmk_norm = (ldmk - tran) / side # (B, 68, 2) + + return ldmk_norm + +def landmark_to_images(ldmks, w=256, h=256, dpi=100, norm=True, prex=""): + # landmarks shape = (nbatch, 68, 2) + nframe = ldmks.shape[0] + + v_images = [] + for i in range(nframe): + ildmk = ldmks[i, :, :] + if prex is not None: + text = f"{prex}-frame-{i:04d}" + else: + text = None + + v_images.append(landmark_to_image(ildmk, w, h, dpi, norm, text)) + + return np.asarray(v_images) + + +def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None): + # landmarks shape = (68, 2) + + if norm: + ildmk[:, 0] = w - ildmk[:, 0] * w + ildmk[:, 1] = h - ildmk[:, 1] * h + + else: + # ildmk[:, 0] = w - ildmk[:, 0] + ildmk[:, 1] = h - ildmk[:, 1] + + if isinstance(ildmk, torch.Tensor): + ildmk = ildmk.cpu().numpy() + + # plot + fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi) + fig.patch.set_facecolor('w') + + ax = fig.add_subplot(1,1,1) + # ax.imshow(np.zeros(shape=(w, h))) + + ax.set_facecolor('m') + # plt.subplots_adjust(left=0, right=1, top=1, bottom=0) + # ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1) + ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1) + ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1) + ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1) + ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1) + ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1) + ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1) + ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1) + + #chin + ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1) + + #left and right eyebrow + ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) + ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) + + #nose + ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) + ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) + + #left and right eye + ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + + ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + + #outer and inner lip + ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + + ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + + ax.set_xlim(0, w) + ax.set_ylim(0, h) + ax.axis('off') + + if text is not None: + ax.text(2, 2, text) + + fig.canvas.draw() + w, h = fig.canvas.get_width_height() + + buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + buffer = buffer.reshape((h, w, 3)) + image = np.asarray(buffer) + # print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}") + + plt.close(fig) + + return image + +# def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None): +# # landmarks shape = (68, 2) + +# if norm: +# ildmk = w - ildmk * w +# else: +# ildmk[:, 1] = h - ildmk[:, 1] + +# if isinstance(ildmk, torch.Tensor): +# ildmk = ildmk.cpu().numpy() + +# # plot +# fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi) +# fig.patch.set_facecolor('w') + +# ax = fig.add_subplot(1,1,1) +# # ax.imshow(np.zeros(shape=(w, h))) + +# ax.set_facecolor('m') +# # plt.subplots_adjust(left=0, right=1, top=1, bottom=0) +# # ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1) +# ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1) +# ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1) +# ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1) +# ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1) +# ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1) +# ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1) +# ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1) + +# #chin +# ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1) + +# #left and right eyebrow +# ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) +# ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1) + +# #nose +# ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) +# ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1) + +# #left and right eye +# ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + +# ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) + +# #outer and inner lip +# ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + +# ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1) +# ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1) + +# ax.set_xlim(0, w) +# ax.set_ylim(0, h) +# ax.axis('off') + +# if text is not None: +# ax.text(10, 10, text) + +# fig.canvas.draw() +# w, h = fig.canvas.get_width_height() + +# buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) +# buffer = buffer.reshape((h, w, 3)) +# image = np.asarray(buffer) +# # print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}") + +# plt.close(fig) + +# return image + +def landmark_to_mask(ildmk, w=256, h=256, dpi=100, norm=True): + # landmarks shape = (68, 2) + # print(f"landmark data shape = {ildmk.shape}") + if norm: + ildmk = ildmk * w + + # plot + fig = plt.figure(figsize=(h/dpi, w/dpi), dpi=dpi) + ax = fig.add_subplot(1,1,1) + + # ax.imshow(np.ones(shape=(w, h))) + # plt.subplots_adjust(left=0, right=1, top=1, bottom=0) + + #chin + ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='green', lw=2) + #left and right eyebrow + ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='orange', lw=2) + ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='orange', lw=2) + #nose + ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2) + ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2) + #left and right eye + ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='red', lw=2) + ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='red', lw=2) + #outer and inner lip + ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='purple', lw=2) + ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='pink', lw=2) + ax.axis('off') + + + fig.canvas.draw() + + + buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + # buffer.shape = (w, h, 4) + + image = buffer.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + + plt.close(fig) + + return image + + + + + + + diff --git a/common/logger.py b/common/logger.py new file mode 100644 index 0000000..e2cf9e5 --- /dev/null +++ b/common/logger.py @@ -0,0 +1,87 @@ +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) diff --git a/common/resampling.py b/common/resampling.py new file mode 100644 index 0000000..7ed3fb9 --- /dev/null +++ b/common/resampling.py @@ -0,0 +1,39 @@ +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 \ No newline at end of file diff --git a/common/utils.py b/common/utils.py new file mode 100644 index 0000000..0bfd7bc --- /dev/null +++ b/common/utils.py @@ -0,0 +1,516 @@ +import cv2 +import numpy as np +import landmarks.lmconfig as lmcfg +from csl_common.utils.nn import to_numpy, to_image +from csl_common.vis import vis +import matplotlib.pyplot as plt +from skimage.metrics import structural_similarity as compare_ssim +import torch +import warnings + +layers = [] + +outline = range(0, 17) +eyebrow_l = range(17, 22) +eyebrow_r = range(22, 27) +nose = range(27, 31) +nostrils = range(31, 36) +eye_l = range(36, 42) +eye_r = range(42, 48) +mouth = range(48, 68) + +components = [outline, eyebrow_l, eyebrow_r, nose, nostrils, eye_l, eye_r, mouth] + +new_layers = [] +for idx in range(20): + lm_ids = [] + for comp in components[1:]: + if len(comp) > idx: + lm = comp[idx] + lm_ids.append(lm) + new_layers.append(lm_ids) + +outline_layers = [[lm] for lm in range(17)] + +layers = components + new_layers + outline_layers + +hm_code_mat = np.zeros((len(layers), 68), dtype=bool) +for l, lm_ids in enumerate(layers): + hm_code_mat[l, lm_ids] = True + + +def generate_colors(n, r, g, b, dim): + ret = [] + step = [0,0,0] + step[dim] = 256 / n + for i in range(n): + r += step[0] + g += step[1] + b += step[2] + r = int(r) % 256 + g = int(g) % 256 + b = int(b) % 256 + ret.append((r,g,b)) + return ret + +_colors = generate_colors(17, 220, 0, 0, 2) + \ + generate_colors(10, 0, 240, 0, 0) + \ + generate_colors(9, 0, 0, 230, 1) + \ + generate_colors(12, 100, 255, 0, 2) + \ + generate_colors(20, 150, 0, 255, 2) +# lmcolors = np.array(_colors) +np.random.seed(0) +lmcolors = np.random.randint(0,255,size=(68,3)) +lmcolors = lmcolors / lmcolors.sum(axis=1).reshape(-1,1)*255 + + +def gaussian(x, mean, sigma): + return 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x-mean)**2 / (2 * sigma**2)) + + +def make_landmark_template(wnd_size, sigma): + X, Y = np.mgrid[-wnd_size//2:wnd_size//2, -wnd_size//2:wnd_size//2] + Z = np.sqrt(X**2 + Y**2) + N = gaussian(Z, 0, sigma) + # return (N/N.max())**2 # square to make sharper + return N / N.max() + + +def _fill_heatmap_layer(dst, lms, lm_id, lm_heatmap_window, wnd_size): + posx, posy = min(lms[lm_id,0], lmcfg.HEATMAP_SIZE-1), min(lms[lm_id,1], lmcfg.HEATMAP_SIZE-1) + + img_size = lmcfg.HEATMAP_SIZE + l = int(posx - wnd_size/2) + t = int(posy - wnd_size/2) + r = l + wnd_size + b = t + wnd_size + + src_l = max(0, -l) + src_t = max(0, -t) + src_r = min(wnd_size, wnd_size-(r-img_size)) + src_b = min(wnd_size, wnd_size-(b-img_size)) + + try: + cn = lm_id + wnd = lm_heatmap_window[src_t:src_b, src_l:src_r] + weight = 1.0 + dst[cn, max(0,t):min(img_size, b), max(0,l):min(img_size, r)] = np.maximum( + dst[cn, max(0,t):min(img_size, b), max(0,l):min(img_size, r)], wnd*weight) + except: + pass + + +def __get_code_mat(num_landmarks): + def to_binary(n, ndigits): + bits = np.array([bool(int(x)) for x in bin(n)[2:]]) + assert len(bits) <= ndigits + zero_pad_bits = np.zeros(ndigits, dtype=bool) + zero_pad_bits[-len(bits):] = bits + return zero_pad_bits + + n_enc_layers = int(np.ceil(np.log2(num_landmarks))) + + # get binary code for each heatmap id + codes = [to_binary(i+1, ndigits=n_enc_layers) for i in range(num_landmarks)] + return np.vstack(codes) + + +def convert_to_encoded_heatmaps(hms): + + def merge_layers(hms): + hms = hms.max(axis=0) + return hms/hms.max() + + num_landmarks = len(hms) + n_enc_layers = len(hm_code_mat) + + # create compressed heatmaps by merging layers according to transpose of binary code mat + encoded_hms = np.zeros((n_enc_layers, hms.shape[1], hms.shape[2])) + for l in range(n_enc_layers): + selected_layer_ids = hm_code_mat[l,:] + encoded_hms[l] = merge_layers(hms[selected_layer_ids].copy()) + decode_heatmaps(encoded_hms) + return encoded_hms + + +def convert_to_hamming_encoded_heatmaps(hms): + + def merge_layers(hms): + hms = hms.max(axis=0) + return hms/hms.max() + + num_landmarks = len(hms) + n_enc_layers = int(np.ceil(np.log2(num_landmarks))) + code_mat = __get_code_mat(num_landmarks) + + # create compressed heatmaps by merging layers according to transpose of binary code mat + encoded_hms = np.zeros((n_enc_layers, hms.shape[1], hms.shape[2])) + for l in range(n_enc_layers): + selected_layer_ids = code_mat[:, l] + encoded_hms[l] = merge_layers(hms[selected_layer_ids].copy()) + # decode_heatmaps(encoded_hms) + return encoded_hms + + +def decode_heatmaps(hms): + import cv2 + def get_decoded_heatmaps_for_layer(hms, lm): + show = False + enc_layer_ids = code_mat[:, lm] + heatmap = np.ones_like(hms[0]) + for i in range(len(enc_layer_ids)): + pos = enc_layer_ids[i] + layer = hms[i] + if pos: + if show: + fig, ax = plt.subplots(1,4) + print(i, pos) + ax[0].imshow(heatmap, vmin=0, vmax=1) + ax[1].imshow(layer, vmin=0, vmax=1) + # mask = layer.copy() + # mask[mask < 0.1] = 0 + # heatmap *= mask + heatmap *= layer + if show: + # ax[2].imshow(mask, vmin=0, vmax=1) + ax[3].imshow(heatmap, vmin=0, vmax=1) + + return heatmap + + num_landmarks = 68 + + # get binary code for each heatmap id + code_mat = hm_code_mat + + decoded_hms = np.zeros((num_landmarks, hms.shape[1], hms.shape[1])) + + show = False + if show: + fig, ax = plt.subplots(1) + ax.imshow(code_mat) + fig_dec, ax_dec = plt.subplots(7, 10) + fig, ax = plt.subplots(5,9) + for i in range(len(hms)): + ax[i//9, i%9].imshow(hms[i]) + + lms = np.zeros((68,2), dtype=int) + # lmid_to_show = 16 + + for lm in range(0,68): + + heatmap = get_decoded_heatmaps_for_layer(hms, lm) + + decoded_hms[lm] = heatmap + heatmap = cv2.blur(heatmap, (5, 5)) + lms[lm, :] = np.unravel_index(np.argmax(heatmap, axis=None), heatmap.shape)[::-1] + + if show: + ax_dec[lm//10, lm%10].imshow(heatmap) + + if show: + plt.show() + + return decoded_hms, lms + + +def create_landmark_heatmaps(lms, sigma, landmarks_to_use, heatmap_size): + lm_wnd_size = int(sigma * 5) + lm_heatmap_window = make_landmark_template(lm_wnd_size, sigma) + nchannels = len(landmarks_to_use) + + hms = np.zeros((nchannels, heatmap_size, heatmap_size)) + for l in landmarks_to_use: + wnd = lm_heatmap_window + _fill_heatmap_layer(hms, lms, l, wnd, lm_wnd_size) + + if lmcfg.LANDMARK_TARGET == 'single_channel': + hms = hms.max(axis=0) + hms /= hms.max() + return hms.astype(np.float32) + + +def calc_landmark_nme_per_img(gt_lms, pred_lms, ocular_norm='pupil', landmarks_to_eval=None, image_size=None): + norm_dists = calc_landmark_nme(gt_lms, pred_lms, ocular_norm, image_size=image_size) + if landmarks_to_eval is None: + landmarks_to_eval = range(norm_dists.shape[1]) + return np.mean(np.array([norm_dists[:,l] for l in landmarks_to_eval]).T, axis=1) + + +def get_pupil_dists(lms): + assert lms.shape[2] == 68 + ocular_dists_inner = np.sqrt(np.sum((lms[:, 42] - lms[:, 39])**2, axis=1)) + ocular_dists_outer = np.sqrt(np.sum((lms[:, 45] - lms[:, 36])**2, axis=1)) + return np.vstack((ocular_dists_inner, ocular_dists_outer)).mean(axis=0) + + +def get_landmark_confs(X_lm_hm): + return np.clip(to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2), a_min=0, a_max=1) + + +def calc_landmark_nme(gt_lms, pred_lms, ocular_norm='pupil', image_size=None): + def reformat(lms): + lms = to_numpy(lms) + if len(lms.shape) == 2: + lms = lms.reshape((1,-1,2)) + return lms + gt = reformat(gt_lms) + pred = reformat(pred_lms) + assert(len(gt.shape) == 3) + assert(len(pred.shape) == 3) + if gt.shape[1] == 5: # VGGFace2 + ocular_dists = np.sqrt(np.sum((gt[:, 1] - gt[:, 0])**2, axis=1)) + elif gt.shape[1] == 19: # AFLW + assert image_size is not None + ocular_dists = np.ones(gt.shape[0], dtype=np.float32) * image_size + elif gt.shape[1] == 98: # WFLW + ocular_dists = np.sqrt(np.sum((gt[:, 72] - gt[:, 60])**2, axis=1)) + elif gt.shape[1] == 68: # 300-W + if ocular_norm == 'pupil': + ocular_dists = get_pupil_dists(gt) + elif ocular_norm == 'outer': + ocular_dists = np.sqrt(np.sum((gt[:, 45] - gt[:, 36])**2, axis=1)) + elif ocular_norm is None or ocular_norm == 'none': + ocular_dists = np.ones((len(gt),1)) * 100.0 + else: + raise ValueError("Ocular norm {} not defined!".format(ocular_norm)) + else: + assert image_size is not None + ocular_dists = np.ones(gt.shape[0], dtype=np.float32) * image_size + norm_dists = np.sqrt(np.sum((gt - pred)**2, axis=2)) / ocular_dists.reshape(len(gt), 1) + return norm_dists * 100 + + +def calc_landmark_failure_rate(nmes, th=10.0): + img_nmes = nmes.mean(axis=1) + assert len(img_nmes) == len(nmes) + return np.count_nonzero(img_nmes > th) / len(img_nmes.ravel()) + + +def calc_landmark_ncc(X, X_recon, lms): + input_images = vis.to_disp_images(X, denorm=True) + recon_images = vis.to_disp_images(X_recon, denorm=True) + nimgs = len(input_images) + nlms = len(lms[0]) + wnd_size = (X_recon.shape[-1] // 16) - 1 + nccs = np.zeros((nimgs, nlms), dtype=np.float32) + img_shape = input_images[0].shape + for i in range(nimgs): + for lid in range(nlms): + x = int(lms[i, lid, 0]) + y = int(lms[i, lid, 1]) + t = max(0, y-wnd_size//2) + b = min(img_shape[0]-1, y+wnd_size//2) + l = max(0, x-wnd_size//2) + r = min(img_shape[1]-1, x+wnd_size//2) + wnd1 = input_images[i][t:b, l:r] + wnd2 = recon_images[i][t:b, l:r] + ncc = ((wnd1-wnd1.mean()) * (wnd2-wnd2.mean())).mean() / (wnd1.std() * wnd2.std()) + nccs[i, lid] = ncc + return np.clip(np.nan_to_num(nccs), a_min=-1, a_max=1) + + +def calc_landmark_ssim_score(X, X_recon, lms, wnd_size=None): + if wnd_size is None: + wnd_size = (X_recon.shape[-1] // 16) - 1 + input_images = vis.to_disp_images(X, denorm=True) + recon_images = vis.to_disp_images(X_recon, denorm=True) + data_range = 255.0 if input_images[0].dtype == np.uint8 else 1.0 + nimgs = len(input_images) + nlms = len(lms[0]) + scores = np.zeros((nimgs, nlms), dtype=np.float32) + for i in range(nimgs): + S = compare_ssim(input_images[i], recon_images[i], data_range=data_range, multichannel=True, full=True)[1] + S = S.mean(axis=2) + for lid in range(nlms): + x = int(lms[i, lid, 0]) + y = int(lms[i, lid, 1]) + t = max(0, y-wnd_size//2) + b = min(S.shape[0]-1, y+wnd_size//2) + l = max(0, x-wnd_size//2) + r = min(S.shape[1]-1, x+wnd_size//2) + wnd = S[t:b, l:r] + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=RuntimeWarning) + scores[i, lid] = wnd.mean() + return np.nan_to_num(scores) + + +def calc_landmark_cs_error(X, X_recon, lms, torch_ssim, training=False, wnd_size=None): + if wnd_size is None: + wnd_size = (X_recon.shape[-1] // 16) - 1 + nimgs = len(X) + nlms = len(lms[0]) + input_size = X.shape[-1] + errs = torch.zeros((nimgs, nlms), requires_grad=training).cuda() + for i in range(len(X)): + torch_ssim(X[i].unsqueeze(0), X_recon[i].unsqueeze(0)) + cs_map = torch_ssim.cs_map[0].mean(dim=0) + map_size = cs_map.shape[0] + margin = (input_size - map_size) // 2 + S = torch.zeros((input_size, input_size), requires_grad=training).cuda() + S[margin:-margin, margin:-margin] = cs_map + for lid in range(nlms): + x = int(lms[i, lid, 0]) + y = int(lms[i, lid, 1]) + t = max(0, y-wnd_size//2) + b = min(S.shape[0]-1, y+wnd_size//2) + l = max(0, x-wnd_size//2) + r = min(S.shape[1]-1, x+wnd_size//2) + wnd = S[t:b, l:r] + errs[i, lid] = 1 - wnd.mean() + return errs + + +def calc_landmark_recon_error(X, X_recon, lms, return_maps=False, reduction='mean'): + assert len(X.shape) == 4 + assert reduction in ['mean', 'none'] + X = to_numpy(X) + X_recon = to_numpy(X_recon) + mask = np.zeros((X.shape[0], X.shape[2], X.shape[3]), dtype=np.float32) + input_size = X.shape[-1] + radius = input_size * 0.05 + for img_id in range(len(mask)): + for lm in lms[img_id]: + cv2.circle(mask[img_id], (int(lm[0]), int(lm[1])), radius=int(radius), color=1, thickness=-1) + err_maps = np.abs(X - X_recon).mean(axis=1) * 255.0 + masked_err_maps = err_maps * mask + + debug = False + if debug: + fig, ax = plt.subplots(1,3) + ax[0].imshow(vis.to_disp_image((X * mask[:,np.newaxis,:,:].repeat(3, axis=1))[0], denorm=True)) + ax[1].imshow(vis.to_disp_image((X_recon * mask[:,np.newaxis,:,:].repeat(3, axis=1))[0], denorm=True)) + ax[2].imshow(masked_err_maps[0]) + plt.show() + + if reduction == 'mean': + err = masked_err_maps.sum() / (mask.sum() * 3) + else: + # err = masked_err_maps.mean(axis=2).mean(axis=1) + err = masked_err_maps.sum(axis=2).sum(axis=1) / (mask.reshape(len(mask), -1).sum(axis=1) * 3) + + if return_maps: + return err, masked_err_maps + else: + return err + + +def to_single_channel_heatmap(lm_heatmaps): + if lmcfg.LANDMARK_TARGET == 'colored': + mc = [to_image(lm_heatmaps[0])] + elif lmcfg.LANDMARK_TARGET == 'single_channel': + mc = [to_image(lm_heatmaps[0, 0])] + else: + mc = to_image(lm_heatmaps.max(axis=1)) + return mc + + +LM68_TO_LM96 = 1 +LM98_TO_LM68 = 2 +LM68_TO_LM5 = 3 + +def convert_landmarks(lms, code): + cvt_func = { + LM98_TO_LM68: lm98_to_lm68, + LM68_TO_LM5: lm68_to_lm5, + } + if len(lms.shape) == 3: + # new_lms = [] + new_lms = torch.zeros((len(lms), 5, 2), requires_grad=True, dtype=torch.float32).cuda() + for i in range(len(lms)): + # new_lms.append(cvt_func[code](lms[i])) + # new_lms[i] += cvt_func[code](lms[i]) + cvt_func[code](lms[i], new_lms[i]) + # new_lms = torch.stack(new_lms) + # new_lms = np.array(new_lms) + return new_lms + elif len(lms.shape) == 2: + return cvt_func[code](lms) + else: + raise ValueError + + +def lm68_to_lm5(lm68, lm5): + # lm5 = np.zeros((len(lm68), 5, 2), dtype=np.float32) + # lm5 = torch.zeros((5, 2), requires_grad=True, dtype=torch.float32) + lm5[0] += (lm68[36] + lm68[39]) / 2 + lm5[1] += (lm68[42] + lm68[45]) / 2 + lm5[2] += lm68[30] + lm5[3] += lm68[48] + lm5[4] += lm68[54] + # return lm5 + + +def lm98_to_lm68(lm98): + def copy_lms(offset68, offset98, n): + lm68[range(offset68, offset68+n)] = lm98[range(offset98, offset98+n)] + + assert len(lm98) == 98, "Cannot convert landmarks to 68 points!" + lm68 = np.zeros((68,2), dtype=np.float32) + + # outline + lm68[range(17)] = lm98[range(0,33,2)] + + # left eyebrow + copy_lms(17, 33, 5) + # right eyebrow + copy_lms(22, 42, 5) + # nose + copy_lms(27, 51, 9) + + # eye left + lm68[36] = lm98[60] + lm68[37] = lm98[61] + lm68[38] = lm98[63] + lm68[39] = lm98[64] + lm68[40] = lm98[65] + lm68[41] = lm98[67] + + # eye right + lm68[36+6] = lm98[60+8] + lm68[37+6] = lm98[61+8] + lm68[38+6] = lm98[63+8] + lm68[39+6] = lm98[64+8] + lm68[40+6] = lm98[65+8] + lm68[41+6] = lm98[67+8] + + copy_lms(48, 76, 20) + + return lm68 + + +def is_good_landmark(confs, rec_errs=None): + if rec_errs is not None: + low_errors = rec_errs < 0.25 + confs *= np.array(low_errors).astype(int) + return confs > 0.8 + + +def smooth_heatmaps(hms): + assert(len(hms.shape) == 4) + hms = to_numpy(hms) + for i in range(hms.shape[0]): + for l in range(hms.shape[1]): + hms[i,l] = cv2.blur(hms[i,l], (9,9), borderType=cv2.BORDER_CONSTANT) + # hms[i,l] = cv2.GaussianBlur(hms[i,l], (9,9), sigmaX=9, borderType=cv2.BORDER_CONSTANT) + return hms + + +def heatmaps_to_landmarks(hms, target_size): + def landmark_id_to_heatmap_id(lm_id): + return {lm: i for i,lm in enumerate(range(num_landmarks))}[lm_id] + + assert len(hms.shape) == 4 + num_images = hms.shape[0] + num_landmarks = hms.shape[1] + heatmap_size = hms.shape[-1] + lms = np.zeros((num_images, num_landmarks, 2), dtype=int) + if hms.shape[1] > 3: + # print(hms.max()) + for i in range(len(hms)): + heatmaps = to_numpy(hms[i]) + for l in range(len(heatmaps)): + hm = heatmaps[landmark_id_to_heatmap_id(l)] + lms[i, l, :] = np.unravel_index(np.argmax(hm, axis=None), hm.shape)[::-1] + lm_scale = heatmap_size / target_size + return lms / lm_scale diff --git a/common/vis.py b/common/vis.py new file mode 100644 index 0000000..f870c59 --- /dev/null +++ b/common/vis.py @@ -0,0 +1,313 @@ +import cv2 +import numpy as np +import torch +from matplotlib import pyplot as plt +from skimage.metrics import structural_similarity as compare_ssim + +from common.utils import nn as nn +from common.utils.nn import to_numpy +from common import vis +from landmarks.lmutils import calc_landmark_nme, calc_landmark_ssim_score, to_single_channel_heatmap, \ + calc_landmark_nme_per_img, smooth_heatmaps + + +def show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1.0): + vmax = 1.0 + rows_heatmaps = [] + if gt_heatmaps is not None: + vmax = gt_heatmaps.max() + if len(gt_heatmaps[0].shape) == 2: + gt_heatmaps = [vis.color_map(hm, vmin=0, vmax=vmax, cmap=plt.cm.jet) for hm in gt_heatmaps] + nCols = 1 if len(gt_heatmaps) == 1 else nimgs + rows_heatmaps.append(cv2.resize(vis.make_grid(gt_heatmaps, nCols=nCols, padval=0), None, fx=f, fy=f)) + + disp_pred_heatmaps = pred_heatmaps + if len(pred_heatmaps[0].shape) == 2: + disp_pred_heatmaps = [vis.color_map(hm, vmin=0, vmax=vmax, cmap=plt.cm.jet) for hm in pred_heatmaps] + nCols = 1 if len(pred_heatmaps) == 1 else nimgs + rows_heatmaps.append(cv2.resize(vis.make_grid(disp_pred_heatmaps, nCols=nCols, padval=0), None, fx=f, fy=f)) + + cv2.imshow('Landmark heatmaps', cv2.cvtColor(np.vstack(rows_heatmaps), cv2.COLOR_RGB2BGR)) + + +def visualize_batch(images, landmarks, X_recon, X_lm_hm, lm_preds_max, + lm_heatmaps=None, target_images=None, lm_preds_cnn=None, ds=None, wait=0, ssim_maps=None, + landmarks_to_draw=None, ocular_norm='outer', horizontal=False, f=1.0, + overlay_heatmaps_input=False, overlay_heatmaps_recon=False, clean=False, + landmarks_only_outline=range(17), landmarks_no_outline=range(17,68)): + + gt_color = (0,255,0) + pred_color = (0,0,255) + image_size = images.shape[3] + assert image_size in [128, 256] + + nimgs = min(10, len(images)) + images = nn.atleast4d(images)[:nimgs] + num_landmarks = lm_preds_max.shape[1] + + if landmarks_to_draw is None: + landmarks_to_draw = range(num_landmarks) + + nme_per_lm = None + if landmarks is None: + # print('num landmarks', lmcfg.NUM_LANDMARKS) + lm_gt = np.zeros((nimgs, num_landmarks, 2)) + else: + lm_gt = nn.atleast3d(to_numpy(landmarks))[:nimgs] + nme_per_lm = calc_landmark_nme(lm_gt, lm_preds_max[:nimgs], ocular_norm=ocular_norm, image_size=image_size) + lm_ssim_errs = 1 - calc_landmark_ssim_score(images, X_recon[:nimgs], lm_gt) + + lm_confs = None + # show landmark heatmaps + pred_heatmaps = None + if X_lm_hm is not None: + pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm[:nimgs])) + pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in pred_heatmaps] + gt_heatmaps = None + if lm_heatmaps is not None: + gt_heatmaps = to_single_channel_heatmap(to_numpy(lm_heatmaps[:nimgs])) + gt_heatmaps = np.array([cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in gt_heatmaps]) + show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1) + lm_confs = to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2) + + # resize images for display and scale landmarks accordingly + lm_preds_max = lm_preds_max[:nimgs] * f + if lm_preds_cnn is not None: + lm_preds_cnn = lm_preds_cnn[:nimgs] * f + lm_gt *= f + + input_images = vis.to_disp_images(images[:nimgs], denorm=True) + if target_images is not None: + disp_images = vis.to_disp_images(target_images[:nimgs], denorm=True) + else: + disp_images = vis.to_disp_images(images[:nimgs], denorm=True) + disp_images = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images] + + recon_images = vis.to_disp_images(X_recon[:nimgs], denorm=True) + disp_X_recon = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()] + + # overlay landmarks on input images + if pred_heatmaps is not None and overlay_heatmaps_input: + disp_images = [vis.overlay_heatmap(disp_images[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))] + if pred_heatmaps is not None and overlay_heatmaps_recon: + disp_X_recon = [vis.overlay_heatmap(disp_X_recon[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))] + + + # + # Show input images + # + disp_images = vis.add_landmarks_to_images(disp_images, lm_gt[:nimgs], color=gt_color) + disp_images = vis.add_landmarks_to_images(disp_images, lm_preds_max[:nimgs], lm_errs=nme_per_lm, + color=pred_color, draw_wireframe=False, gt_landmarks=lm_gt, + draw_gt_offsets=True) + + # disp_images = vis.add_landmarks_to_images(disp_images, lm_gt[:nimgs], color=(1,1,1), radius=1, + # draw_dots=True, draw_wireframe=True, landmarks_to_draw=landmarks_to_draw) + # disp_images = vis.add_landmarks_to_images(disp_images, lm_preds_max[:nimgs], lm_errs=nme_per_lm, + # color=(1.0, 0.0, 0.0), + # draw_dots=True, draw_wireframe=True, radius=1, + # gt_landmarks=lm_gt, draw_gt_offsets=False, + # landmarks_to_draw=landmarks_to_draw) + + + # + # Show reconstructions + # + X_recon_errs = 255.0 * torch.abs(images - X_recon[:nimgs]).reshape(len(images), -1).mean(dim=1) + if not clean: + disp_X_recon = vis.add_error_to_images(disp_X_recon[:nimgs], errors=X_recon_errs, format_string='{:>4.1f}') + + # modes of heatmaps + # disp_X_recon = [overlay_heatmap(disp_X_recon[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))] + if not clean: + lm_errs_max = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm, + landmarks_no_outline, image_size=image_size) + lm_errs_max_outline = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm, + landmarks_only_outline, image_size=image_size) + lm_errs_max_all = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm, + list(landmarks_only_outline)+list(landmarks_no_outline), + image_size=image_size) + disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max, loc='br-2', format_string='{:>5.2f}', vmax=15) + disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max_outline, loc='br-1', format_string='{:>5.2f}', vmax=15) + disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max_all, loc='br', format_string='{:>5.2f}', vmax=15) + disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_gt, color=gt_color, draw_wireframe=True) + + # disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_preds_max[:nimgs], + # color=pred_color, draw_wireframe=False, + # lm_errs=nme_per_lm, lm_confs=lm_confs, + # lm_rec_errs=lm_ssim_errs, gt_landmarks=lm_gt, + # draw_gt_offsets=True, draw_dots=True) + + disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_preds_max[:nimgs], + color=pred_color, draw_wireframe=True, + gt_landmarks=lm_gt, draw_gt_offsets=True, lm_errs=nme_per_lm, + draw_dots=True, radius=2) + + def add_confidences(disp_X_recon, lmids, loc): + means = lm_confs[:,lmids].mean(axis=1) + colors = vis.color_map(to_numpy(1-means), cmap=plt.cm.jet, vmin=0.0, vmax=0.4) + return vis.add_error_to_images(disp_X_recon, means, loc=loc, format_string='{:>4.2f}', colors=colors) + + # disp_X_recon = add_confidences(disp_X_recon, lmcfg.LANDMARKS_NO_OUTLINE, 'bm-2') + # disp_X_recon = add_confidences(disp_X_recon, lmcfg.LANDMARKS_ONLY_OUTLINE, 'bm-1') + # disp_X_recon = add_confidences(disp_X_recon, lmcfg.ALL_LANDMARKS, 'bm') + + # print ssim errors + ssim = np.zeros(nimgs) + for i in range(nimgs): + ssim[i] = compare_ssim(input_images[i], recon_images[i], data_range=1.0, multichannel=True) + if not clean: + disp_X_recon = vis.add_error_to_images(disp_X_recon, 1 - ssim, loc='bl-1', format_string='{:>4.2f}', + vmax=0.8, vmin=0.2) + # print ssim torch errors + if ssim_maps is not None and not clean: + disp_X_recon = vis.add_error_to_images(disp_X_recon, ssim_maps.reshape(len(ssim_maps), -1).mean(axis=1), + loc='bl-2', format_string='{:>4.2f}', vmin=0.0, vmax=0.4) + + rows = [vis.make_grid(disp_images, nCols=nimgs, normalize=False)] + rows.append(vis.make_grid(disp_X_recon, nCols=nimgs)) + + if ssim_maps is not None: + disp_ssim_maps = to_numpy(nn.denormalized(ssim_maps)[:nimgs].transpose(0, 2, 3, 1)) + for i in range(len(disp_ssim_maps)): + disp_ssim_maps[i] = vis.color_map(disp_ssim_maps[i].mean(axis=2), vmin=0.0, vmax=2.0) + grid_ssim_maps = vis.make_grid(disp_ssim_maps, nCols=nimgs, fx=f, fy=f) + cv2.imshow('ssim errors', cv2.cvtColor(grid_ssim_maps, cv2.COLOR_RGB2BGR)) + + if horizontal: + assert(nimgs == 1) + disp_rows = vis.make_grid(rows, nCols=2) + else: + disp_rows = vis.make_grid(rows, nCols=1) + wnd_title = 'Predicted Landmarks ' + if ds is not None: + wnd_title += ds.__class__.__name__ + cv2.imshow(wnd_title, cv2.cvtColor(disp_rows, cv2.COLOR_RGB2BGR)) + cv2.waitKey(wait) + + +def visualize_images(X, X_lm_hm, landmarks=None, show_recon=True, show_landmarks=True, show_heatmaps=False, + draw_wireframe=False, smoothing_level=2, heatmap_opacity=0.8, f=1): + + if show_recon: + disp_X = vis.to_disp_images(X, denorm=True) + else: + disp_X = vis.to_disp_images(torch.zeros_like(X), denorm=False) + heatmap_opacity = 1 + + if X_lm_hm is not None: + if smoothing_level > 0: + X_lm_hm = smooth_heatmaps(X_lm_hm) + if smoothing_level > 1: + X_lm_hm = smooth_heatmaps(X_lm_hm) + + if show_heatmaps: + pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm)) + pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_CUBIC) for im in pred_heatmaps] + disp_X = [vis.overlay_heatmap(disp_X[i], pred_heatmaps[i], heatmap_opacity) for i in range(len(pred_heatmaps))] + + if show_landmarks and landmarks is not None: + pred_color = (0,255,255) + disp_X = vis.add_landmarks_to_images(disp_X, landmarks, color=pred_color, draw_wireframe=draw_wireframe) + + return disp_X + + +def generate_images(net, z_random, **kwargs): + with torch.no_grad(): + X_gen_vis = net.P(z_random)[:, :3] + X_lm_hm = net.LMH(net.P) + return visualize_images(X_gen_vis, X_lm_hm, **kwargs) + + +def visualize_random_faces(net, nimgs=10, wait=10, f=1.0): + z_random = torch.randn(nimgs, net.z_dim).cuda() + disp_X_gen = generate_images(net, z_random) + grid_img = vis.make_grid(disp_X_gen, nCols=nimgs//2) + cv2.imshow("random faces", cv2.cvtColor(grid_img, cv2.COLOR_RGB2BGR)) + cv2.waitKey(wait) + + +def visualize_batch_CVPR(images, landmarks, X_recon, X_lm_hm, lm_preds, show_recon=True, + lm_heatmaps=None, ds=None, wait=0, horizontal=False, f=1.0, radius=2, + draw_wireframes=False): + + gt_color = (0,255,0) + pred_color = (0,255,255) + # pred_color = (255,0,0) + + nimgs = min(10, len(images)) + images = nn.atleast4d(images)[:nimgs] + num_landmarks = lm_preds.shape[1] + + # if landmarks is None: + # print('num landmarks', num_landmarks) + # lm_gt = np.zeros((nimgs, num_landmarks, 2)) + # else: + + # show landmark heatmaps + pred_heatmaps = None + if X_lm_hm is not None: + pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm[:nimgs])) + pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in pred_heatmaps] + gt_heatmaps = None + if lm_heatmaps is not None: + gt_heatmaps = to_single_channel_heatmap(to_numpy(lm_heatmaps[:nimgs])) + gt_heatmaps = np.array([cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in gt_heatmaps]) + show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1) + lm_confs = to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2) + + # resize images for display and scale landmarks accordingly + lm_preds = lm_preds[:nimgs] * f + + rows = [] + + disp_images = vis.to_disp_images(images[:nimgs], denorm=True) + disp_images = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images] + rows.append(vis.make_grid(disp_images, nCols=nimgs, normalize=False)) + + heatmap_opacity = 1.0 + if show_recon: + recon_images = vis.to_disp_images(X_recon[:nimgs], denorm=True) + else: + recon_images = vis.to_disp_images(torch.ones_like(X_recon[:nimgs]), denorm=False) + heatmap_opacity = 1 + + disp_X_recon = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()] + rows.append(vis.make_grid(disp_X_recon, nCols=nimgs)) + + # overlay landmarks on images + disp_X_recon_hm = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()] + disp_X_recon_hm = [vis.overlay_heatmap(disp_X_recon_hm[i], pred_heatmaps[i], heatmap_opacity) for i in range(len(pred_heatmaps))] + rows.append(vis.make_grid(disp_X_recon_hm, nCols=nimgs)) + + # reconstructions with prediction + disp_X_recon_pred = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()] + disp_X_recon_pred = vis.add_landmarks_to_images(disp_X_recon_pred, lm_preds, color=pred_color,radius=radius) + rows.append(vis.make_grid(disp_X_recon_pred, nCols=nimgs)) + + # reconstructions with ground truth (if gt available) + if landmarks is not None: + lm_gt = nn.atleast3d(to_numpy(landmarks))[:nimgs] * f + disp_X_recon_gt = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()] + disp_X_recon_gt = vis.add_landmarks_to_images(disp_X_recon_gt, lm_gt, color=gt_color, radius=radius) + rows.append(vis.make_grid(disp_X_recon_gt, nCols=nimgs)) + + # input images with prediction (and ground truth) + disp_images_pred = vis.to_disp_images(images[:nimgs], denorm=True) + disp_images_pred = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images_pred] + # disp_images_pred = vis.add_landmarks_to_images(disp_images_pred, lm_gt, color=gt_color, radius=radius) + disp_images_pred = vis.add_landmarks_to_images(disp_images_pred, lm_preds, color=pred_color, radius=radius, + draw_wireframe=draw_wireframes) + rows.append(vis.make_grid(disp_images_pred, nCols=nimgs)) + + if horizontal: + assert(nimgs == 1) + disp_rows = vis.make_grid(rows, nCols=len(rows)) + else: + disp_rows = vis.make_grid(rows, nCols=1) + wnd_title = 'recon errors ' + if ds is not None: + wnd_title += ds.__class__.__name__ + cv2.imshow(wnd_title, cv2.cvtColor(disp_rows, cv2.COLOR_RGB2BGR)) + cv2.waitKey(wait) \ No newline at end of file diff --git a/configs/callbacks/callback_audio2render.yaml b/configs/callbacks/callback_audio2render.yaml new file mode 100644 index 0000000..13f2adb --- /dev/null +++ b/configs/callbacks/callback_audio2render.yaml @@ -0,0 +1,36 @@ +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 \ No newline at end of file diff --git a/configs/dataset/motion_audio2render.yaml b/configs/dataset/motion_audio2render.yaml new file mode 100644 index 0000000..901b129 --- /dev/null +++ b/configs/dataset/motion_audio2render.yaml @@ -0,0 +1,32 @@ +_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" \ No newline at end of file diff --git a/configs/experiment/audio2render/train_audio2render_20220513.yaml b/configs/experiment/audio2render/train_audio2render_20220513.yaml new file mode 100644 index 0000000..b74e420 --- /dev/null +++ b/configs/experiment/audio2render/train_audio2render_20220513.yaml @@ -0,0 +1,61 @@ +# @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: [1,] + 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: 1 + num_workers: 8 + + 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 + + diff --git a/configs/model/model_audio2render.yaml b/configs/model/model_audio2render.yaml new file mode 100644 index 0000000..c2dabbe --- /dev/null +++ b/configs/model/model_audio2render.yaml @@ -0,0 +1,60 @@ +_target_: src.models.module_audio2render.Audio2RenderModel + +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: + 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 + + + + + diff --git a/scripts/Actor5Data/run-21-features-3dmm.py b/scripts/Actor5Data/run-21-features-3dmm.py new file mode 100644 index 0000000..ce51465 --- /dev/null +++ b/scripts/Actor5Data/run-21-features-3dmm.py @@ -0,0 +1,100 @@ +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! ") + + + diff --git a/scripts/Actor5Data/run-41-train-dict-data-raw-deca.py b/scripts/Actor5Data/run-41-train-dict-data-raw-deca.py new file mode 100644 index 0000000..a33f0c2 --- /dev/null +++ b/scripts/Actor5Data/run-41-train-dict-data-raw-deca.py @@ -0,0 +1,159 @@ +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}") \ No newline at end of file diff --git a/scripts/Actor5Data/run-42-train-split-data-list.py b/scripts/Actor5Data/run-42-train-split-data-list.py new file mode 100644 index 0000000..02b58f1 --- /dev/null +++ b/scripts/Actor5Data/run-42-train-split-data-list.py @@ -0,0 +1,159 @@ +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}") \ No newline at end of file diff --git a/src/datasets/components/motion_render_train.py b/src/datasets/components/motion_render_train.py new file mode 100644 index 0000000..7e4c1e3 --- /dev/null +++ b/src/datasets/components/motion_render_train.py @@ -0,0 +1,181 @@ +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 + + + + diff --git a/src/datasets/components/vggface.py b/src/datasets/components/vggface.py new file mode 100644 index 0000000..1da1076 --- /dev/null +++ b/src/datasets/components/vggface.py @@ -0,0 +1,232 @@ +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 \ No newline at end of file diff --git a/src/datasets/motion_datamodule.py b/src/datasets/motion_datamodule.py index 47b8daa..a61ef36 100644 --- a/src/datasets/motion_datamodule.py +++ b/src/datasets/motion_datamodule.py @@ -43,7 +43,6 @@ class MotionDataModule(LightningDataModule): self.dataset_valid = dataset_valid self.dataset_test = dataset_test - def train_dataloader(self): return DataLoader( dataset=self.dataset_train, diff --git a/src/losses/lossfunc.py b/src/losses/lossfunc.py index 5297b4e..7b4eb04 100755 --- a/src/losses/lossfunc.py +++ b/src/losses/lossfunc.py @@ -128,13 +128,14 @@ def batch_kp_2d_l1_loss(real_2d_kp, predicted_2d_kp, weights=None): kp_pred: N x K x 2 """ if weights is not None: - real_2d_kp[:,:,2] = weights[None,:]*real_2d_kp[:,:,2] + real_2d_kp[..., 2] = weights[None, None, :] * real_2d_kp[...,2] + kp_gt = real_2d_kp.view(-1, 3) kp_pred = predicted_2d_kp.contiguous().view(-1, 2) - vis = kp_gt[:, 2] + vis = kp_gt[..., 2] k = torch.sum(vis) * 2.0 + 1e-8 - dif_abs = torch.abs(kp_gt[:, :2] - kp_pred).sum(1) + dif_abs = torch.abs(kp_gt[..., :2] - kp_pred).sum(1) return torch.matmul(dif_abs, vis) * 1.0 / k @@ -142,9 +143,11 @@ def batch_kp_2d_l1_loss(real_2d_kp, predicted_2d_kp, weights=None): def landmark_loss(predicted_landmarks, landmarks_gt, weight=1.): # (predicted_theta, predicted_verts, predicted_landmarks) = ringnet_outputs[-1] if torch.is_tensor(landmarks_gt) is not True: - real_2d = torch.cat(landmarks_gt).cuda() + real_2d = torch.cat(landmarks_gt).to(predicted_landmarks.device) else: - real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1) + dims = landmarks_gt.shape + real_2d = torch.cat([landmarks_gt, + torch.ones(dims[:-2]+[68, 1]).to(landmarks_gt.device)], dim=-1) # (..., 68, 3) # real_2d = torch.cat(landmarks_gt).cuda() loss_lmk_2d = batch_kp_2d_l1_loss(real_2d, predicted_landmarks) @@ -154,20 +157,22 @@ def landmark_loss(predicted_landmarks, landmarks_gt, weight=1.): def eye_dis(landmarks): # left eye: [38,42], [39,41] - 1 # right eye: [44,48], [45,47] -1 - eye_up = landmarks[:,[37, 38, 43, 44], :] - eye_bottom = landmarks[:,[41, 40, 47, 46], :] + eye_up = landmarks[..., [37, 38, 43, 44], :] + eye_bottom = landmarks[..., [41, 40, 47, 46], :] dis = torch.sqrt(((eye_up - eye_bottom)**2).sum(2)) #[bz, 4] return dis def eyed_loss(predicted_landmarks, landmarks_gt, weight=1.): if torch.is_tensor(landmarks_gt) is not True: - real_2d = torch.cat(landmarks_gt).cuda() + real_2d = torch.cat(landmarks_gt).to(predicted_landmarks.device) else: - real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1) - - pred_eyed = eye_dis(predicted_landmarks[:,:,:2]) - gt_eyed = eye_dis(real_2d[:,:,:2]) + dims = landmarks_gt.shape + real_2d = torch.cat([landmarks_gt, + torch.ones(dims[:-2]+[68, 1]).to(landmarks_gt.device)], dim=-1) + + pred_eyed = eye_dis(predicted_landmarks[..., :2]) + gt_eyed = eye_dis(real_2d[..., :2]) loss = (pred_eyed - gt_eyed).abs().mean() return loss @@ -176,19 +181,21 @@ def eyed_loss(predicted_landmarks, landmarks_gt, weight=1.): def lip_dis(landmarks): # up inner lip: [62, 63, 64] - 1 # down innder lip: [68, 67, 66] -1 - lip_up = landmarks[:,[61, 62, 63], :] - lip_down = landmarks[:,[67, 66, 65], :] + lip_up = landmarks[..., [61, 62, 63], :] + lip_down = landmarks[..., [67, 66, 65], :] dis = torch.sqrt(((lip_up - lip_down)**2).sum(2)) #[bz, 4] return dis def lipd_loss(predicted_landmarks, landmarks_gt, weight=1.): if torch.is_tensor(landmarks_gt) is not True: - real_2d = torch.cat(landmarks_gt).cuda() + real_2d = torch.cat(landmarks_gt).to(predicted_landmarks.device) else: - real_2d = torch.cat([landmarks_gt, torch.ones((landmarks_gt.shape[0], 68, 1)).cuda()], dim=-1) - - pred_lipd = lip_dis(predicted_landmarks[:,:,:2]) + dims = landmarks_gt.shape + real_2d = torch.cat([landmarks_gt, + torch.ones(dims[:-2]+[68, 1]).to(landmarks_gt.device)], dim=-1) + + pred_lipd = lip_dis(predicted_landmarks[...,:2]) gt_lipd = lip_dis(real_2d[:,:,:2]) loss = (pred_lipd - gt_lipd).abs().mean() diff --git a/src/mesh/FLAME.py b/src/mesh/FLAME.py index e898904..77ece80 100644 --- a/src/mesh/FLAME.py +++ b/src/mesh/FLAME.py @@ -215,18 +215,35 @@ class FLAME(nn.Module): shape_params: N X number of shape parameters expression_params: N X number of expression parameters pose_params: N X number of pose parameters (6) + eye_pose_params: N x number of eye pose parameters(6) + template_vertices: N x 5023 x 3 return:d vertices: N X V X 3 landmarks: N X number of landmarks X 3 """ + # remember high dimenstion + shape_dims = shape_params.shape + if len(shape_dims) > 2: + shape_params = shape_params.reshape(-1, shape_params.shape[-1]) + expression_params = expression_params.reshape(-1, expression_params.shape[-1]) + if pose_params is not None: + pose_params = pose_params.reshape(-1, pose_params.shape[-1]) + if eye_pose_params is not None: + eye_pose_params = eye_pose_params.reshape(-1, eye_pose_params.shape[-1]) # (B x 6) + if template_vertices is not None: + template_vertices = template_vertices.reshape(-1, template_vertices.shape[-2], template_vertices.shape[-1]) # (B x 5023 x 3) + # get update batch size batch_size = shape_params.shape[0] if pose_params is None: pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6) if eye_pose_params is None: eye_pose_params = self.eye_pose.expand(batch_size, -1) # (B x 6) + if template_vertices is None: + template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) # (B x 5023 x 3) + # print(f"shape_params = {shape_params.shape}, expression_params={expression_params.shape}, pose_params={pose_params.shape}") # print(f"batch_size = {batch_size}, self.neck_pose={self.neck_pose.shape}") @@ -243,9 +260,7 @@ class FLAME(nn.Module): eye_pose_params # (B x 6), eye pose ], dim=1) - if template_vertices is None: - template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) # (B x 5023 x 3) - + vertices, _ = lbs(betas, pose, template_vertices, self.shapedirs, self.posedirs, self.J_regressor, self.parents, @@ -269,6 +284,14 @@ class FLAME(nn.Module): self.full_lmk_faces_idx.repeat(bz, 1), self.full_lmk_bary_coords.repeat(bz, 1, 1)) + + # expand dimension + if len(shape_dims) > 2: + vertices = vertices.reshape(list(shape_dims[:-1]) + list(vertices.shape[1:])) + landmarks2d = landmarks2d.reshape(list(shape_dims[:-1]) + list(landmarks2d.shape[1:])) + landmarks3d = landmarks3d.reshape(list(shape_dims[:-1]) + list(landmarks3d.shape[1:])) + + return vertices, landmarks2d, landmarks3d class FLAMETex(nn.Module): @@ -311,10 +334,22 @@ class FLAMETex(nn.Module): def forward(self, texcode): ''' texcode: [batchsize, n_tex] - texture: [bz, 3, 256, 256], range: 0-1 + texture: [batchsize, 3, 512, 512], range: 0-1 + ##### texture: [batchsize, 3, 256, 256], range: 0-1 ''' + # remember high dimenstion + shape_dims = texcode.shape + if len(shape_dims) > 2: + texcode = texcode.reshape(-1, texcode.shape[-1]) + texture = self.texture_mean + (self.texture_basis*texcode[:,None,:]).sum(-1) texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0,3,1,2) - texture = F.interpolate(texture, [256, 256]) - texture = texture[:,[2,1,0], :,:] + + ##### texture = F.interpolate(texture, [256, 256]) + texture = texture[:, [2,1,0], :,:] + + # expand dimension + if len(shape_dims) > 2: + texture = texture.reshape(list(shape_dims[:-1]) + list(texture.shape[1:])) + return texture \ No newline at end of file diff --git a/src/mesh/renderer.py b/src/mesh/renderer.py index 417b37b..cb42745 100755 --- a/src/mesh/renderer.py +++ b/src/mesh/renderer.py @@ -182,8 +182,8 @@ class SRenderY(nn.Module): self.uv_rasterizer = Pytorch3dRasterizer(uv_size) verts, faces, aux = load_obj(obj_filename) - uvcoords = aux.verts_uvs[None, ...] # (N, V, 2) - uvfaces = faces.textures_idx[None, ...] # (N, F, 3) + uvcoords = aux.verts_uvs[None, ...] # (N, V, 2) + uvfaces = faces.textures_idx[None, ...] # (N, F, 3) faces = faces.verts_idx[None,...] elif rasterizer_type == 'standard': @@ -236,6 +236,16 @@ class SRenderY(nn.Module): light_type: point or directional ''' + + # remember high dimenstion + shape_dims = vertices.shape + if len(shape_dims) > 3: + vertices = vertices.reshape(-1, vertices.shape[-2], vertices.shape[-1]) # (..., V, 3) + transformed_vertices = transformed_vertices.reshape(-1, transformed_vertices.shape[-2], transformed_vertices.shape[-1]) # (..., V, 3) + albedos = albedos.reshape(-1, albedos.shape[-3], albedos.shape[-2], albedos.shape[-1]) # (..., 3, h, w) + lights = lights.reshape(-1, lights.shape[-2], lights.shape[-1]) # (..., nfeat1, nfeat2) + + batch_size = vertices.shape[0] ## rasterizer near 0 far 100. move mesh so minz larger than 0 transformed_vertices[:,:,2] = transformed_vertices[:,:,2] + 10 @@ -283,17 +293,22 @@ class SRenderY(nn.Module): shading_images = images.detach()*0. outputs = { - 'images': images*alpha_images, - 'albedo_images': albedo_images*alpha_images, + 'images': images * alpha_images, + 'albedo_images': albedo_images * alpha_images, 'alpha_images': alpha_images, 'pos_mask': pos_mask, 'shading_images': shading_images, 'grid': grid, 'normals': normals, - 'normal_images': normal_images*alpha_images, + 'normal_images': normal_images * alpha_images, 'transformed_normals': transformed_normals, } + # expand dimension + if len(shape_dims) > 3: + for i in outputs.keys(): + outputs[i] = outputs[i].reshape(list(shape_dims[:-2]) + list(outputs[i].shape[1:])) + return outputs def add_SHlight(self, normal_images, sh_coeff): diff --git a/src/mesh/util.py b/src/mesh/util.py index 246997c..1d5ea8e 100755 --- a/src/mesh/util.py +++ b/src/mesh/util.py @@ -284,12 +284,24 @@ def batch_orth_proj(X, camera): ''' orthgraphic projection X: 3d vertices, [bz, n_point, 3] camera: scale and translation, [bz, 3], [scale, tx, ty] + Xn: ''' + # remember high dimenstion + shape_dims = X.shape + if len(shape_dims) > 3: + X = X.reshape(-1, X.shape[-2], X.shape[-1]) # (..., n_point, 3) + camera = camera.reshape(-1, camera.shape[-1]) # (..., 3) + camera = camera.clone().view(-1, 1, 3) X_trans = X[:, :, :2] + camera[:, :, 1:] X_trans = torch.cat([X_trans, X[:,:,2:]], 2) shape = X_trans.shape Xn = (camera[:, :, 0:1] * X_trans) + + # expand dimension + if len(shape_dims) > 3: + Xn = Xn.reshape(list(shape_dims[:-2]) + list(Xn.shape[1:])) + return Xn # -------------------------------------- image processing diff --git a/src/models/__init__.py b/src/models/__init__.py index d92e6bc..97f22c4 100644 --- a/src/models/__init__.py +++ b/src/models/__init__.py @@ -1,5 +1,4 @@ import torch -import torch.nn as nn import logging def init_weights(net, init_type='normal', init_gain=0.02): @@ -18,22 +17,22 @@ def init_weights(net, init_type='normal', init_gain=0.02): #print(classname, hasattr(m, 'weight'),) if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): if init_type == 'normal': - nn.init.normal_(m.weight.data, 0.0, init_gain) + torch.nn.init.normal_(m.weight.data, 0.0, init_gain) elif init_type == 'xavier': - nn.init.xavier_normal_(m.weight.data, gain=init_gain) + torch.nn.init.xavier_normal_(m.weight.data, gain=init_gain) elif init_type == 'kaiming': - nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') + torch.nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif init_type == 'orthogonal': - nn.init.orthogonal_(m.weight.data, gain=init_gain) + torch.nn.init.orthogonal_(m.weight.data, gain=init_gain) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_type) if hasattr(m, 'bias') and m.bias is not None: - nn.init.constant_(m.bias.data, 0.0) + torch.nn.init.constant_(m.bias.data, 0.0) elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies. - nn.init.normal_(m.weight.data, 1.0, init_gain) - nn.init.constant_(m.bias.data, 0.0) + torch.nn.init.normal_(m.weight.data, 1.0, init_gain) + torch.nn.init.constant_(m.bias.data, 0.0) logging.info('initialize network with %s' % init_type) net.apply(init_func) # apply the initialization function diff --git a/src/models/components/audio2coeff.py b/src/models/components/audio2coeff.py deleted file mode 100644 index 4d832b4..0000000 --- a/src/models/components/audio2coeff.py +++ /dev/null @@ -1,72 +0,0 @@ -import torch -import torch.nn as nn -import logging - -from .encoders import ResnetEncoder, VOCAEncoder -from ..mesh.FLAME import FLAME, FLAMETex - - -class Audio2Coeff(nn.Module): - - def __init__(self, opt, opt_FLAME): - super(Audio2Coeff, self).__init__() - - self.opt = opt - self.dim_motion = opt.dim_motion # 53 - self.dim_speech = opt.dim_speech # 29 - self.dim_hidden = opt.dim_hidden # 256 - - # creat model - self.driven = VOCAEncoder(outsize=self.dim_motion) - self.flame = FLAME(opt_FLAME) - - # setup render - - def _setup_renderer(self, model_cfg): - set_rasterizer(self.cfg.rasterizer_type) - self.render = SRenderY(self.image_size, obj_filename=model_cfg.topology_path, uv_size=model_cfg.uv_size, rasterizer_type=self.cfg.rasterizer_type).to(self.device) - - # face mask for rendering details - mask = imread(model_cfg.face_eye_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() - self.uv_face_eye_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device) - mask = imread(model_cfg.face_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() - self.uv_face_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device) - # displacement correction - fixed_dis = np.load(model_cfg.fixed_displacement_path) - self.fixed_uv_dis = torch.tensor(fixed_dis).float().to(self.device) - # mean texture - mean_texture = imread(model_cfg.mean_tex_path).astype(np.float32)/255.; mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous() - self.mean_texture = F.interpolate(mean_texture, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device) - # dense mesh template, for save detail mesh - self.dense_template = np.load(model_cfg.dense_template_path, allow_pickle=True, encoding='latin1').item() - - - - def forward(self, x): - """ forward function - Args: - x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit] - return: - pred: torch.Tensor, [nbatch x seqlen x dim_motion] - """ - (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29) - logging.debug(f"[forward] input x shape = {x.shape}") - - # preprocessing data - x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29) - x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1) - logging.debug(f"[forward] transpose x shape = {x.shape}") - - feat = self.encoder(x) # (B * nseq, 50) - logging.debug(f"[forward] encoder shape = {feat.shape}") - - pred = self.decoder(feat) # (B * nseq, dim_motion) - logging.debug(f"[forward] decoder shape = {pred.shape}") - - pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion) - logging.debug(f"[forward] reshape shape = {pred.shape}") - - - return pred - - diff --git a/src/models/components/audio2motion.py b/src/models/components/audio2motion.py new file mode 100644 index 0000000..4a5245d --- /dev/null +++ b/src/models/components/audio2motion.py @@ -0,0 +1,89 @@ +import torch +import torch.nn as nn +import logging + +class Audio2Motion(nn.Module): + + def __init__(self, nc_motion, nc_condit): + super(Audio2Motion, self).__init__() + + self.nc_motion = nc_motion # 53 + self.nc_condit = nc_condit # 29 + + # creat model + self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1) + nn.BatchNorm2d(self.nc_condit), + + # block 1 + nn.Conv2d(self.nc_condit, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + + nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + + nn.Flatten(), # 64, + + nn.Linear(in_features=128, out_features=2048), # 128, + nn.Tanh(), + + nn.Linear(in_features=2048, out_features=128) # 50, + ) + + # output + self.decoder = nn.Sequential( + nn.Linear(in_features=128, out_features=self.nc_motion), + ) + + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [B x nwind x dim_condit] + return: + pred: torch.Tensor, [B x nc_motion] + """ + logging.debug(f"[forward] input x shape = {x.shape}") + + # remember high dimenstion + shape_dims = x.shape + if len(shape_dims) > 3: + x = x.reshape(-1, x.shape[-2], x.shape[-1]) + + # preprocessing data + x = x.unsqueeze(dim=1).transpose(1,3) # (B, 1, W, nc_motion) --> (B, nc_motion, W, 1) + logging.debug(f"[forward] transpose x shape = {x.shape}") + + feat = self.encoder(x) # (B, 50) + logging.debug(f"[forward] encoder shape = {feat.shape}") + + pred = self.decoder(feat) # (B, nc_motion) + logging.debug(f"[forward] decoder shape = {pred.shape}") + + # recover high dimension + if len(shape_dims) > 3: + pred = pred.reshape(list(shape_dims[:-2]) + list(pred.shape[1:])) + + logging.debug(f"[forward] reshape shape = {pred.shape}") + return pred + + diff --git a/src/models/module_audio2coeff.py b/src/models/module_audio2render.py similarity index 72% rename from src/models/module_audio2coeff.py rename to src/models/module_audio2render.py index 9ce246c..55454a3 100644 --- a/src/models/module_audio2coeff.py +++ b/src/models/module_audio2render.py @@ -24,7 +24,7 @@ from src.mesh import util from src.utils.animation import write_video, write_video_with_gt -class Audio2CoeffModel(LightningModule): +class Audio2RenderModel(LightningModule): def __init__( self, @@ -61,23 +61,26 @@ class Audio2CoeffModel(LightningModule): # init netG init_weights(self.netG, init_type='kaiming') - # init last layer - init_exp_weight = np.load(opt.path_init_expression_basis) - init_exp_weight = torch.from_numpy(init_exp_weight).float() #.to(self.device) - init_exp_weight = init_exp_weight[:, :50] - self.netG.decoder_mesh.weight.data = init_exp_weight - logging.info(f"init_exp_weight shape = {init_exp_weight.shape}") + # # init last layer + # init_exp_weight = np.load(opt.path_init_expression_basis) + # init_exp_weight = torch.from_numpy(init_exp_weight).float() #.to(self.device) + # init_exp_weight = init_exp_weight[:, :50] + # self.netG.decoder_mesh.weight.data = init_exp_weight + # logging.info(f"init_exp_weight shape = {init_exp_weight.shape}") # load mean path_deca_mean = self.opt.path_mean_dict self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + # save mean shape + self.register_buffer("mean_shape", torch.from_numpy(self.mean_dict["shape"].reshape(1, 1, 100))) # (1,1,100) + + # get template (with specific avator) - temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) + temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) temp_verts_specific, temp_ldmk2d_specific, 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.register_buffer("temp_verts", temp_verts) self.register_buffer("temp_verts_specific", temp_verts_specific) @@ -86,8 +89,8 @@ class Audio2CoeffModel(LightningModule): vertices_weight[:, :, flame_mouth_idx, :] = 10 self.register_buffer("vertices_weight", vertices_weight) - landmarks_weight = self._set_landmark68_weight() - self.register_buffer("landmarks_weight", landmarks_weight) + landmark_weight = self._set_landmark68_weight() + self.register_buffer("landmark_weight", landmark_weight) # loss function self.loss_func_wing = WingLoss(reduction="none") # return (B, ) @@ -166,14 +169,18 @@ class Audio2CoeffModel(LightningModule): param.requires_grad = False # face mask for rendering details - mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255. - mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() - uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) + mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255. + mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() # (1, 1, 256, 256) + uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 512, 512) + # mask = torch.from_numpy(mask[:,:,0])[None, None,None,:,:].contiguous() # (1, 1, 1, 256, 256) + # uv_face_eye_mask = F.interpolate(mask, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512) self.register_buffer("uv_face_eye_mask", uv_face_eye_mask) mask = imread(opt_netR.face_mask_path).astype(np.float32)/255. - mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() - uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) + # mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() # (1, 1, 256, 256) + # uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 512, 512) + mask = torch.from_numpy(mask[:,:,0])[None, None,None,:,:].contiguous() # (1, 1, 1, 256, 256) + uv_face_mask = F.interpolate(mask, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512) self.register_buffer("uv_face_mask", uv_face_mask) # # displacement correction @@ -183,10 +190,14 @@ class Audio2CoeffModel(LightningModule): # mean texture mean_texture = imread(opt_netR.mean_tex_path).astype(np.float32)/255. - mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous() - mean_texture = F.interpolate(mean_texture, [opt_netR.uv_size, opt_netR.uv_size]) + mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,None, :,:,:].contiguous() # (1, 1, 1, 256, 256) + mean_texture = F.interpolate(mean_texture, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512) self.register_buffer("mean_texture", mean_texture) + + debug(f"uv_face_eye_mask = {uv_face_eye_mask.shape}, uv_face_mask={uv_face_mask.shape},mean_texture={mean_texture.shape}") + + # # dense mesh template, for save detail mesh # self.dense_template = np.load(opt_netR.dense_template_path, allow_pickle=True, encoding='latin1').item() @@ -233,34 +244,9 @@ class Audio2CoeffModel(LightningModule): @torch.no_grad() def set_input(self, batch:Any): - - # logging.info(f"\n[set_input] self.device = {self.device}") - # motion data - data = batch["data"].float() # (B, nsteps, nc_motion) - debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False) - - - images = batch['image'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size] - images = images.view(-1, images.shape[-3], images.shape[-2], images.shape[-1]) - lmk = batch['landmark'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size] - lmk = lmk.view(-1, lmk.shape[-2], lmk.shape[-1]) - masks = batch['mask'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size] - masks = masks.view(-1, images.shape[-2], images.shape[-1]) - - # batch information - batch_info = { - "vid": batch['vid'], - "nframe": batch['nframe'], - "interv": batch['frame_interval'], - "images": images, - "lmk": lmk, - "masks": masks - } - - # speech data - cond = None - raw_speech = batch["cond"].cpu().numpy() # (B, nsegments) + # processing speech feature + raw_speech = batch["data_audio"].cpu().numpy() # (B, nsegments) debug(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) # padding half frame length for bed and end @@ -269,103 +255,122 @@ class Audio2CoeffModel(LightningModule): debug(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt") - cond = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat - debug(f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False) + audio_feat = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat + debug(f"audio_feat = {audio_feat.shape}, dtype={audio_feat.dtype}, device={audio_feat.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) + audio_feat = audio_feat.unfold(dimension=1, size=16, step=1) # (B, N, nc_codit, 16) + audio_feat = audio_feat.permute(0, 1, 3, 2) # (B, N, 16, nc_condit) + B, N, W, nc_condit = audio_feat.size() - # 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) + # setup raw-speech + idx_segmt_beg = int(7 * self.opt.sr / self.opt.fps + 0.5) + idx_segmt_end = int((7 + N) * self.opt.sr / self.opt.fps + 0.5) + raw_speech = raw_speech[:, idx_segmt_beg: idx_segmt_end] # (B, nsteps * sr / fps) - # cut audio clips - idx_beg = int(7 * self.opt.sr / self.opt.fps + 0.5) - idx_end = int((7 + self.nsteps) * self.opt.sr / self.opt.fps + 0.5) - self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps) + # setup others data + data_coeff = batch["data_coeff"][:, 7:7+N] # (B, N, nc_coeff) + data_frame = batch['data_frame'][:, 7:7+N] # [B, N, 3, 512, 512] + data_mask = batch['data_mask'][:, 7:7+N] # [B, N, 512, 512] + data_ldmk = batch['data_ldmk'][:, 7:7+N] # [B, N, 68, 2] - debug(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False) - debug(f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) - debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False) - debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False) + # update batch information + batch["data_audio"] = audio_feat # (B, N, 16, nc_condit) + batch["data_frame"] = data_frame # [B, N, 3, 512, 512] + batch["data_mask"] = data_mask # [B, N, 512, 512] + batch["data_ldmk"] = data_ldmk # [B, N, 68, 2] + batch["data_coeff"] = data_coeff # (B, N, 236) + batch["raw_speech"] = raw_speech # (B, N * sr / fps) - return self.cond, self.vert, batch_info + debug(f"[set_input] audio_feat = {audio_feat.shape}, dtype={audio_feat.dtype}, device={audio_feat.device}", verbose=False) + debug(f"[set_input] data_frame = {data_frame.shape}, dtype={data_frame.dtype}, device={data_frame.device}", verbose=False) + debug(f"[set_input] data_mask = {data_mask.shape}, dtype={data_mask.dtype}, device={data_mask.device}", verbose=False) + debug(f"[set_input] data_ldmk = {data_ldmk.shape}, dtype={data_ldmk.dtype}, device={data_ldmk.device}", verbose=False) + debug(f"[set_input] data_coeff = {data_coeff.shape}, dtype={data_coeff.dtype}, device={data_coeff.device}", verbose=False) + debug(f"[set_input] raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) + + return B, N, batch def forward(self, x:torch.Tensor): - return self.netG(x) + pass - def step(self, batch:Any, return_vis:bool=False): + def step(self, batch:Any): - batch_x, batch_tgt, batch_info = self.set_input(batch) - B, N = batch_x.size(0), batch_x.size(1) # get batch_size + B, N, batch_set = self.set_input(batch) + + batch_x = batch_set["data_audio"] # (B, N, 16, nc_condit) + batch_pdt = self.netG(batch_x) # (B, N, nc_motion=53) + debug(f"batch_pdt = {batch_pdt.shape}") - # get exp + pos - batch_pdt = self.netG(batch_x) # B*N x dim_motion # prepare codedict for render codedict = {} - codedict["exp"] = batch_pdt['exp'] # from predict - codedict["pos"] = batch_pdt['pos'] # from predict + codedict["exp"] = batch_pdt[:, :, :50] # (B, N, 50), from predict + codedict["shape"] = self.mean_shape.expand(B, N, -1) # (B, N, 100), use mean shape, NOT GT + codedict["tex"] = batch_set['data_coeff'][:, :, 100:150] # (B, N, 50), from GT + codedict["cam"] = batch_set['data_coeff'][:, :, 206:209] # (B, N, 3), from GT + codedict["light"] = batch_set['data_coeff'][:, :, 209:236].reshape(B, N, 9, 3) # (B, N, 9, 3), from GT + codedict["pose"]= torch.cat([ # (B, N, 6), from GT & predict + batch_set['data_coeff'][:, :, 150:153], # head pose, from GT + batch_pdt[:, :, 50:53], # mouth pose, from predict result + ], dim=2) - codedict["shape"] = batch_info['shape'] # from ** mean ** shape - codedict["tex"] = batch_info['tex'] # from predict - codedict["cam"] = batch_info['cam'] # from predict - codedict["pose"] = batch_info['pose'] # from predict - codedict["light"] = batch_info['light'] # from predict - - # # get geometry vertice - verts, landmarks2d, landmarks3d = self.netF( + verts, landmarks2d, landmarks3d = self.netF( # (B, N, 5023, 3), (B,N,68,3), (B,N,68,3) shape_params=codedict['shape'], expression_params=codedict['exp'], pose_params=codedict['pose']) + debug(f"verts = {verts.shape},landmarks2d={landmarks2d.shape}, landmarks3d = {landmarks3d.shape}") # get albedo texture - albedo = self.netT(codedict['tex']) + albedo = self.netT(codedict['tex']) # (B, N, 3, 512, 512) + debug(f"albedo = {albedo.shape}") ## projection with camera (2D landmarks, 3D landmarks, verts) landmarks3d_world = landmarks3d.clone() - landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[:,:,:2] - landmarks2d[:,:,1:] = -landmarks2d[:,:,1:] + landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[..., :2] + landmarks2d[..., 1:] = -landmarks2d[..., 1:] + landmarks3d = util.batch_orth_proj(landmarks3d, codedict['cam']) - landmarks3d[:,:,1:] = -landmarks3d[:,:,1:] + landmarks3d[..., 1:] = -landmarks3d[..., 1:] + trans_verts = util.batch_orth_proj(verts, codedict['cam']) - trans_verts[:,:,1:] = -trans_verts[:,:,1:] + trans_verts[..., 1:] = -trans_verts[..., 1:] # render to image ops = self.netR(verts, trans_verts, albedo, codedict['light']) + ## output opdict = { - 'images': batch_info['images'], - 'lmk': batch_info['lmk'], - 'albedo': albedo, - 'verts': verts, - 'trans_verts': trans_verts, - 'landmarks2d': landmarks2d, - 'landmarks3d': landmarks3d, - 'landmarks3d_world': landmarks3d_world, - 'grid': ops['grid'], - 'rendered_images': ops['images'], - 'alpha_images': ops['alpha_images'], - 'normal_images': ops['normal_images'] + 'albedo': albedo, # (B, N, 3, 512, 512) + 'verts': verts, # (B, N, 5023, 3) + 'trans_verts': trans_verts, # (B, N, 5023, 3) + 'landmarks2d': landmarks2d, # (B, N, 68, 2) + 'landmarks3d': landmarks3d, # (B, N, 68, 3) + 'landmarks3d_world': landmarks3d_world, # (B, N, 68, 3) + 'grid': ops['grid'], # (B, N, 512, 512, 2) + 'rendered_images': ops['images'], # (B, N, 3, 512, 512) + 'alpha_images': ops['alpha_images'], # (B, N, 1, 512, 512) + 'normal_images': ops['normal_images'] # (B, N, 3, 512, 512) } - # get mask predicted_images - mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B,-1,-1,-1), opdict['grid'].detach(), align_corners=False) + debug(f"grid = {ops['grid'].shape},rendered_images={ops['images'].shape}, alpha_images={ops['alpha_images'].shape}, normal_images={ops['normal_images'].shape}") + + # get mask predicted_images # uv_face_eye_mask > (1, 1, 1, 512, 512) + opdict['grid'] = opdict['grid'].reshape(B*N, 512, 512, 2) + mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B*N, -1,-1,-1), opdict['grid'].detach(), align_corners=False) + mask_face_eye = mask_face_eye.reshape(B, N, mask_face_eye.shape[-3], mask_face_eye.shape[-2], mask_face_eye.shape[-1]) + predicted_images = opdict['rendered_images'] * mask_face_eye * opdict['alpha_images'] opdict['predicted_images'] = predicted_images + debug(f"mask_face_eye = {mask_face_eye.shape}, predicted_images={predicted_images.shape}") - + # eval loss - loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt) - - - return loss, loss_dict, batch_pdt, batch_tgt, batch_info + loss, loss_dict = self.eval_losses(batch_set, opdict, mask_face_eye, batch_pdt) + return loss, loss_dict def training_step(self, batch, batch_idx): @@ -439,45 +444,54 @@ class Audio2CoeffModel(LightningModule): self.test_rec.reset(), self.test_vel.reset() - def eval_loss(self, lmk, mask_face_eye, images, predicted_images, opdict, codedict): + def eval_losses(self, batch_set, opdict, mask_face_eye, batch_pdt): loss = 0 loss_dict = {} ## base shape - predicted_landmarks = opdict['landmarks2d'] + tgt_ldmk = batch_set["data_ldmk"] # [B, N, 68, 2], GT 2D landmarks + pdt_ldmk = opdict['landmarks2d'] # [B, N, 68, 2], PT 2D lanmdarks # landmarks loss - loss_lmk = lossfunc.landmark_loss(predicted_landmarks, lmk, self.landmak_weight) + loss_lmk = lossfunc.landmark_loss(pdt_ldmk, tgt_ldmk, self.landmark_weight) loss_dict['landmark'] = loss_lmk.detach() - if self.opt_loss.lmk > 0.0: - loss += loss_lmk * self.opt_loss.lmk + if self.opt_loss.lambda_lmk > 0.0: + loss += loss_lmk * self.opt_loss.lambda_lmk # eye closure loss - loss_eye = lossfunc.eyed_loss(predicted_landmarks, lmk) + loss_eye = lossfunc.eyed_loss(pdt_ldmk, tgt_ldmk) loss_dict['eye_distance'] = loss_eye.detach() - if self.opt_loss.eyed > 0.0: - loss += loss_eye * self.opt_loss.eyed + if self.opt_loss.lambda_eyed > 0.0: + loss += loss_eye * self.opt_loss.lambda_eyed # lip closure loss - loss_lip = lossfunc.lipd_loss(predicted_landmarks, lmk) + loss_lip = lossfunc.lipd_loss(pdt_ldmk, tgt_ldmk) loss_dict['lip_distance'] = loss_lip.detach() - if self.opt_loss.lipd > 0.0: - loss += loss_lip * self.opt_loss.lipd + if self.opt_loss.lambda_lipd > 0.0: + loss += loss_lip * self.opt_loss.lambda_lipd # photometric loss - masks = masks[:,None,:,:] if self.opt_loss.useSeg else (mask_face_eye * opdict['alpha_images']) - loss_pho = masks * (predicted_images - images).abs().mean() + tgt_image = batch_set["data_frame"] # [B, N, 3, 512, 512] + pdt_image = opdict['predicted_images'] # [B, N, 3, 512, 512] + tgt_mask = batch_set["data_mask"] # [B, N, 512, 512] + + if self.opt_loss.useSeg: + tgt_mask = tgt_mask[:,:,None,:,:] # [B, N, 1, 512, 512] + else: + tgt_mask = (mask_face_eye * opdict['alpha_images']) + + loss_pho = tgt_mask * (pdt_image - tgt_image).abs().mean() loss_dict['photometric_texture'] = loss_pho.detach() - if self.opt_loss.photo > 0.0: - loss += loss_pho * self.opt_loss.photo + if self.opt_loss.lambda_photo > 0.0: + loss += loss_pho * self.opt_loss.lambda_photo # expression regularization - loss_reg = torch.sum(codedict['exp']**2)/2 + loss_reg = torch.sum(batch_pdt**2)/2 loss_dict['expression_reg'] = loss_reg.detach() - if self.opt_loss.reg > 0.0 : + if self.opt_loss.lambda_reg > 0.0 : # import ipdb; ipdb.set_trace() - loss += loss_reg * self.opt_loss.reg + loss += loss_reg * self.opt_loss.lambda_reg ######################################################### @@ -486,8 +500,7 @@ class Audio2CoeffModel(LightningModule): return loss, loss_dict - - def eval_losses(self, batch_pdt_geo, batch_tgt_geo): + def eval_losses2(self, batch_pdt_geo, batch_tgt_geo): """ Computes the loss function. pramas: batch_tgt_geo, (nbatch, seqlen, num_vertices, 3) @@ -633,7 +646,7 @@ class Audio2CoeffModel(LightningModule): @torch.no_grad() 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_pdt_pos, [B x N x nc_motion] # batch_speech, [B x N*sr/fps ] B, N, *_ = batch_pdt_geo.shape diff --git a/src/utils/debug.py b/src/utils/debug.py index 9eb0164..19a8313 100644 --- a/src/utils/debug.py +++ b/src/utils/debug.py @@ -1,5 +1,5 @@ -FLAG_DEBUG = False +FLAG_DEBUG = True def debug(msg="", verbose=False): if FLAG_DEBUG or verbose: