beta add render

This commit is contained in:
liangsen committed 2022-05-14 23:20:55 +08:00
1 parent 83f99d9ec5
commit b4c197a8ac
30 files changed
+3210 -235

No files matched your search

+343
View File
@@ -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()