remove lfs

This commit is contained in:
sen.liang committed 2025-05-24 14:54:46 +08:00
1 parent 6fe3a2c3cd
commit 4a53051fee
196 files changed
-42808

No files matched your search

View File
Whitespace-only changes.
-343
View File
@@ -1,343 +0,0 @@
import moviepy.editor as mpy
import numpy as np
import os
import cv2
import sys
# sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.landmark import landmark_to_images
import tempfile
from scipy.io import wavfile
def save_animation(data_motion, path_save, suffix, w=128*5, h=72*5, dpi=80):
""" convert data_motion to .mp4 animation
data_motion, shape [B, N, 136, ...]
"""
# no need invert
# anim_clips = inv_standardize(data_motion[:self.nseq_test, :, :], self.motion_scaler)
fps = 30
B, *_ = data_motion.shape
for i in range(B):
idata_pt = data_motion[i, :, :].reshape(-1, 68, 2)
images_pt = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex="PT")
duration = idata_pt.shape[0] / fps
# animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) - 1,...], duration= duration )
animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5),...], duration= duration )
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
animation.write_videofile(str(ipath_save), fps=fps, logger=None)
def save_animation_ws_audio(data_motion, path_save, path_audio=None, start_time=None, end_time=None, fps=30, w=256, h=256, dpi=150):
""" convert data_motion to .mp4 animation
data_motion, shape [nsteps, 136]
"""
# fps = 30
nsteps = data_motion.shape[0]
data_motion = data_motion.copy().reshape(nsteps, 68, 2) # nsteps x 68 x 2
image = landmark_to_images(data_motion, w=w, h=h, dpi=dpi, norm=True, prex="PT") # (nsteps, H, W, 3)
duration = nsteps / fps
animation = mpy.VideoClip(lambda t: image[int(fps * t + 0.5),...], duration= duration )
duration = animation.duration
if path_audio is not None:
audioclip = mpy.AudioFileClip(str(path_audio))
# cut-off
if (start_time is not None) and (end_time is not None):
audioclip = audioclip.subclip(start_time, end_time)
# alignment to video
audioclip = audioclip.set_duration(duration)
# add audio to animation
animation = animation.set_audio(audioclip)
animation = animation.set_duration(duration)
# save
animation.write_videofile(str(path_save), fps=fps, logger=None)
def save_animation_grid(data_motion, path_save, path_audio=None, start_time=None, end_time=None, ncol=3, w=128*5, h=72*5, dpi=80):
""" convert data_motion to .mp4 animation
data_motion, shape [N, nsteps, 136]
"""
# no need invert
# anim_clips = inv_standardize(data_motion[:self.nseq_test, :, :], self.motion_scaler)
fps = 30
N, nsteps, _ = data_motion.shape
total_image = []
for i in range(N):
idata_pt = data_motion[i, :, :].reshape(-1, 68, 2) # nsteps x 68 x 2
prex = "ground-truth" if i == 0 else f"prediction-{i-0:02d}"
image = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex=prex) # (nsteps, H, W, 3)
total_image.append(image)
print(f"images shape = {image.shape}")
total_image = np.concatenate(total_image, axis=0) # N x nsteps x H x W x 3
total_image = total_image.reshape(N//ncol, ncol, nsteps, h, w, 3)
total_image = total_image.transpose((2, 0, 3, 1, 4, 5)) # nsteps x nrow x H x ncol x W x 3
total_image = total_image.reshape(nsteps, -1, ncol*w, 3) # nsteps x nrow*H x ncol*W x 3
print(f"total images shape = {total_image.shape}")
duration = nsteps / fps
animation = mpy.VideoClip(lambda t: total_image[int(fps * t + 0.5),...], duration= duration )
# animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) ,...], duration= duration )
duration = animation.duration
if path_audio is not None:
audioclip = mpy.AudioFileClip(str(path_audio))
# cut-off
if (start_time is not None) and (end_time is not None):
audioclip = audioclip.cutout(start_time, end_time)
# alignment to video
audioclip = audioclip.set_duration(duration)
# add audio to animation
animation = animation.set_audio(audioclip)
animation = animation.set_duration(duration)
# save
animation.write_videofile(str(path_save), fps=fps, logger=None)
def save_animation2(images, path_save):
fps = 30
duration = len(images) / fps
animation = mpy.VideoClip(lambda t: images[int(fps * t + 0.5) - 1], duration= duration )
animation.write_videofile(str(path_save), fps=fps, logger=None)
def save_animation_with_gts(images_list, path_save):
""" convert images_pt to .mp4 animation
images_pt, shape len=N list [224, 224, 3]
images_gt, shape len=N list [224, 224, 3]
"""
# print(f"images_pt shape = {len(images_list[0])}, shape[0]={images_pt[0].shape}")
fps = 30
N = len(images_list[0])
duration = N / fps
print(f"fps = {fps}, N ={N}, duration={duration}")
# assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})"
animations = []
for images in images_list:
animations.append(mpy.VideoClip(lambda t: images[int(fps * t + 0.5) -1], duration= duration))
# mixture & save
animation = mpy.clips_array([animations])
animation.write_videofile(str(path_save), fps=fps, logger=None)
# close
animation.close()
# def write_videos(images, raw_speech, path_save, fps=50):
def write_video(list_images, raw_speech, path_video, fps=50, sr=16000):
""" convert images_pt to .mp4 animation
list_images, shape len=N list [512, 512, 3], or [1080, 1920, 3]
raw_speech, shape = (nsegmet, )
"""
num_frame = len(list_images)
H, W = list_images[0].shape[:2]
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=sr, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (W, H), True)
for i in range(num_frame):
writer.write(list_images[i])
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
# close tmp file
file_audio.close()
file_video.close()
def write_video_with_gt(images_pt, images_gt, raw_speech, path_video, fps=50, sr=16000):
""" convert images_pt to .mp4 animation
images_pt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3]
images_gt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3]
raw_speech, shape = (nsegmet, )
"""
num_frame = len(images_pt)
H, W = images_pt[0].shape[:2]
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=sr, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (2*W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True)
for i in range(num_frame):
concate_image = np.concatenate((images_pt[i], images_gt[i]), axis=1) # (H, 2*W, 3)
writer.write(concate_image)
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
# close tmp file
file_audio.close()
file_video.close()
def save_images_with_audio(images, path_audio, path_save, fps=50):
""" convert images_pt to .mp4 animation
images_pt, shape len=N list [224, 224, 3]
images_gt, shape len=N list [224, 224, 3]
"""
N = len(images)
duration = N / fps
audioclip = mpy.AudioFileClip(str(path_audio))
print(f"\naudio clip duration = {audioclip.duration}, N={N}, fps={fps}, duration_N/fps={duration}")
if audioclip.duration + 0.0001 < duration:
print("\n\n\n ERROR: ")
# assert audioclip.duration + 0.0001 < duration,
audioclip = audioclip.set_duration(duration)
# add video
animation = mpy.VideoClip(lambda t: images[int(fps * t + 0.5) -1], duration= duration)
animation = animation.set_audio(audioclip) # add audio to animation
# save
animation.write_videofile(str(path_save), fps=fps)
print(f"animation duration={animation.duration}, > save to = {path_save}")
# close
audioclip.close()
animation.close()
# add
path_save2 = str(path_save).replace(".mp4", "2.mp4")
cmd = f"ffmpeg -y -i {str(path_save)} -i {str(path_audio)} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest {str(path_save2)}"
os.system(cmd)
# del
cmd = f"rm {str(path_save)}"
os.system(cmd)
def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audio=None, start_time=None, end_time=None):
""" convert images_pt to .mp4 animation
images_pt, shape len= N list [224, 224, 3]
images_gt, shape len= N list [224, 224, 3]
"""
# print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}")
fps = fps if fps else 50
N = len(images_pt)
duration = N / fps
# print(f"fps = {fps}, N ={N}, duration={duration}")
# assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})"
animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) -1], duration= duration)
animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5) -1], duration= duration)
# mixture & save
animation = mpy.clips_array([[animation_pt, animation_gt]])
if path_audio is not None:
audioclip = mpy.AudioFileClip(str(path_audio))
# cut-off
if (start_time is not None) and (end_time is not None):
print(f"subclip clips {start_time}:{end_time}")
audioclip = audioclip.subclip(start_time, end_time)
# alignment to video
audioclip = audioclip.set_duration(duration)
# add audio to animation
animation = animation.set_audio(audioclip)
animation = animation.set_duration(duration)
animation.write_videofile(str(path_save), fps=fps)
# close
animation_pt.close()
animation_gt.close()
animation.close()
def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30):
""" convert data_motion to .mp4 animation
data_motion, shape [B, N, 68, 2]
data_motion_gt, shape [B, N, 68, 2]
"""
B, *_ = data_motion.shape
B = min(B, maxsave)
for i in range(B):
idata_pt = data_motion[i].reshape(-1, 68, 2)
idata_gt = data_motion_gt[i].reshape(-1, 68, 2)
images_pt = landmark_to_images(idata_pt, w=w, h=h, dpi=dpi, norm=True, prex="PT")
images_gt = landmark_to_images(idata_gt, w=w, h=h, dpi=dpi, norm=True, prex="GT")
duration = idata_pt.shape[0] / fps
# animation = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) - 1,...], duration= duration )
animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5),...], duration= duration)
animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5),...], duration= duration)
# mixture
animation = mpy.clips_array([[animation_pt, animation_gt]])
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
animation.write_videofile(str(ipath_save), fps=fps, logger=None)
# close
animation_pt.close()
animation_gt.close()
animation.close()
-9
View File
@@ -1,9 +0,0 @@
def debug(opt=None, msg="", verbose=False):
if opt is None or verbose:
print(msg)
if opt.DEBUG or verbose:
print(msg)
-135
View File
@@ -1,135 +0,0 @@
import torch
# target, torch.Tensor, (Bx2x16, 68, 2)
def get_mouth_width(landmark):
""" Get mouth width between L48 and L54
Params:
landmark: torch, (N, 68, 2)
Return:
tensor, (N,)
"""
WM = (landmark[:, 48, :] - landmark[:, 54, :]) * (landmark[:, 48, :] - landmark[:, 54, :]) # (N, 2)
WM = torch.sqrt(WM[:, 0] + WM[:, 1])
return WM
def get_mouth_open_param(landmark, eps=1e-6):
""" Get mouth open distance and rate
Params:
landmark: torch, (N, 68, 2)
Return:
two tensors: lip distance and open rate (N,), (N, )
"""
up = 0.5 * (landmark[:, 50, :] + landmark[:, 52, :])
dw = 0.5 * (landmark[:, 56, :] + landmark[:, 58, :])
distance = (up - dw) * (up -dw) # (N, 2)
distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, )
width = get_mouth_width(landmark)
rate = distance / (width + eps)
rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1
# assert torch.any(torch.isnan(rate)), f"rate have nan"
# if torch.any(torch.isnan(rate)) or torch.any(torch.isinf(rate)) :
# # print("KKKKKK,",rate)
# for i, item in enumerate(rate):
# if torch.isnan(item) or torch.isinf(item):
# print(f"error mouth nan, item = {item} distance = {distance[i]}, width={width[i]}, data = {landmark[i, [50,52,56,58]]}")
return distance, rate
def get_eye_width(landmark):
""" Get left eye width between L36 and L39, and right eye width between L42 and L45
Params:
landmark: torch, (N, 68, 2)
Return:
two tensor of left and right eye width , (N,), (N,)
"""
return get_left_eye_width(landmark), get_right_eye_width(landmark)
def get_left_eye_width(landmark):
""" Get left eye width between L36 and L39, and right eye width between L42 and L45
Params:
landmark: torch, (N, 68, 2)
Return:
two tensor of left and right eye width , (N,), (N,)
"""
WL = (landmark[:, 36, :] - landmark[:, 39, :]) * (landmark[:, 36, :] - landmark[:, 39, :]) # (N, 2)
WL = torch.sqrt(WL[:, 0] + WL[:, 1])
return WL
def get_right_eye_width(landmark):
""" Get left eye width between L36 and L39, and right eye width between L42 and L45
Params:
landmark: torch, (N, 68, 2)
Return:
two tensor of left and right eye width , (N,), (N,)
"""
WR = (landmark[:, 42, :] - landmark[:, 45, :]) * (landmark[:, 42, :] - landmark[:, 45, :]) # (N, 2)
WR = torch.sqrt(WR[:, 0] + WR[:, 1])
return WR
def get_eye_open_param(landmark):
""" Get left/right eye open distance and rate
Params:
landmark: torch, (N, 68, 2)
Return:
four tensors: left/right eye distance and open rate (N,), (N, )
"""
L_dist, L_rate = get_left_eye_open_param(landmark)
R_dist, R_rate = get_right_eye_open_param(landmark)
return L_dist, L_rate, R_dist, R_rate
def get_left_eye_open_param(landmark, eps=1e-6):
""" Get left eye open distance and rate
Params:
landmark: torch, (N, 68, 2)
Return:
four tensors: left eye distance and open rate (N,), (N, )
"""
up = 0.5 * (landmark[:, 37, :] + landmark[:, 38, :])
dw = 0.5 * (landmark[:, 40, :] + landmark[:, 41, :])
distance = (up - dw) * (up -dw) # (N, 2)
distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, )
width = get_left_eye_width(landmark)
rate = distance / (width + eps)
rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1
# if torch.any(torch.isnan(rate)) or torch.any(torch.isinf(rate)) :
# # print("KKKKKK,",rate)
# for i, item in enumerate(rate):
# if torch.isnan(item) or torch.isinf(item):
# print(f"error eye nan, item = {item} distance = {distance[i]}, width={width[i]}, data = {landmark[i, 37:42]}")
return distance, rate
def get_right_eye_open_param(landmark, eps = 1e-6):
""" Get left eye open distance and rate
Params:
landmark: torch, (N, 68, 2)
Return:
four tensors: left eye distance and open rate (N,), (N, )
"""
up = 0.5 * (landmark[:, 43, :] + landmark[:, 44, :])
dw = 0.5 * (landmark[:, 46, :] + landmark[:, 47, :])
distance = (up - dw) * (up -dw) # (N, 2)
distance = torch.sqrt(distance[:, 0] + distance[:, 1]) # (N, )
rate = distance / (get_left_eye_width(landmark) + eps)
rate = torch.where(torch.isinf(rate), torch.full_like(rate, 1), rate) # for bigger rate --> 1
return distance, rate
-121
View File
@@ -1,121 +0,0 @@
"""
This utils for geometry transform and carera projection
"""
import torch
import torch.nn as nn
import numpy as np
import render_util
def euler2rot(euler):
"""Convert euler to rotation matrix
params:
euler: torch.Tensor, (nbatch, 3)
return:
rotation matrix, torch.Tensor, (nbtach, 3, 3)
"""
batch_size = euler.shape[0]
theta = euler[:, 0].reshape(-1, 1, 1)
phi = euler[:, 1].reshape(-1, 1, 1)
psi = euler[:, 2].reshape(-1, 1, 1)
ones = torch.ones((batch_size, 1, 1), dtype=torch.float32, device=euler.device)
zero = torch.zeros((batch_size, 1, 1), dtype=torch.float32, device=euler.device)
rot_x = torch.cat(( # (nbatch, 3, 3)
torch.cat((ones, zero, zero), 1), #(nbatch, 3, 1)
torch.cat((zero, theta.cos(), theta.sin()), 1), #(nbatch, 3, 1)
torch.cat((zero, -theta.sin(), theta.cos()), 1), #(nbatch, 3, 1)
), 2)
rot_y = torch.cat((
torch.cat((phi.cos(), zero, -phi.sin()), 1),
torch.cat((zero, ones, zero), 1),
torch.cat((phi.sin(), zero, phi.cos()), 1),
), 2)
rot_z = torch.cat((
torch.cat((psi.cos(), -psi.sin(), zero), 1),
torch.cat((psi.sin(), psi.cos(), zero), 1),
torch.cat((zero, zero, ones), 1)
), 2)
rot = torch.bmm(rot_x, torch.bmm(rot_y, rot_z)) # (nbatch, 3, 3)
return rot
def geo_rotation_transfrom(geo, rot, trans=None):
""" rotation geometry and trans
params:
geo: geometry, torch.Tensor, (nbatch, N, 3)
rot: rotation matrix, torch.Tensor, (nbatch, 3, 3)
trans: transform matrix, torch.Tensor, (nbtach, 3)
return:
geometry, torch.Tensor, (nbatch, N, 3)
"""
# rotation
geo = torch.bmm(rot, geo.permute(0, 2, 1)) # (nbatch, 3, N)
# transform
if trans is not None:
geo += trans.view(-1, 3, 1)
geo = geo.permute(0, 2, 1)
return geo
def geo_projection(geo, param_camera):
"""project geo to 2D plane
params:
geo, geometry, torch.Tensor, (nbatch, N, 3)
param_camera: torch.Tensor, (nbatch, 4)
return:
geometry, torch.Tensor, (nbatch, N, 3)
"""
fx, fy = param_camera[:, 0], param_camera[:, 1] # (nbatch, )
cx, cy = param_camera[:, 2], param_camera[:, 3] # (nbatch, )
X, Y, Z = geo[:, :, 0], geo[:, :, 1], geo[:, :, 2] # (nbatch, N)
fxX = fx[:, None] * X # (nbatch, N)
fyY = fy[:, None] * Y # (nbatch, N)
proj_x = -fxX / Z + cx[:, None] # (nbatch, N)
proj_y = fyY / Z + cy[:, None]
geo_pro = torch.cat([proj_x, proj_y, Z], 2)
return geo_pro
def landmark_projection(geo, ldmk_info, ldmk_num=68):
"""Landmark Projection
params:
geo, geometry, torch.Tensor, (nbatch, N, 3)
ldmk_info, torch.Tensor, (68,)
ldmk_num, int, the number of landmarks, default=68
return:
projection landmark, (nbatch, 68, 2)
"""
n_points = geo.shape[0]
rot_tri_normal = compute_tri_normal(geo_rot, self.tris)
rot_ver_normal = torch.index_select(rot_tri_normal, 1, self.vert_tris)
is_visible = -torch.bmm(rot_ver_normal.reshape(-1, 1, 3), geo_rot.reshape(-1, 3, 1))
is_visible = is_visible.reshape(-1, n_points)
ldmk_idx = render_util.update_contour(ldmk_info, is_visible, ldmk_num)
print(f"DEBUG: landmark projection, ldmk_num={ldmk_num}, update contour, ldmk_idx len={ldmk_idx.shape}, should be (Nbatch * 68)")
ldmk_pro = torch.index_select(geo.reshape(-1, 3), 0, ldmk_idx) # (len(ldmk_idx), 3)
ldmk_pro = ldmk_pro[:, :2].reshape(-1, ldmk_num, 2) # (nbatch, ldmk_num, 2)
return ldmk_pro
-41
View File
@@ -1,41 +0,0 @@
import os
import torch
import numpy as np
from PIL import Image
def tensor2im(input_image, imtype=np.uint8):
""""Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input image tensor array
imtype (type) -- the desired type of the converted numpy array
"""
if not isinstance(input_image, np.ndarray):
if isinstance(input_image, torch.Tensor): # get the data from a variable
image_tensor = input_image.data
else:
return input_image
image_numpy = image_tensor[0].cpu().float().numpy() # convert it into a numpy array
if image_numpy.shape[0] == 1: # grayscale to RGB
image_numpy = np.tile(image_numpy, (3, 1, 1))
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 # post-processing: tranpose and scaling
else: # if it is a numpy array, do nothing
image_numpy = input_image
return image_numpy.astype(imtype)
def save_image(image_numpy, image_path):
"""Save a numpy image to the disk
Parameters:
image_numpy (numpy array) -- input numpy array
image_path (str) -- the path of the image
"""
image_pil = Image.fromarray(image_numpy)
image_pil.save(image_path)
-254
View File
@@ -1,254 +0,0 @@
import os
import cv2
import torch
import numpy as np
from pathlib import Path
from matplotlib import pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'
def landmark_normalize(ldmk):
# ldmk shape = (68, 2)
pos_mean = np.mean(ldmk, axis=0) # (2, )
pos_max = np.max(ldmk, axis=0) # (2, )
pos_min = np.min(ldmk, axis=0) # (2, )
side = int(1.5 * np.max(pos_max - pos_min)) # (1, )
# print(f"landmarks = {ldmk[::10, :]}, \n mean={pos_mean}, max={pos_max}, min={pos_min}, side={side}")
tran = pos_mean - 0.5 * side # (2, )
ldmk_tran = ldmk - tran[np.newaxis, :] # (68, 2)
ldmk_norm = ldmk_tran / side # (68, 2)
# print(f"ldmk_tran = {ldmk_tran[::10, :]}, \n ldmk_tran = {ldmk_norm[::10, :]}")
return ldmk_norm, pos_mean, side
def landmark_normalize_by_param(ldmk, params):
# ldmk shape = (B, 68, 2)
# params shape = (B, 3)
pos_mean = params[:, 0:2 ] # (B, 2)
pos_mean = pos_mean[:, np.newaxis, :] # (B, 1, 2)
side = params[:, 2:] # (B, 2)
side = side[:, np.newaxis, :] # (B, 1, 2)
tran = pos_mean - 0.5 * side # (B, 1, 2)
ldmk_norm = (ldmk - tran) / side # (B, 68, 2)
return ldmk_norm
def landmark_to_images(ldmks, w=256, h=256, dpi=100, norm=True, prex=""):
# landmarks shape = (nbatch, 68, 2)
nframe = ldmks.shape[0]
v_images = []
for i in range(nframe):
ildmk = ldmks[i, :, :]
if prex is not None:
text = f"{prex}-frame-{i:04d}"
else:
text = None
v_images.append(landmark_to_image(ildmk, w, h, dpi, norm, text))
return np.asarray(v_images)
def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None):
# landmarks shape = (68, 2)
if norm:
ildmk[:, 0] = w - ildmk[:, 0] * w
ildmk[:, 1] = h - ildmk[:, 1] * h
else:
# ildmk[:, 0] = w - ildmk[:, 0]
ildmk[:, 1] = h - ildmk[:, 1]
if isinstance(ildmk, torch.Tensor):
ildmk = ildmk.cpu().numpy()
# plot
fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi)
fig.patch.set_facecolor('w')
ax = fig.add_subplot(1,1,1)
# ax.imshow(np.zeros(shape=(w, h)))
ax.set_facecolor('m')
# plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
# ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1)
ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1)
ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1)
ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1)
ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1)
ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1)
ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1)
ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1)
#chin
ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1)
#left and right eyebrow
ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
#nose
ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
#left and right eye
ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
#outer and inner lip
ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
ax.set_xlim(0, w)
ax.set_ylim(0, h)
ax.axis('off')
if text is not None:
ax.text(2, 2, text)
fig.canvas.draw()
w, h = fig.canvas.get_width_height()
buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
buffer = buffer.reshape((h, w, 3))
image = np.asarray(buffer)
# print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}")
plt.close(fig)
return image
# def landmark_to_image(ildmk, w=256, h=256, dpi=100, norm=True, text=None):
# # landmarks shape = (68, 2)
# if norm:
# ildmk = w - ildmk * w
# else:
# ildmk[:, 1] = h - ildmk[:, 1]
# if isinstance(ildmk, torch.Tensor):
# ildmk = ildmk.cpu().numpy()
# # plot
# fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi)
# fig.patch.set_facecolor('w')
# ax = fig.add_subplot(1,1,1)
# # ax.imshow(np.zeros(shape=(w, h)))
# ax.set_facecolor('m')
# # plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
# # ax.scatter(ildmk[:, 0], ildmk[:, 1], marker='o', s=5, color="#808080",alpha=1)
# ax.scatter(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='o', s=3, color="#008B8B",alpha=1)
# ax.scatter(ildmk[17:22,0], ildmk[17:22,1], marker='o', s=3, color="#F4A460",alpha=1)
# ax.scatter(ildmk[22:27,0], ildmk[22:27,1], marker='o', s=3, color="#F4A460",alpha=1)
# ax.scatter(ildmk[27:36,0], ildmk[27:36,1], marker='o', s=3, color="blue",alpha=1)
# ax.scatter(ildmk[36:48,0], ildmk[36:48,1], marker='o', s=3, color="#DC143C",alpha=1)
# ax.scatter(ildmk[48:60,0], ildmk[48:60,1], marker='o', s=3, color="#DC143C",alpha=1)
# ax.scatter(ildmk[60:68,0], ildmk[60:68,1], marker='o', s=3, color="#FF1493",alpha=1)
# #chin
# ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='#008B8B', lw=2, alpha=1)
# #left and right eyebrow
# ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
# ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='#F4A460', lw=2, alpha=1)
# #nose
# ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
# ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2, alpha=1)
# #left and right eye
# ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
# ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
# ax.plot(ildmk[[41,36],0], ildmk[[41,36],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
# ax.plot(ildmk[[47,42],0], ildmk[[47,42],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
# #outer and inner lip
# ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
# ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
# ax.plot(ildmk[[59,48],0], ildmk[[59,48],1], marker='', markersize=1, linestyle='-', color='#DC143C', lw=2, alpha=1)
# ax.plot(ildmk[[67,60],0], ildmk[[67,60],1], marker='', markersize=1, linestyle='-', color='#FF1493', lw=2, alpha=1)
# ax.set_xlim(0, w)
# ax.set_ylim(0, h)
# ax.axis('off')
# if text is not None:
# ax.text(10, 10, text)
# fig.canvas.draw()
# w, h = fig.canvas.get_width_height()
# buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
# buffer = buffer.reshape((h, w, 3))
# image = np.asarray(buffer)
# # print(f"w,h={w},{h}, buffer shape = {buffer.shape}, dtype = {buffer.dtype}, class = {(buffer)}")
# plt.close(fig)
# return image
def landmark_to_mask(ildmk, w=256, h=256, dpi=100, norm=True):
# landmarks shape = (68, 2)
# print(f"landmark data shape = {ildmk.shape}")
if norm:
ildmk = ildmk * w
# plot
fig = plt.figure(figsize=(h/dpi, w/dpi), dpi=dpi)
ax = fig.add_subplot(1,1,1)
# ax.imshow(np.ones(shape=(w, h)))
# plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
#chin
ax.plot(ildmk[ 0:17,0], ildmk[ 0:17,1], marker='', markersize=1, linestyle='-', color='green', lw=2)
#left and right eyebrow
ax.plot(ildmk[17:22,0], ildmk[17:22,1], marker='', markersize=1, linestyle='-', color='orange', lw=2)
ax.plot(ildmk[22:27,0], ildmk[22:27,1], marker='', markersize=1, linestyle='-', color='orange', lw=2)
#nose
ax.plot(ildmk[27:31,0], ildmk[27:31,1], marker='', markersize=1, linestyle='-', color='blue', lw=2)
ax.plot(ildmk[31:36,0], ildmk[31:36,1], marker='', markersize=1, linestyle='-', color='blue', lw=2)
#left and right eye
ax.plot(ildmk[36:42,0], ildmk[36:42,1], marker='', markersize=1, linestyle='-', color='red', lw=2)
ax.plot(ildmk[42:48,0], ildmk[42:48,1], marker='', markersize=1, linestyle='-', color='red', lw=2)
#outer and inner lip
ax.plot(ildmk[48:60,0], ildmk[48:60,1], marker='', markersize=1, linestyle='-', color='purple', lw=2)
ax.plot(ildmk[60:68,0], ildmk[60:68,1], marker='', markersize=1, linestyle='-', color='pink', lw=2)
ax.axis('off')
fig.canvas.draw()
buffer = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
# buffer.shape = (w, h, 4)
image = buffer.reshape(fig.canvas.get_width_height()[::-1] + (3,))
plt.close(fig)
return image
-89
View File
@@ -1,89 +0,0 @@
import os
import sys
import shutil
import logging
from logging import INFO, ERROR, DEBUG, CRITICAL, FATAL, WARNING, WARN, NOTSET
import datetime
from pathlib import Path
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#The background is set with 40 plus the number of the color, and the foreground with 30
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': RED,
'ERROR': RED
}
class Logger(logging.Logger):
def __init__(self, path_output, path_config=None, postfix=None, level=logging.NOTSET ):
logging.Logger.__init__(self, '', level)
# logger filename suffix
suffix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}"
if postfix is not None:
suffix += str("-" + postfix)
# make dir & set filename
if path_config is not None:
basename = path_config.name.split(".")[0]
self.path_output = Path(path_output).joinpath(basename, suffix)
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(suffix + ".log")
# add file hander
fHander = logging.FileHandler(filename)
fFormat = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
fHander.setFormatter(fFormat)
self.addHandler(fHander)
# add console hander
cHander = logging.StreamHandler(sys.stdout)
cFormat = ColoredFormatter( RESET_SEQ+"[%(asctime)s] %(message)s"+RESET_SEQ )
cHander.setFormatter(cFormat)
self.addHandler(cHander)
def setContext(self, key, value):
self.context[key] = value
def log(self, msg, level, *args, **kwargs):
extra = kwargs
extra.update(self.context)
# super(Logger, self).info(msg)
def error(self, msg, *args, **kwargs):
super(Logger, self).error(msg, *args, **kwargs)
def exception(self, *args, **kwargs):
e = sys.exc_info()
extra = kwargs
extra.update(self.context)
super(Logger, self).error(e[1].message)
class ColoredFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg, datefmt='%Y-%m-%d %H:%M:%S')
self.use_color = use_color
def format(self, record):
levelname = record.levelname
if self.use_color and levelname in COLORS:
levelname_color = COLOR_SEQ % (30+COLORS[levelname]) + levelname + RESET_SEQ
record.levelname = levelname_color
return logging.Formatter.format(self, record)
-39
View File
@@ -1,39 +0,0 @@
import numpy as np
from scipy import interpolate
def resample_by_nsteps(feat, nsteps_tgt):
"""
feat, (nframes, ... ) (with source_fps)
"""
nsteps_src = feat.shape[0]
data_idx = np.arange(0, nsteps_src, 1)
samp_idx = np.arange(0, nsteps_src-1, (nsteps_src - 1) / nsteps_tgt)
# print(f"data_idx = {list(data_idx)} \nsmap_idx = {list(samp_idx)}")
# sample function
func = interpolate.interp1d(data_idx, y=feat, axis=0)
data_interpolate = func(samp_idx)
return data_interpolate
def convert_fps(data, source_fps = 30, target_fps=25):
"""
data, (nframes, ... ) (with source_fps)
"""
nsize = data.shape[0]
data_idx = np.arange(0, nsize, 1)
samp_idx = np.arange(0, nsize-1, 1.0*source_fps/target_fps)
func = interpolate.interp1d(data_idx, data=data, axis=0)
data_interpolate = func(samp_idx)
if source_fps < target_fps:
data_interpolate = np.concatenate([data_interpolate, data[-1:]])
return data_interpolate
# def
-516
View File
@@ -1,516 +0,0 @@
import cv2
import numpy as np
import landmarks.lmconfig as lmcfg
from csl_common.utils.nn import to_numpy, to_image
from csl_common.vis import vis
import matplotlib.pyplot as plt
from skimage.metrics import structural_similarity as compare_ssim
import torch
import warnings
layers = []
outline = range(0, 17)
eyebrow_l = range(17, 22)
eyebrow_r = range(22, 27)
nose = range(27, 31)
nostrils = range(31, 36)
eye_l = range(36, 42)
eye_r = range(42, 48)
mouth = range(48, 68)
components = [outline, eyebrow_l, eyebrow_r, nose, nostrils, eye_l, eye_r, mouth]
new_layers = []
for idx in range(20):
lm_ids = []
for comp in components[1:]:
if len(comp) > idx:
lm = comp[idx]
lm_ids.append(lm)
new_layers.append(lm_ids)
outline_layers = [[lm] for lm in range(17)]
layers = components + new_layers + outline_layers
hm_code_mat = np.zeros((len(layers), 68), dtype=bool)
for l, lm_ids in enumerate(layers):
hm_code_mat[l, lm_ids] = True
def generate_colors(n, r, g, b, dim):
ret = []
step = [0,0,0]
step[dim] = 256 / n
for i in range(n):
r += step[0]
g += step[1]
b += step[2]
r = int(r) % 256
g = int(g) % 256
b = int(b) % 256
ret.append((r,g,b))
return ret
_colors = generate_colors(17, 220, 0, 0, 2) + \
generate_colors(10, 0, 240, 0, 0) + \
generate_colors(9, 0, 0, 230, 1) + \
generate_colors(12, 100, 255, 0, 2) + \
generate_colors(20, 150, 0, 255, 2)
# lmcolors = np.array(_colors)
np.random.seed(0)
lmcolors = np.random.randint(0,255,size=(68,3))
lmcolors = lmcolors / lmcolors.sum(axis=1).reshape(-1,1)*255
def gaussian(x, mean, sigma):
return 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x-mean)**2 / (2 * sigma**2))
def make_landmark_template(wnd_size, sigma):
X, Y = np.mgrid[-wnd_size//2:wnd_size//2, -wnd_size//2:wnd_size//2]
Z = np.sqrt(X**2 + Y**2)
N = gaussian(Z, 0, sigma)
# return (N/N.max())**2 # square to make sharper
return N / N.max()
def _fill_heatmap_layer(dst, lms, lm_id, lm_heatmap_window, wnd_size):
posx, posy = min(lms[lm_id,0], lmcfg.HEATMAP_SIZE-1), min(lms[lm_id,1], lmcfg.HEATMAP_SIZE-1)
img_size = lmcfg.HEATMAP_SIZE
l = int(posx - wnd_size/2)
t = int(posy - wnd_size/2)
r = l + wnd_size
b = t + wnd_size
src_l = max(0, -l)
src_t = max(0, -t)
src_r = min(wnd_size, wnd_size-(r-img_size))
src_b = min(wnd_size, wnd_size-(b-img_size))
try:
cn = lm_id
wnd = lm_heatmap_window[src_t:src_b, src_l:src_r]
weight = 1.0
dst[cn, max(0,t):min(img_size, b), max(0,l):min(img_size, r)] = np.maximum(
dst[cn, max(0,t):min(img_size, b), max(0,l):min(img_size, r)], wnd*weight)
except:
pass
def __get_code_mat(num_landmarks):
def to_binary(n, ndigits):
bits = np.array([bool(int(x)) for x in bin(n)[2:]])
assert len(bits) <= ndigits
zero_pad_bits = np.zeros(ndigits, dtype=bool)
zero_pad_bits[-len(bits):] = bits
return zero_pad_bits
n_enc_layers = int(np.ceil(np.log2(num_landmarks)))
# get binary code for each heatmap id
codes = [to_binary(i+1, ndigits=n_enc_layers) for i in range(num_landmarks)]
return np.vstack(codes)
def convert_to_encoded_heatmaps(hms):
def merge_layers(hms):
hms = hms.max(axis=0)
return hms/hms.max()
num_landmarks = len(hms)
n_enc_layers = len(hm_code_mat)
# create compressed heatmaps by merging layers according to transpose of binary code mat
encoded_hms = np.zeros((n_enc_layers, hms.shape[1], hms.shape[2]))
for l in range(n_enc_layers):
selected_layer_ids = hm_code_mat[l,:]
encoded_hms[l] = merge_layers(hms[selected_layer_ids].copy())
decode_heatmaps(encoded_hms)
return encoded_hms
def convert_to_hamming_encoded_heatmaps(hms):
def merge_layers(hms):
hms = hms.max(axis=0)
return hms/hms.max()
num_landmarks = len(hms)
n_enc_layers = int(np.ceil(np.log2(num_landmarks)))
code_mat = __get_code_mat(num_landmarks)
# create compressed heatmaps by merging layers according to transpose of binary code mat
encoded_hms = np.zeros((n_enc_layers, hms.shape[1], hms.shape[2]))
for l in range(n_enc_layers):
selected_layer_ids = code_mat[:, l]
encoded_hms[l] = merge_layers(hms[selected_layer_ids].copy())
# decode_heatmaps(encoded_hms)
return encoded_hms
def decode_heatmaps(hms):
import cv2
def get_decoded_heatmaps_for_layer(hms, lm):
show = False
enc_layer_ids = code_mat[:, lm]
heatmap = np.ones_like(hms[0])
for i in range(len(enc_layer_ids)):
pos = enc_layer_ids[i]
layer = hms[i]
if pos:
if show:
fig, ax = plt.subplots(1,4)
print(i, pos)
ax[0].imshow(heatmap, vmin=0, vmax=1)
ax[1].imshow(layer, vmin=0, vmax=1)
# mask = layer.copy()
# mask[mask < 0.1] = 0
# heatmap *= mask
heatmap *= layer
if show:
# ax[2].imshow(mask, vmin=0, vmax=1)
ax[3].imshow(heatmap, vmin=0, vmax=1)
return heatmap
num_landmarks = 68
# get binary code for each heatmap id
code_mat = hm_code_mat
decoded_hms = np.zeros((num_landmarks, hms.shape[1], hms.shape[1]))
show = False
if show:
fig, ax = plt.subplots(1)
ax.imshow(code_mat)
fig_dec, ax_dec = plt.subplots(7, 10)
fig, ax = plt.subplots(5,9)
for i in range(len(hms)):
ax[i//9, i%9].imshow(hms[i])
lms = np.zeros((68,2), dtype=int)
# lmid_to_show = 16
for lm in range(0,68):
heatmap = get_decoded_heatmaps_for_layer(hms, lm)
decoded_hms[lm] = heatmap
heatmap = cv2.blur(heatmap, (5, 5))
lms[lm, :] = np.unravel_index(np.argmax(heatmap, axis=None), heatmap.shape)[::-1]
if show:
ax_dec[lm//10, lm%10].imshow(heatmap)
if show:
plt.show()
return decoded_hms, lms
def create_landmark_heatmaps(lms, sigma, landmarks_to_use, heatmap_size):
lm_wnd_size = int(sigma * 5)
lm_heatmap_window = make_landmark_template(lm_wnd_size, sigma)
nchannels = len(landmarks_to_use)
hms = np.zeros((nchannels, heatmap_size, heatmap_size))
for l in landmarks_to_use:
wnd = lm_heatmap_window
_fill_heatmap_layer(hms, lms, l, wnd, lm_wnd_size)
if lmcfg.LANDMARK_TARGET == 'single_channel':
hms = hms.max(axis=0)
hms /= hms.max()
return hms.astype(np.float32)
def calc_landmark_nme_per_img(gt_lms, pred_lms, ocular_norm='pupil', landmarks_to_eval=None, image_size=None):
norm_dists = calc_landmark_nme(gt_lms, pred_lms, ocular_norm, image_size=image_size)
if landmarks_to_eval is None:
landmarks_to_eval = range(norm_dists.shape[1])
return np.mean(np.array([norm_dists[:,l] for l in landmarks_to_eval]).T, axis=1)
def get_pupil_dists(lms):
assert lms.shape[2] == 68
ocular_dists_inner = np.sqrt(np.sum((lms[:, 42] - lms[:, 39])**2, axis=1))
ocular_dists_outer = np.sqrt(np.sum((lms[:, 45] - lms[:, 36])**2, axis=1))
return np.vstack((ocular_dists_inner, ocular_dists_outer)).mean(axis=0)
def get_landmark_confs(X_lm_hm):
return np.clip(to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2), a_min=0, a_max=1)
def calc_landmark_nme(gt_lms, pred_lms, ocular_norm='pupil', image_size=None):
def reformat(lms):
lms = to_numpy(lms)
if len(lms.shape) == 2:
lms = lms.reshape((1,-1,2))
return lms
gt = reformat(gt_lms)
pred = reformat(pred_lms)
assert(len(gt.shape) == 3)
assert(len(pred.shape) == 3)
if gt.shape[1] == 5: # VGGFace2
ocular_dists = np.sqrt(np.sum((gt[:, 1] - gt[:, 0])**2, axis=1))
elif gt.shape[1] == 19: # AFLW
assert image_size is not None
ocular_dists = np.ones(gt.shape[0], dtype=np.float32) * image_size
elif gt.shape[1] == 98: # WFLW
ocular_dists = np.sqrt(np.sum((gt[:, 72] - gt[:, 60])**2, axis=1))
elif gt.shape[1] == 68: # 300-W
if ocular_norm == 'pupil':
ocular_dists = get_pupil_dists(gt)
elif ocular_norm == 'outer':
ocular_dists = np.sqrt(np.sum((gt[:, 45] - gt[:, 36])**2, axis=1))
elif ocular_norm is None or ocular_norm == 'none':
ocular_dists = np.ones((len(gt),1)) * 100.0
else:
raise ValueError("Ocular norm {} not defined!".format(ocular_norm))
else:
assert image_size is not None
ocular_dists = np.ones(gt.shape[0], dtype=np.float32) * image_size
norm_dists = np.sqrt(np.sum((gt - pred)**2, axis=2)) / ocular_dists.reshape(len(gt), 1)
return norm_dists * 100
def calc_landmark_failure_rate(nmes, th=10.0):
img_nmes = nmes.mean(axis=1)
assert len(img_nmes) == len(nmes)
return np.count_nonzero(img_nmes > th) / len(img_nmes.ravel())
def calc_landmark_ncc(X, X_recon, lms):
input_images = vis.to_disp_images(X, denorm=True)
recon_images = vis.to_disp_images(X_recon, denorm=True)
nimgs = len(input_images)
nlms = len(lms[0])
wnd_size = (X_recon.shape[-1] // 16) - 1
nccs = np.zeros((nimgs, nlms), dtype=np.float32)
img_shape = input_images[0].shape
for i in range(nimgs):
for lid in range(nlms):
x = int(lms[i, lid, 0])
y = int(lms[i, lid, 1])
t = max(0, y-wnd_size//2)
b = min(img_shape[0]-1, y+wnd_size//2)
l = max(0, x-wnd_size//2)
r = min(img_shape[1]-1, x+wnd_size//2)
wnd1 = input_images[i][t:b, l:r]
wnd2 = recon_images[i][t:b, l:r]
ncc = ((wnd1-wnd1.mean()) * (wnd2-wnd2.mean())).mean() / (wnd1.std() * wnd2.std())
nccs[i, lid] = ncc
return np.clip(np.nan_to_num(nccs), a_min=-1, a_max=1)
def calc_landmark_ssim_score(X, X_recon, lms, wnd_size=None):
if wnd_size is None:
wnd_size = (X_recon.shape[-1] // 16) - 1
input_images = vis.to_disp_images(X, denorm=True)
recon_images = vis.to_disp_images(X_recon, denorm=True)
data_range = 255.0 if input_images[0].dtype == np.uint8 else 1.0
nimgs = len(input_images)
nlms = len(lms[0])
scores = np.zeros((nimgs, nlms), dtype=np.float32)
for i in range(nimgs):
S = compare_ssim(input_images[i], recon_images[i], data_range=data_range, multichannel=True, full=True)[1]
S = S.mean(axis=2)
for lid in range(nlms):
x = int(lms[i, lid, 0])
y = int(lms[i, lid, 1])
t = max(0, y-wnd_size//2)
b = min(S.shape[0]-1, y+wnd_size//2)
l = max(0, x-wnd_size//2)
r = min(S.shape[1]-1, x+wnd_size//2)
wnd = S[t:b, l:r]
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
scores[i, lid] = wnd.mean()
return np.nan_to_num(scores)
def calc_landmark_cs_error(X, X_recon, lms, torch_ssim, training=False, wnd_size=None):
if wnd_size is None:
wnd_size = (X_recon.shape[-1] // 16) - 1
nimgs = len(X)
nlms = len(lms[0])
input_size = X.shape[-1]
errs = torch.zeros((nimgs, nlms), requires_grad=training).cuda()
for i in range(len(X)):
torch_ssim(X[i].unsqueeze(0), X_recon[i].unsqueeze(0))
cs_map = torch_ssim.cs_map[0].mean(dim=0)
map_size = cs_map.shape[0]
margin = (input_size - map_size) // 2
S = torch.zeros((input_size, input_size), requires_grad=training).cuda()
S[margin:-margin, margin:-margin] = cs_map
for lid in range(nlms):
x = int(lms[i, lid, 0])
y = int(lms[i, lid, 1])
t = max(0, y-wnd_size//2)
b = min(S.shape[0]-1, y+wnd_size//2)
l = max(0, x-wnd_size//2)
r = min(S.shape[1]-1, x+wnd_size//2)
wnd = S[t:b, l:r]
errs[i, lid] = 1 - wnd.mean()
return errs
def calc_landmark_recon_error(X, X_recon, lms, return_maps=False, reduction='mean'):
assert len(X.shape) == 4
assert reduction in ['mean', 'none']
X = to_numpy(X)
X_recon = to_numpy(X_recon)
mask = np.zeros((X.shape[0], X.shape[2], X.shape[3]), dtype=np.float32)
input_size = X.shape[-1]
radius = input_size * 0.05
for img_id in range(len(mask)):
for lm in lms[img_id]:
cv2.circle(mask[img_id], (int(lm[0]), int(lm[1])), radius=int(radius), color=1, thickness=-1)
err_maps = np.abs(X - X_recon).mean(axis=1) * 255.0
masked_err_maps = err_maps * mask
debug = False
if debug:
fig, ax = plt.subplots(1,3)
ax[0].imshow(vis.to_disp_image((X * mask[:,np.newaxis,:,:].repeat(3, axis=1))[0], denorm=True))
ax[1].imshow(vis.to_disp_image((X_recon * mask[:,np.newaxis,:,:].repeat(3, axis=1))[0], denorm=True))
ax[2].imshow(masked_err_maps[0])
plt.show()
if reduction == 'mean':
err = masked_err_maps.sum() / (mask.sum() * 3)
else:
# err = masked_err_maps.mean(axis=2).mean(axis=1)
err = masked_err_maps.sum(axis=2).sum(axis=1) / (mask.reshape(len(mask), -1).sum(axis=1) * 3)
if return_maps:
return err, masked_err_maps
else:
return err
def to_single_channel_heatmap(lm_heatmaps):
if lmcfg.LANDMARK_TARGET == 'colored':
mc = [to_image(lm_heatmaps[0])]
elif lmcfg.LANDMARK_TARGET == 'single_channel':
mc = [to_image(lm_heatmaps[0, 0])]
else:
mc = to_image(lm_heatmaps.max(axis=1))
return mc
LM68_TO_LM96 = 1
LM98_TO_LM68 = 2
LM68_TO_LM5 = 3
def convert_landmarks(lms, code):
cvt_func = {
LM98_TO_LM68: lm98_to_lm68,
LM68_TO_LM5: lm68_to_lm5,
}
if len(lms.shape) == 3:
# new_lms = []
new_lms = torch.zeros((len(lms), 5, 2), requires_grad=True, dtype=torch.float32).cuda()
for i in range(len(lms)):
# new_lms.append(cvt_func[code](lms[i]))
# new_lms[i] += cvt_func[code](lms[i])
cvt_func[code](lms[i], new_lms[i])
# new_lms = torch.stack(new_lms)
# new_lms = np.array(new_lms)
return new_lms
elif len(lms.shape) == 2:
return cvt_func[code](lms)
else:
raise ValueError
def lm68_to_lm5(lm68, lm5):
# lm5 = np.zeros((len(lm68), 5, 2), dtype=np.float32)
# lm5 = torch.zeros((5, 2), requires_grad=True, dtype=torch.float32)
lm5[0] += (lm68[36] + lm68[39]) / 2
lm5[1] += (lm68[42] + lm68[45]) / 2
lm5[2] += lm68[30]
lm5[3] += lm68[48]
lm5[4] += lm68[54]
# return lm5
def lm98_to_lm68(lm98):
def copy_lms(offset68, offset98, n):
lm68[range(offset68, offset68+n)] = lm98[range(offset98, offset98+n)]
assert len(lm98) == 98, "Cannot convert landmarks to 68 points!"
lm68 = np.zeros((68,2), dtype=np.float32)
# outline
lm68[range(17)] = lm98[range(0,33,2)]
# left eyebrow
copy_lms(17, 33, 5)
# right eyebrow
copy_lms(22, 42, 5)
# nose
copy_lms(27, 51, 9)
# eye left
lm68[36] = lm98[60]
lm68[37] = lm98[61]
lm68[38] = lm98[63]
lm68[39] = lm98[64]
lm68[40] = lm98[65]
lm68[41] = lm98[67]
# eye right
lm68[36+6] = lm98[60+8]
lm68[37+6] = lm98[61+8]
lm68[38+6] = lm98[63+8]
lm68[39+6] = lm98[64+8]
lm68[40+6] = lm98[65+8]
lm68[41+6] = lm98[67+8]
copy_lms(48, 76, 20)
return lm68
def is_good_landmark(confs, rec_errs=None):
if rec_errs is not None:
low_errors = rec_errs < 0.25
confs *= np.array(low_errors).astype(int)
return confs > 0.8
def smooth_heatmaps(hms):
assert(len(hms.shape) == 4)
hms = to_numpy(hms)
for i in range(hms.shape[0]):
for l in range(hms.shape[1]):
hms[i,l] = cv2.blur(hms[i,l], (9,9), borderType=cv2.BORDER_CONSTANT)
# hms[i,l] = cv2.GaussianBlur(hms[i,l], (9,9), sigmaX=9, borderType=cv2.BORDER_CONSTANT)
return hms
def heatmaps_to_landmarks(hms, target_size):
def landmark_id_to_heatmap_id(lm_id):
return {lm: i for i,lm in enumerate(range(num_landmarks))}[lm_id]
assert len(hms.shape) == 4
num_images = hms.shape[0]
num_landmarks = hms.shape[1]
heatmap_size = hms.shape[-1]
lms = np.zeros((num_images, num_landmarks, 2), dtype=int)
if hms.shape[1] > 3:
# print(hms.max())
for i in range(len(hms)):
heatmaps = to_numpy(hms[i])
for l in range(len(heatmaps)):
hm = heatmaps[landmark_id_to_heatmap_id(l)]
lms[i, l, :] = np.unravel_index(np.argmax(hm, axis=None), hm.shape)[::-1]
lm_scale = heatmap_size / target_size
return lms / lm_scale
-313
View File
@@ -1,313 +0,0 @@
import cv2
import numpy as np
import torch
from matplotlib import pyplot as plt
from skimage.metrics import structural_similarity as compare_ssim
from common.utils import nn as nn
from common.utils.nn import to_numpy
from common import vis
from landmarks.lmutils import calc_landmark_nme, calc_landmark_ssim_score, to_single_channel_heatmap, \
calc_landmark_nme_per_img, smooth_heatmaps
def show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1.0):
vmax = 1.0
rows_heatmaps = []
if gt_heatmaps is not None:
vmax = gt_heatmaps.max()
if len(gt_heatmaps[0].shape) == 2:
gt_heatmaps = [vis.color_map(hm, vmin=0, vmax=vmax, cmap=plt.cm.jet) for hm in gt_heatmaps]
nCols = 1 if len(gt_heatmaps) == 1 else nimgs
rows_heatmaps.append(cv2.resize(vis.make_grid(gt_heatmaps, nCols=nCols, padval=0), None, fx=f, fy=f))
disp_pred_heatmaps = pred_heatmaps
if len(pred_heatmaps[0].shape) == 2:
disp_pred_heatmaps = [vis.color_map(hm, vmin=0, vmax=vmax, cmap=plt.cm.jet) for hm in pred_heatmaps]
nCols = 1 if len(pred_heatmaps) == 1 else nimgs
rows_heatmaps.append(cv2.resize(vis.make_grid(disp_pred_heatmaps, nCols=nCols, padval=0), None, fx=f, fy=f))
cv2.imshow('Landmark heatmaps', cv2.cvtColor(np.vstack(rows_heatmaps), cv2.COLOR_RGB2BGR))
def visualize_batch(images, landmarks, X_recon, X_lm_hm, lm_preds_max,
lm_heatmaps=None, target_images=None, lm_preds_cnn=None, ds=None, wait=0, ssim_maps=None,
landmarks_to_draw=None, ocular_norm='outer', horizontal=False, f=1.0,
overlay_heatmaps_input=False, overlay_heatmaps_recon=False, clean=False,
landmarks_only_outline=range(17), landmarks_no_outline=range(17,68)):
gt_color = (0,255,0)
pred_color = (0,0,255)
image_size = images.shape[3]
assert image_size in [128, 256]
nimgs = min(10, len(images))
images = nn.atleast4d(images)[:nimgs]
num_landmarks = lm_preds_max.shape[1]
if landmarks_to_draw is None:
landmarks_to_draw = range(num_landmarks)
nme_per_lm = None
if landmarks is None:
# print('num landmarks', lmcfg.NUM_LANDMARKS)
lm_gt = np.zeros((nimgs, num_landmarks, 2))
else:
lm_gt = nn.atleast3d(to_numpy(landmarks))[:nimgs]
nme_per_lm = calc_landmark_nme(lm_gt, lm_preds_max[:nimgs], ocular_norm=ocular_norm, image_size=image_size)
lm_ssim_errs = 1 - calc_landmark_ssim_score(images, X_recon[:nimgs], lm_gt)
lm_confs = None
# show landmark heatmaps
pred_heatmaps = None
if X_lm_hm is not None:
pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm[:nimgs]))
pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in pred_heatmaps]
gt_heatmaps = None
if lm_heatmaps is not None:
gt_heatmaps = to_single_channel_heatmap(to_numpy(lm_heatmaps[:nimgs]))
gt_heatmaps = np.array([cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in gt_heatmaps])
show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1)
lm_confs = to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2)
# resize images for display and scale landmarks accordingly
lm_preds_max = lm_preds_max[:nimgs] * f
if lm_preds_cnn is not None:
lm_preds_cnn = lm_preds_cnn[:nimgs] * f
lm_gt *= f
input_images = vis.to_disp_images(images[:nimgs], denorm=True)
if target_images is not None:
disp_images = vis.to_disp_images(target_images[:nimgs], denorm=True)
else:
disp_images = vis.to_disp_images(images[:nimgs], denorm=True)
disp_images = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images]
recon_images = vis.to_disp_images(X_recon[:nimgs], denorm=True)
disp_X_recon = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
# overlay landmarks on input images
if pred_heatmaps is not None and overlay_heatmaps_input:
disp_images = [vis.overlay_heatmap(disp_images[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))]
if pred_heatmaps is not None and overlay_heatmaps_recon:
disp_X_recon = [vis.overlay_heatmap(disp_X_recon[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))]
#
# Show input images
#
disp_images = vis.add_landmarks_to_images(disp_images, lm_gt[:nimgs], color=gt_color)
disp_images = vis.add_landmarks_to_images(disp_images, lm_preds_max[:nimgs], lm_errs=nme_per_lm,
color=pred_color, draw_wireframe=False, gt_landmarks=lm_gt,
draw_gt_offsets=True)
# disp_images = vis.add_landmarks_to_images(disp_images, lm_gt[:nimgs], color=(1,1,1), radius=1,
# draw_dots=True, draw_wireframe=True, landmarks_to_draw=landmarks_to_draw)
# disp_images = vis.add_landmarks_to_images(disp_images, lm_preds_max[:nimgs], lm_errs=nme_per_lm,
# color=(1.0, 0.0, 0.0),
# draw_dots=True, draw_wireframe=True, radius=1,
# gt_landmarks=lm_gt, draw_gt_offsets=False,
# landmarks_to_draw=landmarks_to_draw)
#
# Show reconstructions
#
X_recon_errs = 255.0 * torch.abs(images - X_recon[:nimgs]).reshape(len(images), -1).mean(dim=1)
if not clean:
disp_X_recon = vis.add_error_to_images(disp_X_recon[:nimgs], errors=X_recon_errs, format_string='{:>4.1f}')
# modes of heatmaps
# disp_X_recon = [overlay_heatmap(disp_X_recon[i], pred_heatmaps[i]) for i in range(len(pred_heatmaps))]
if not clean:
lm_errs_max = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm,
landmarks_no_outline, image_size=image_size)
lm_errs_max_outline = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm,
landmarks_only_outline, image_size=image_size)
lm_errs_max_all = calc_landmark_nme_per_img(lm_gt, lm_preds_max, ocular_norm,
list(landmarks_only_outline)+list(landmarks_no_outline),
image_size=image_size)
disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max, loc='br-2', format_string='{:>5.2f}', vmax=15)
disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max_outline, loc='br-1', format_string='{:>5.2f}', vmax=15)
disp_X_recon = vis.add_error_to_images(disp_X_recon, lm_errs_max_all, loc='br', format_string='{:>5.2f}', vmax=15)
disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_gt, color=gt_color, draw_wireframe=True)
# disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_preds_max[:nimgs],
# color=pred_color, draw_wireframe=False,
# lm_errs=nme_per_lm, lm_confs=lm_confs,
# lm_rec_errs=lm_ssim_errs, gt_landmarks=lm_gt,
# draw_gt_offsets=True, draw_dots=True)
disp_X_recon = vis.add_landmarks_to_images(disp_X_recon, lm_preds_max[:nimgs],
color=pred_color, draw_wireframe=True,
gt_landmarks=lm_gt, draw_gt_offsets=True, lm_errs=nme_per_lm,
draw_dots=True, radius=2)
def add_confidences(disp_X_recon, lmids, loc):
means = lm_confs[:,lmids].mean(axis=1)
colors = vis.color_map(to_numpy(1-means), cmap=plt.cm.jet, vmin=0.0, vmax=0.4)
return vis.add_error_to_images(disp_X_recon, means, loc=loc, format_string='{:>4.2f}', colors=colors)
# disp_X_recon = add_confidences(disp_X_recon, lmcfg.LANDMARKS_NO_OUTLINE, 'bm-2')
# disp_X_recon = add_confidences(disp_X_recon, lmcfg.LANDMARKS_ONLY_OUTLINE, 'bm-1')
# disp_X_recon = add_confidences(disp_X_recon, lmcfg.ALL_LANDMARKS, 'bm')
# print ssim errors
ssim = np.zeros(nimgs)
for i in range(nimgs):
ssim[i] = compare_ssim(input_images[i], recon_images[i], data_range=1.0, multichannel=True)
if not clean:
disp_X_recon = vis.add_error_to_images(disp_X_recon, 1 - ssim, loc='bl-1', format_string='{:>4.2f}',
vmax=0.8, vmin=0.2)
# print ssim torch errors
if ssim_maps is not None and not clean:
disp_X_recon = vis.add_error_to_images(disp_X_recon, ssim_maps.reshape(len(ssim_maps), -1).mean(axis=1),
loc='bl-2', format_string='{:>4.2f}', vmin=0.0, vmax=0.4)
rows = [vis.make_grid(disp_images, nCols=nimgs, normalize=False)]
rows.append(vis.make_grid(disp_X_recon, nCols=nimgs))
if ssim_maps is not None:
disp_ssim_maps = to_numpy(nn.denormalized(ssim_maps)[:nimgs].transpose(0, 2, 3, 1))
for i in range(len(disp_ssim_maps)):
disp_ssim_maps[i] = vis.color_map(disp_ssim_maps[i].mean(axis=2), vmin=0.0, vmax=2.0)
grid_ssim_maps = vis.make_grid(disp_ssim_maps, nCols=nimgs, fx=f, fy=f)
cv2.imshow('ssim errors', cv2.cvtColor(grid_ssim_maps, cv2.COLOR_RGB2BGR))
if horizontal:
assert(nimgs == 1)
disp_rows = vis.make_grid(rows, nCols=2)
else:
disp_rows = vis.make_grid(rows, nCols=1)
wnd_title = 'Predicted Landmarks '
if ds is not None:
wnd_title += ds.__class__.__name__
cv2.imshow(wnd_title, cv2.cvtColor(disp_rows, cv2.COLOR_RGB2BGR))
cv2.waitKey(wait)
def visualize_images(X, X_lm_hm, landmarks=None, show_recon=True, show_landmarks=True, show_heatmaps=False,
draw_wireframe=False, smoothing_level=2, heatmap_opacity=0.8, f=1):
if show_recon:
disp_X = vis.to_disp_images(X, denorm=True)
else:
disp_X = vis.to_disp_images(torch.zeros_like(X), denorm=False)
heatmap_opacity = 1
if X_lm_hm is not None:
if smoothing_level > 0:
X_lm_hm = smooth_heatmaps(X_lm_hm)
if smoothing_level > 1:
X_lm_hm = smooth_heatmaps(X_lm_hm)
if show_heatmaps:
pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm))
pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_CUBIC) for im in pred_heatmaps]
disp_X = [vis.overlay_heatmap(disp_X[i], pred_heatmaps[i], heatmap_opacity) for i in range(len(pred_heatmaps))]
if show_landmarks and landmarks is not None:
pred_color = (0,255,255)
disp_X = vis.add_landmarks_to_images(disp_X, landmarks, color=pred_color, draw_wireframe=draw_wireframe)
return disp_X
def generate_images(net, z_random, **kwargs):
with torch.no_grad():
X_gen_vis = net.P(z_random)[:, :3]
X_lm_hm = net.LMH(net.P)
return visualize_images(X_gen_vis, X_lm_hm, **kwargs)
def visualize_random_faces(net, nimgs=10, wait=10, f=1.0):
z_random = torch.randn(nimgs, net.z_dim).cuda()
disp_X_gen = generate_images(net, z_random)
grid_img = vis.make_grid(disp_X_gen, nCols=nimgs//2)
cv2.imshow("random faces", cv2.cvtColor(grid_img, cv2.COLOR_RGB2BGR))
cv2.waitKey(wait)
def visualize_batch_CVPR(images, landmarks, X_recon, X_lm_hm, lm_preds, show_recon=True,
lm_heatmaps=None, ds=None, wait=0, horizontal=False, f=1.0, radius=2,
draw_wireframes=False):
gt_color = (0,255,0)
pred_color = (0,255,255)
# pred_color = (255,0,0)
nimgs = min(10, len(images))
images = nn.atleast4d(images)[:nimgs]
num_landmarks = lm_preds.shape[1]
# if landmarks is None:
# print('num landmarks', num_landmarks)
# lm_gt = np.zeros((nimgs, num_landmarks, 2))
# else:
# show landmark heatmaps
pred_heatmaps = None
if X_lm_hm is not None:
pred_heatmaps = to_single_channel_heatmap(to_numpy(X_lm_hm[:nimgs]))
pred_heatmaps = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in pred_heatmaps]
gt_heatmaps = None
if lm_heatmaps is not None:
gt_heatmaps = to_single_channel_heatmap(to_numpy(lm_heatmaps[:nimgs]))
gt_heatmaps = np.array([cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in gt_heatmaps])
show_landmark_heatmaps(pred_heatmaps, gt_heatmaps, nimgs, f=1)
lm_confs = to_numpy(X_lm_hm).reshape(X_lm_hm.shape[0], X_lm_hm.shape[1], -1).max(axis=2)
# resize images for display and scale landmarks accordingly
lm_preds = lm_preds[:nimgs] * f
rows = []
disp_images = vis.to_disp_images(images[:nimgs], denorm=True)
disp_images = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images]
rows.append(vis.make_grid(disp_images, nCols=nimgs, normalize=False))
heatmap_opacity = 1.0
if show_recon:
recon_images = vis.to_disp_images(X_recon[:nimgs], denorm=True)
else:
recon_images = vis.to_disp_images(torch.ones_like(X_recon[:nimgs]), denorm=False)
heatmap_opacity = 1
disp_X_recon = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
rows.append(vis.make_grid(disp_X_recon, nCols=nimgs))
# overlay landmarks on images
disp_X_recon_hm = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
disp_X_recon_hm = [vis.overlay_heatmap(disp_X_recon_hm[i], pred_heatmaps[i], heatmap_opacity) for i in range(len(pred_heatmaps))]
rows.append(vis.make_grid(disp_X_recon_hm, nCols=nimgs))
# reconstructions with prediction
disp_X_recon_pred = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
disp_X_recon_pred = vis.add_landmarks_to_images(disp_X_recon_pred, lm_preds, color=pred_color,radius=radius)
rows.append(vis.make_grid(disp_X_recon_pred, nCols=nimgs))
# reconstructions with ground truth (if gt available)
if landmarks is not None:
lm_gt = nn.atleast3d(to_numpy(landmarks))[:nimgs] * f
disp_X_recon_gt = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in recon_images.copy()]
disp_X_recon_gt = vis.add_landmarks_to_images(disp_X_recon_gt, lm_gt, color=gt_color, radius=radius)
rows.append(vis.make_grid(disp_X_recon_gt, nCols=nimgs))
# input images with prediction (and ground truth)
disp_images_pred = vis.to_disp_images(images[:nimgs], denorm=True)
disp_images_pred = [cv2.resize(im, None, fx=f, fy=f, interpolation=cv2.INTER_NEAREST) for im in disp_images_pred]
# disp_images_pred = vis.add_landmarks_to_images(disp_images_pred, lm_gt, color=gt_color, radius=radius)
disp_images_pred = vis.add_landmarks_to_images(disp_images_pred, lm_preds, color=pred_color, radius=radius,
draw_wireframe=draw_wireframes)
rows.append(vis.make_grid(disp_images_pred, nCols=nimgs))
if horizontal:
assert(nimgs == 1)
disp_rows = vis.make_grid(rows, nCols=len(rows))
else:
disp_rows = vis.make_grid(rows, nCols=1)
wnd_title = 'recon errors '
if ds is not None:
wnd_title += ds.__class__.__name__
cv2.imshow(wnd_title, cv2.cvtColor(disp_rows, cv2.COLOR_RGB2BGR))
cv2.waitKey(wait)