add deployment tools of pytorch2onnx
This commit is contained in:
1 parent
28810e9ed3
commit
91cdd0d678
9 files changed
+461
-71
No files matched your search
@@ -8,8 +8,10 @@ if __name__ == '__main__':
|
||||
|
||||
# path_root = Path("/yrfs/lsen/DATA/Actor1")
|
||||
|
||||
path_raw = Path("/ssdata1/cf/data/raw/20220319")
|
||||
path_root = Path("/yrfs/lsen/DATA/Actor2")
|
||||
# path_raw = Path("/ssdata1/cf/data/raw/20220319")
|
||||
path_raw = Path("/ssdata1/cf/data/raw/20220408")
|
||||
# path_root = Path("/mfs/lsen/DATA/Actor2/processing")
|
||||
path_root = Path("/mfs/lsen/DATA/Actor2/happy")
|
||||
|
||||
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
@@ -25,7 +27,7 @@ if __name__ == '__main__':
|
||||
# if iname not in IDs: continue
|
||||
|
||||
# data path
|
||||
ipath_data = path_root.joinpath("processing", ipath_item.stem)
|
||||
ipath_data = path_root.joinpath(ipath_item.stem)
|
||||
|
||||
ipath_frame = ipath_data.joinpath("frames")
|
||||
ipath_video = ipath_data.joinpath("video")
|
||||
@@ -91,7 +93,6 @@ if __name__ == '__main__':
|
||||
nframes = len(list(video.iter_frames()))
|
||||
|
||||
|
||||
|
||||
# get audio
|
||||
audio_sub = video.audio
|
||||
if audio_sub is None:
|
||||
|
||||
@@ -24,8 +24,9 @@ def main(args):
|
||||
deca = DECA(config = deca_cfg, device=device)
|
||||
|
||||
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
|
||||
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
|
||||
|
||||
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
|
||||
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
|
||||
|
||||
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
||||
print(f"Have {len(v_dir_videos)} dir files")
|
||||
|
||||
@@ -39,7 +40,6 @@ def main(args):
|
||||
# if ivideo_name not in IDs: continue
|
||||
|
||||
# if i > 25: break
|
||||
|
||||
ipath_infor = ipath_data.joinpath("video/info.json")
|
||||
ipath_frame = ipath_data.joinpath("frames")
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import moviepy
|
||||
from moviepy.editor import VideoFileClip, AudioFileClip
|
||||
|
||||
@@ -36,18 +37,18 @@ if __name__ == '__main__':
|
||||
ipath_video.mkdir(parents=True, exist_ok=True)
|
||||
ipath_audio.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# # load video info & check
|
||||
if ipath_infor.exists():
|
||||
# continue
|
||||
with open(str(ipath_infor), "r") as f:
|
||||
info = json.load(f)
|
||||
nframe_info = info['nframes']
|
||||
# # # load video info & check
|
||||
# if ipath_infor.exists():
|
||||
# # continue
|
||||
# with open(str(ipath_infor), "r") as f:
|
||||
# info = json.load(f)
|
||||
# nframe_info = info['nframes']
|
||||
|
||||
# check frames
|
||||
nframe_real = len(list(ipath_frame.glob("*.jpg")))
|
||||
if nframe_real == nframe_info:
|
||||
print(f"\n Skip: have already done!")
|
||||
continue
|
||||
# # check frames
|
||||
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
|
||||
# if nframe_real == nframe_info:
|
||||
# print(f"\n Skip: have already done!")
|
||||
# continue
|
||||
|
||||
# load video
|
||||
video = VideoFileClip(str(ipath_item))
|
||||
@@ -61,71 +62,79 @@ if __name__ == '__main__':
|
||||
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
|
||||
# continue
|
||||
|
||||
# Trim
|
||||
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
|
||||
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
|
||||
# add
|
||||
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
|
||||
if not ipath_video_sub.exists():
|
||||
cmd = f"ffmpeg -y -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
|
||||
os.system(cmd)
|
||||
print(f"save video > {ipath_video_sub}")
|
||||
|
||||
# video = video.subclip(t_start=5.0, t_end=60.0)
|
||||
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||
nframes = int(video.duration * video.fps)
|
||||
# nframes = len(list(video.iter_frames()))
|
||||
|
||||
# # Trim
|
||||
# # video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
|
||||
# video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
|
||||
|
||||
# # video = video.subclip(t_start=5.0, t_end=60.0)
|
||||
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||
# nframes = int(video.duration * video.fps)
|
||||
# # nframes = len(list(video.iter_frames()))
|
||||
# # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||
|
||||
# if fps != 50
|
||||
if video.fps != 50:
|
||||
print("FPS NOT = 50!! ")
|
||||
# # if fps != 50
|
||||
# if video.fps != 50:
|
||||
# print("FPS NOT = 50!! ")
|
||||
|
||||
# save sub video fps=50
|
||||
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
|
||||
if ipath_video_sub.exists():
|
||||
print("\nERROR: ipath_video_sub.exists()")
|
||||
continue
|
||||
else:
|
||||
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
|
||||
print(f"save video > {ipath_video_sub}")
|
||||
# # save sub video fps=50
|
||||
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
|
||||
# if ipath_video_sub.exists():
|
||||
# print("\nERROR: ipath_video_sub.exists()")
|
||||
# continue
|
||||
# else:
|
||||
# video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
|
||||
# print(f"save video > {ipath_video_sub}")
|
||||
|
||||
# reload video
|
||||
video.close()
|
||||
video = VideoFileClip(str(ipath_video_sub))
|
||||
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||
nframes = len(list(video.iter_frames()))
|
||||
# # reload video
|
||||
# video.close()
|
||||
# video = VideoFileClip(str(ipath_video_sub))
|
||||
# print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||
# nframes = len(list(video.iter_frames()))
|
||||
|
||||
|
||||
# get audio
|
||||
audio_sub = video.audio
|
||||
if audio_sub is None:
|
||||
print("\nERROR: audio info is None")
|
||||
# # get audio
|
||||
# audio_sub = video.audio
|
||||
# if audio_sub is None:
|
||||
# print("\nERROR: audio info is None")
|
||||
|
||||
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
|
||||
# print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
|
||||
|
||||
# save audio_sub
|
||||
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
|
||||
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
|
||||
print(f"save audio > {ipath_audio_sub}")
|
||||
# # save audio_sub
|
||||
# ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
|
||||
# audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
|
||||
# print(f"save audio > {ipath_audio_sub}")
|
||||
|
||||
# # check fps
|
||||
# if int(video.fps) != 50:
|
||||
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
|
||||
# # # check fps
|
||||
# # if int(video.fps) != 50:
|
||||
# # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
|
||||
|
||||
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
|
||||
# video.write_videofile(str(ipath_video_save), fps=50.0)
|
||||
# print(f"save video to > {ipath_video_save}...")
|
||||
# # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
|
||||
# # video.write_videofile(str(ipath_video_save), fps=50.0)
|
||||
# # print(f"save video to > {ipath_video_save}...")
|
||||
|
||||
# save video feature
|
||||
info = {"nframes": nframes,
|
||||
"fps": video.fps,
|
||||
"width": video.w,
|
||||
"height": video.h}
|
||||
# # save video feature
|
||||
# info = {"nframes": nframes,
|
||||
# "fps": video.fps,
|
||||
# "width": video.w,
|
||||
# "height": video.h}
|
||||
|
||||
with open(str(ipath_infor), 'w+') as f:
|
||||
json.dump(info, f)
|
||||
print(info)
|
||||
print(f"save video info in -> {ipath_infor}\n")
|
||||
# with open(str(ipath_infor), 'w+') as f:
|
||||
# json.dump(info, f)
|
||||
# print(info)
|
||||
# print(f"save video info in -> {ipath_infor}\n")
|
||||
|
||||
# save trim video
|
||||
print(f"write_images_sequence...")
|
||||
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
|
||||
video.write_images_sequence(ipath_format, fps=50)
|
||||
# # save trim video
|
||||
# print(f"write_images_sequence...")
|
||||
# ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
|
||||
# video.write_images_sequence(ipath_format, fps=50)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ def _convert_batchnorm(module):
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
|
||||
|
||||
parser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
|
||||
parser.add_argument("--opt", type=str, default="experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml", help="experiment configure file name")
|
||||
args, _ = parser.parse_known_args()
|
||||
update_config(args.opt)
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# Copyright (c) OpenMMLab. All rights reserved.
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
import onnx
|
||||
import onnxruntime as rt
|
||||
|
||||
import os, sys
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
|
||||
|
||||
from lsp.options.test_feature2face_options import TestOptions as RenderOptions
|
||||
from lsp.models import create_model
|
||||
from lsp.models import feature2face_model
|
||||
from lsp.models.feature2face_G import Feature2Face_G
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
# create m2f model
|
||||
gen_opt = RenderOptions().parse()
|
||||
gen_opt.name = "ljj" #args.name
|
||||
gen_opt.batch_size = 64 #args.batch_size_m2f
|
||||
path_ckpt_m2f = f'./data/render/models/{gen_opt.name}/render_g.pkl'
|
||||
|
||||
device = torch.device("cuda:0")
|
||||
|
||||
# model_m2f = create_model(gen_opt)
|
||||
# model_m2f.Feature2Face_G.eval()
|
||||
# model_m2f.Feature2Face_G.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
|
||||
|
||||
netG = Feature2Face_G(gen_opt).to(device)
|
||||
netG = torch.nn.DataParallel(netG, [device,])
|
||||
netG.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
|
||||
netG.eval()
|
||||
|
||||
path_onnx = Path(f"./data/render/models/{gen_opt.name}/render_g.onnx")
|
||||
if not path_onnx.exists():
|
||||
# forward test
|
||||
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
|
||||
batch_otput = netG(batch_input) # (B, 3, 512, 512)
|
||||
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
|
||||
|
||||
torch.onnx.export(
|
||||
netG.module, # model being run
|
||||
batch_input,
|
||||
str(path_onnx),
|
||||
export_params=True,
|
||||
verbose=True,
|
||||
opset_version=11,
|
||||
input_names=["input"],
|
||||
output_names=["output"],
|
||||
dynamic_axes = {
|
||||
"input": {0: "batch_size"},
|
||||
"output": {0: "batch_size"}
|
||||
}
|
||||
)
|
||||
print(f'Successfully exported ONNX model: {path_onnx}')
|
||||
else:
|
||||
print(f'Have existed exported ONNX model: {path_onnx}')
|
||||
|
||||
# valify
|
||||
onnx_model = onnx.load(path_onnx)
|
||||
onnx.checker.check_model(onnx_model)
|
||||
|
||||
# check the numerical value
|
||||
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
|
||||
batch_otput = netG(batch_input).detach().cpu().numpy() # (B, 3, 512, 512)
|
||||
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
|
||||
|
||||
# get onnx output
|
||||
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
||||
batch_onnx = sess.run(["output"], {"input": batch_input.cpu().numpy()})[0]
|
||||
|
||||
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
|
||||
|
||||
assert np.allclose(batch_otput, batch_onnx, atol=1e-4), 'The outputs are different between Pytorch and ONNX'
|
||||
print('The numerical values are same between Pytorch and ONNX')
|
||||
print(f"output[0, :, 100] = \n{batch_otput[0, 0, 100:120, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0, 0, 100:120, 100]}")
|
||||
|
||||
Reference in new issue
Block a user