init first

This commit is contained in:
Sen Liang committed 2022-05-08 17:42:17 +08:00
1 parent a4b5299c26
commit c4ed7854e7
74 files changed
+9565 -89

No files matched your search

+1 -1
View File
@@ -130,7 +130,7 @@ def log_hyperparameters(
p.numel() for p in model.parameters() if not p.requires_grad
)
hparams["datamodule"] = config["datamodule"]
hparams["dataset"] = config["dataset"]
hparams["trainer"] = config["trainer"]
if "seed" in config:
+342
View File
@@ -0,0 +1,342 @@
import moviepy.editor as mpy
import numpy as np
import os
import cv2
from .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()
+7
View File
@@ -0,0 +1,7 @@
FLAG_DEBUG = False
def debug(msg="", verbose=False):
if FLAG_DEBUG or verbose:
print(msg)
+252
View File
@@ -0,0 +1,252 @@
import cv2
import torch
import numpy as np
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
+39
View File
@@ -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