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

99 lines
3.3 KiB
Python

import os,sys
import cv2
import math
import numpy as np
from pathlib import Path
import torch
from PIL import Image
from reconstruction import Reconstruction
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
def show_landmarks(path_img, path_save, lands):
img = cv2.imread(str(path_img))
for i in range(68):
cv2.circle(img, (lands[i,0], lands[i,1]), 2, (255,0,0))
ipath_save = path_save.joinpath(path_img.stem + "_land.jpg")
cv2.imwrite(str(ipath_save), img)
if __name__ == "__main__":
# load Reconstruction
model = Reconstruction()
# load data
path_data = Path("/mnt/data/DATA/GRID/processing")
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
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):
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark in {ipath_video}")
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_ladmks = ipath_data.joinpath("landmk")
ipath_coeffs = ipath_data.joinpath("coeff")
# STEP1: get frames and landmark
vpath_frames = sorted(ipath_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmks = list(ipath_ladmks.glob("*.txt"))
vpath_coeffs = list(ipath_coeffs.glob("*.txt"))
if len(vpath_frames) != len(vpath_ladmks) or len(vpath_frames) ==0: # if missing landmark data
continue
if ipath_coeffs.exists() and len(vpath_coeffs) == len(vpath_frames): # if have already reconstruction
continue
# STEP2: reconstruction
for ik, ipath_frame in enumerate(vpath_frames):
fid = int(ipath_frame.stem[-4:])
ipath_ladmk = ipath_ladmks.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)
# show_landmarks(image, path_save, ildmk)
# reconstruction
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=ipath_ladmks.parent)
if ik % 100 == 99:
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")