Files
audio2motion/scripts/Test/run-10-processing.py
T
2022-01-21 17:42:41 +08:00

195 lines
6.9 KiB
Python

import cv2
import math
import numpy as np
from pathlib import Path
from PIL import Image
import librosa
import python_speech_features
from reconstruction import Reconstruction
from face_alignment import FaceAlignment, LandmarksType
STEP_EXTRACT_FRAMES = False
STEP_EXTRACT_LANDMK = False
STEP_EXTRACT_MFCC = True
STEP_EXTRACT_3DMM = True
def select_ldmk(ladmks):
ladmks = np.array(ladmks)
area = []
for i in range(ladmks.shape[0]):
lands = ladmks[i, ...]
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
area.append((xmax - xmin) * (ymax-ymin))
print("area = ", area, "select = ", np.argmax(area))
return ladmks[np.argmax(area), :, :]
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
def get_rect(lands):
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
length = 1.2 * math.sqrt((xmax - xmin) * (xmax - xmin) + (ymax - ymin) * (ymax - ymin))
left = (xmax + xmin) / 2 - length / 2
top = (ymax + ymin) / 2 - length / 2
rect = np.array([left, top, length], dtype=np.float)
return rect
if __name__ == "__main__":
path_root = Path("/mnt/data/CODE/Audio2Expression")
path_data = path_root.joinpath("data")
path_audio = path_data.joinpath('input/test_video.wav') # 03Fsi1201.wav,5_00006,03Fsi1201
path_video = path_data.joinpath('input/test_video.mp4') # 31.mp4 ken
video_name = path_video.stem
audio_name = path_audio.stem
path_save = path_data.joinpath(f"processing/{video_name}")
path_save.mkdir(parents=True, exist_ok=True)
# ======================================
# STEP 1: extract frames
# ======================================
path_frames = path_save.joinpath("frames")
path_frames.mkdir(parents=True, exist_ok=True)
if STEP_EXTRACT_FRAMES:
print("STEP 1: extract frames...")
count = 0
cap = cv2.VideoCapture(str(path_video))
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while True:
success, image = cap.read()
if not success:
break
ipath_frame = path_frames.joinpath(f"frame-{count:04d}.jpg")
cv2.imwrite(str(ipath_frame), image)
count += 1
print(f"--> Extract video, have {length}/{count} frames, {path_video}")
# ======================================
# STEP 2: extract landmark
# ======================================
path_landmk = path_save.joinpath("landmk")
path_landmk.mkdir(parents=True, exist_ok=True)
if STEP_EXTRACT_LANDMK:
print("STEP 2: extract landmark...")
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
v_path_frames = sorted(path_frames.glob("*.jpg"))
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = path_landmk.joinpath(f"frame-{frame_id:04d}.txt")
if not ipath_landmk_frame.exists():
# detect image
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
ldmk_pred = model.get_landmarks(np.array(image))
if ldmk_pred is None:
continue
# select the first one or the bigger one face
if len(ldmk_pred) > 1:
ldmk_pred = select_ldmk(ldmk_pred)
else:
ldmk_pred = ldmk_pred[0]
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
# ======================================
# STEP 3: extract mfcc
# ======================================
if STEP_EXTRACT_MFCC:
print("STEP 3: extract mfcc...")
path_save_audio = path_save.joinpath("audio")
path_save_audio.mkdir(parents=True, exist_ok=True)
path_feat = path_save_audio.joinpath("mfcc_feat.npy")
path_feat_align = path_save_audio.joinpath("mfcc_feat_align.npy")
# extarct mfcc feature
audio, sr = librosa.load(str(path_audio), sr=16000) # 16000, (69760, )
mfcc = python_speech_features.mfcc(audio, 16000, winstep=0.01) # seqlen1 x 13
np.save(path_feat, mfcc)
# splited by windows (to fit video frame with fps 25)
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
## seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
mfcc_align = splited_by_windows(mfcc, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
np.save(path_feat_align, mfcc_align)
print(f"audio shape={audio.shape}, mfcc shape={mfcc.shape}, mfcc_align = {mfcc_align.shape} duration={len(audio) / sr}")
# ======================================
# STEP 4: extract 3dmm
# ======================================
path_coeffs = path_save.joinpath("coeff")
path_coeffs.mkdir(parents=True, exist_ok=True)
if STEP_EXTRACT_3DMM:
print("STEP 4: extract 3dmm...")
model = Reconstruction()
vpath_frames = sorted(path_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
for ik, ipath_frame in enumerate(vpath_frames):
fid = int(ipath_frame.stem[-4:])
ipath_ladmk = path_landmk.joinpath(f"frame-{fid:04d}.txt") # get landmark path
if not ipath_ladmk.exists():
continue
# read image and landmark
image = Image.open(str(ipath_frame)).convert('RGB') # (h, w, 3)
ladmk = np.loadtxt(ipath_ladmk, dtype=int) # (68, 2)
bbox = get_rect(ladmk)
# reconstruction
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=path_save)
if ik % 100 == 99:
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")