Files
audio2motion/scripts/GRID/run-21-extract-landmark.py
T
2022-01-21 17:42:41 +08:00

83 lines
2.7 KiB
Python

import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
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), :, :]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
#if id_name != "s29": continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_landmk.mkdir(parents=True, exist_ok=True)
# STEP1: get frames
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
# STEP2: extract landmarks
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_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")
#break
#break