update actor5 & actor6 data processing code

This commit is contained in:
liangsen committed 2022-05-23 22:11:29 +08:00
1 parent 2095b48c56
commit 922a98e36b
29 files changed
+3694 -94

No files matched your search

+93
View File
@@ -0,0 +1,93 @@
import numpy as np
from pathlib2 import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def bbox2point(left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "smile" # processing, processing2
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
logger = Logger(f"./data/{actor}", postfix=f"max-bbox-{sub_folder}")
path_mean_bbox = Path(f"./data/{actor}/max_bbox_{sub_folder}.npy")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
logger.info(f"Have {len(vpath_videos)} dir files")
# IDs = ["2-23min"]
mean_bbox = []
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
# check
vpath_ldmks = list(ipath_ldmks.glob("*.txt"))
kmean_bbox = []
for k, kpath_ldmk in enumerate(vpath_ldmks):
# if k%1000 == 0:
# logger.info(f"batching {k}/{len(vpath_ldmks)} ... ")
kpt = np.loadtxt(kpath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
kpt = kpt[:68, :]
logger.info(f"ERROR: > use first 68-kpts, kpt = {kpt.shape} ipath_ldmk={kpath_ldmk}")
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
kmean_bbox.append([left, right, top, bottom])
if len(vpath_ldmks) > 0:
kmean_bbox = np.array(kmean_bbox)
# kmean_bbox = kmean_bbox.max(axis=0)
left, right = np.min(kmean_bbox[:, 0]), np.max(kmean_bbox[:, 1])
top, bottom = np.min(kmean_bbox[:, 2]), np.max(kmean_bbox[:, 3])
mean_bbox.append([left, right, top, bottom])
logger.info(f"\t max bbox ={[left, right, top, bottom]}")
# get toatl mean bbox
mean_bbox = np.array(mean_bbox)
# mean_bbox = mean_bbox.max(axis=0).astype(np.int32)
left, right = np.min(mean_bbox[:, 0]), np.max(mean_bbox[:, 1])
top, bottom = np.min(mean_bbox[:, 2]), np.max(mean_bbox[:, 3])
mean_bbox = [left, right, top, bottom]
logger.info(f"\ntotal max bbox ={mean_bbox}, ")
logger.info(f"wsize = {right - left}, hsize = {bottom - top} ")
# save mean
np.save(path_mean_bbox, mean_bbox)
# break
@@ -0,0 +1,212 @@
import cv2
from cv2 import norm
import numpy as np
from pathlib2 import Path
from skimage.transform import estimate_transform, warp
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def bbox2point(left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
'''
if type=='kpt68':
old_size = (right - left + bottom - top) / 2 * 1.1
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 ])
elif type=='bbox':
old_size = (right - left + bottom - top)/2
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top ) / 2.0 + old_size*0.12])
else:
raise NotImplementedError
return old_size, center
def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop,
suffix="jpg", crop_size=512, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None):
# get images
vpath_image = sorted(ipath_frame.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
logger.info(f'--> total have {len(vpath_image)} images, top: \n{vpath_image[:3]}')
# set prev_ldmk
prev_ldmk = None
if use_same_bbox:
same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom]
logger.info(f"same_bbox = {same_bbox}")
# for iteration
for j, jpath_frame in enumerate(vpath_image):
image_name = jpath_frame.stem # (frame-0000)
if j%100 == 0:
logger.info(f"load jpath_frame --> {jpath_frame}")
# if j < 19300: continue
ipath_ldmk = ipath_ldmks.joinpath(image_name + ".txt")
if not ipath_ldmk.exists():
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
kpath_fcrop = ipath_fcrop.joinpath(image_name + ".jpg")
kpath_tfrom = ipath_tfrom.joinpath(image_name + ".npy")
kpath_lcrop = ipath_lcrop.joinpath(image_name + ".txt")
###########################
# # check exists
# if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
# # logger.info(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ")
# print(f"kpath_fcrop, kpath_tfrom, kpath_lcrop, have existing! ---> {kpath_fcrop} ")
# continue
###########################
# load orignal image & landmarks
image = cv2.imread(str(jpath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
if kpt.shape[0] > 68:
logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
n_kpt = kpt.shape[0] // 68
max_cos = 0
kpt_selected = None
for idx in range(n_kpt):
cur_kpt = kpt[idx*68:(idx+1)*68, :]
cur_cos = np.dot(prev_ldmk, cur_kpt.reshape(-1)) / (np.linalg.norm(prev_ldmk) * np.linalg.norm(cur_kpt.reshape(-1)))
if cur_cos > max_cos:
max_cos = cur_cos
kpt_selected = cur_kpt
# get kpt, which match the prev_landmarks
logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}")
kpt = kpt_selected
# record prev
prev_ldmk = kpt.copy().reshape(-1) # record prev_ldmk
# reverse H&W
if roation_image:
image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2)
if use_same_bbox:
left, right = same_bbox[0], same_bbox[1]
top, bottom = same_bbox[2], same_bbox[3]
else:
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = bbox2point(left, right, top, bottom, type='kpt68')
# crop transform
size = int(old_size * scale)
src_pts = np.array([[center[0] - size/2, center[1] - size/2], # (left, top)
[center[0] - size/2, center[1] + size/2], # (left, bottom)
[center[0] + size/2, center[1] - size/2]]) # (right, top)
DST_PTS = np.array([[0, 0], # (left-top-corner)
[0, crop_size - 1], # (left-botton corner)
[crop_size - 1, 0]]) # (right-top corner)
# tform_params dytpe = float64, shape = (3, 3)
tform = estimate_transform('similarity', src_pts, DST_PTS)
# image = image/255.
# (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(crop_size, crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2]
# logger.info(f"image dytpe = {image.dtype}, shape = {image.shape} ")
# logger.info(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
# logger.info(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
# logger.info(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
np.save(kpath_tfrom, tform.params)
np.savetxt(kpath_lcrop, cropped_ldmk, fmt=" %3d")
cropped_imag = (255*cropped_imag).astype(np.uint8)
cv2.imwrite(str(kpath_fcrop), cropped_imag)
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_same_bbox = f"data/{actor}/max_bbox_{sub_folder}.npy"
#
vpath_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame
roation_image = True if sub_folder == "body" else False
logger.info(f"roation_image = {roation_image}")
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in ["4R3A0069"]: continue
if iname not in ["4R3A0068", "4R3A0066", "4R3A0065"]: continue
# if iname not in IDs: continue
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_fcrop = ipath_item.joinpath("frames_crop_512")
ipath_tfrom = ipath_item.joinpath("frames_crop_tform_512")
ipath_lcrop = ipath_item.joinpath("frames_crop_ldmks_512")
ipath_fcrop.mkdir(parents=True, exist_ok=True)
ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True)
num_frame = len(list(ipath_frame.glob("*.jpg")))
# check have done
# num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
# if num_frame == num_fcrop:
# logger.info(f"\n Skip: have already done!")
# continue
# check landmarks have exists
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
if num_frame != num_ldmks:
logger.info(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!")
continue
# processing one folder
processing_one_folder(
ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ipath_lcrop,
suffix="jpg", crop_size=512, scale=1.5,
roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox
)
+62 -20
View File
@@ -1,4 +1,5 @@
import cv2
from cv2 import norm
import numpy as np
from pathlib2 import Path
from skimage.transform import estimate_transform, warp
@@ -6,7 +7,7 @@ from skimage.transform import estimate_transform, warp
from torch.utils.data import Dataset, DataLoader
class ImagesDataset(Dataset):
def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=224, scale=1.25, roation_image=False):
def __init__(self, path_frames, path_landmk, suffix="jpg", crop_size=512, scale=1.25, roation_image=False, use_same_bbox=False, path_same_bbox = None):
'''
path_frames: folder, vpath_image, image path, video path
'''
@@ -19,6 +20,14 @@ class ImagesDataset(Dataset):
self.scale = scale # 1.25
self.crop_size = crop_size # 224
self.roation_image =roation_image
self.use_same_bbox = use_same_bbox
self.prev_ldmk = None
if self.use_same_bbox:
self.same_bbox = np.load(path_same_bbox).reshape(-1) # (4,) [left, right, top, bottom]
print(f"same_bbox = {self.same_bbox}")
def bbox2point(self, left, right, top, bottom, type='bbox'):
''' bbox from detector and landmarks are different
@@ -36,10 +45,10 @@ class ImagesDataset(Dataset):
return old_size, center
def __len__(self):
return len(self.vpath_image)
def __getitem__(self, index):
ipath_frame = self.vpath_image[index]
image_name = ipath_frame.stem # (frame-0000)
@@ -51,16 +60,40 @@ class ImagesDataset(Dataset):
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
# load orignal image & landmarks
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
kpt_selected = None
if kpt.shape[0] > 68:
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
n_kpt = kpt.shape[0] // 68
max_cos = 0
for idx in range(n_kpt):
cur_kpt = kpt[idx*68:(idx+1)*68, :]
cur_cos = np.dot(self.prev_ldmk, cur_kpt.reshape(-1)) / (np.linalg.norm(self.prev_ldmk) * np.linalg.norm(cur_kpt.reshape(-1)))
if cur_cos > max_cos:
kpt_selected = cur_kpt
# get kpt, which match the prev_landmarks
kpt = kpt_selected
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {kpt.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
# record prev_ldmk
self.prev_ldmk = kpt.copy().reshpae(-1)
# reverse H&W
if self.roation_image:
image = image.transpose(1,0,2) # (H, W, 3)
kpt = kpt[:, ::-1] # (68, 2)
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
if self.use_same_bbox:
left, right = self.same_bbox[0], self.same_bbox[1]
top, bottom = self.same_bbox[2], self.same_bbox[3]
else:
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68')
# crop transform
@@ -78,17 +111,12 @@ class ImagesDataset(Dataset):
# image = image/255.
# (crop_size, crop_size, 3) ,float64
cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_imag = warp(image, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
cropped_ldmk = cropped_ldmk[:, :2]
# cropped_ldmk[:,:2] = cropped_ldmk[:,:2] / self.crop_size * 2 - 1
if cropped_ldmk.shape[0] > 68:
# raise Exception(f"cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
cropped_ldmk = cropped_ldmk[:68, :]
print(f"ERROR: > use first 68-kpts, cropped_ldmk = {cropped_ldmk.shape}, frame={image_name}, ipath_ldmk={ipath_ldmk}")
# cropped_mask = warp(mask, tform.inverse, output_shape=(self.crop_size, self.crop_size)) # scale to (0~1)
# print(f"image dytpe = {image.dtype}, shape = {image.shape} ")
@@ -107,13 +135,17 @@ class ImagesDataset(Dataset):
if __name__ == "__main__":
sub_folder = "processing" # processing, body, smile
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{sub_folder}")
vpath_videos = sorted(path_data.glob("*"), reverse=False)
sub_folder = "processing2" # processing, processing2
path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}")
path_same_bbox = f"data/Actor6/max_bbox_{sub_folder}.npy"
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
# whole body need roation frame
roation_image = True if sub_folder == "body" else False
print(f"roation_image = {roation_image}")
# IDs = ["2-23min"]
# for each word
@@ -133,17 +165,27 @@ if __name__ == "__main__":
ipath_tfrom.mkdir(parents=True, exist_ok=True)
ipath_lcrop.mkdir(parents=True, exist_ok=True)
# check
# check have done
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
if num_frame == num_fcrop:
print(f"\n Skip: have already done!")
continue
# check landmarks have exists
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
if num_frame != num_ldmks:
print(f"\n ERROR & Skip: ldmaks = {num_ldmks} != nframes {num_frame}!")
continue
# only whole body image, need set roation_image=True
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5, roation_image=roation_image)
dloader = DataLoader(dataset, batch_size=64, num_workers=4, shuffle=False)
dataset = ImagesDataset(ipath_frame, ipath_ldmks, suffix="jpg", crop_size=512, scale=1.5,
roation_image=roation_image, use_same_bbox=True, path_same_bbox = path_same_bbox )
dloader = DataLoader(dataset, batch_size=12, num_workers=1, shuffle=False)
print(f"processing crop ... ")
for j, jbatch in enumerate(dloader):
# print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}")
if j%100 == 0:
@@ -170,6 +212,6 @@ if __name__ == "__main__":
np.save(kpath_tfrom, jbatch_tfrom[k])
np.savetxt(kpath_lcrop, jbatch_ldmks[k], fmt=" %3d")
cv2.imwrite(str(kpath_fcrop), jbatch_crop[k])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# break
-81
View File
@@ -1,81 +0,0 @@
from torch.utils.data import Dataset, DataLoader
import cv2
import torch
import numpy as np
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
from zmq import device
class ImagesDataset(Dataset):
def __init__(self, path_folder:Path):
self.path_folder = path_folder
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
def __len__(self):
return len(self.list_image)
def __getitem__(self, idx):
path_frame = self.list_image[idx]
# image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
# image = np.asarray(image)
image = cv2.imread(str(path_frame)).astype(np.float32)
return {"image_name": path_frame.stem, "image": image}
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:7"
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
print(f"load FaceAlignment model in {device}")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos[16:]):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_frame = ipath_item.joinpath("frames")
ipath_mask = ipath_item.joinpath("skin_mask")
ipath_mask.mkdir(parents=True, exist_ok=True)
# check
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_mask = len(list(ipath_mask.glob("*.jpg")))
if num_frame == num_mask:
print(f"\n Skip: have already done!")
continue
vframe_frame = list(ipath_frame.glob("*.jpg"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
for k, kpath_ in enumerate(dloader):
ibatch_name = ibatch["image_name"]
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
if k%100 == 0:
print(f"batching {k}/{len(dloader)} ... ")
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
# save landmarks
for jldmk, jname in zip(pred, ibatch_name):
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
# break
+110
View File
@@ -0,0 +1,110 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
def load_mask(j, path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno).astype(np.uint8) # (512, 512)
atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
# atts_selected = ['skin', 'l_brow', 'r_brow', 'nose', 'u_lip', 'l_lip']
# atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
# 'nose', 'mouth', 'u_lip', 'l_lip', ]
atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'nose', 'mouth', 'u_lip', 'l_lip']
class_contains = np.unique(parsing_anno)
if j % 1000 == 0:
logger.info(f"\t the {j:06d}-th frame, class_contains = {class_contains}")
for iclass, iatt in enumerate(atts, 1):
if (iatt in atts_selected) and (iclass in class_contains):
index = np.where(parsing_anno == iclass)
mask[index[0], index[1]] = 1
return mask
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"generate-mask-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
logger.info(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_parse = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
logger.info(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_parse = ipath_data.joinpath("frames_crop_parse_512")
ipath_parse_skin = ipath_data.joinpath("frames_crop_parse_skin_512")
ipath_parse_skin.mkdir(parents=True, exist_ok=True)
# if ipath_save_parse.exists():
# logger.info(f"ipath_save_exp have already save > {ipath_save_parse}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
logger.info(f"info = {info}, duration ={nframes / fps / 60}")
# check equal
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_parse = list(ipath_parse.glob("*.npy"))
logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_parse={len(vframe_parse)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_parse += len(vframe_parse) / 50 / 60
logger.info(f"add duration_frame = {duration_frame} min, duration_parse={duration_parse} min")
if len(vframe_frame) != nframes:
logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
# check have done
# vframe_parse = list(ipath_parse_skin.glob("*.npy"))
# if len(vframe_parse) == nframes:
# logger.info(f"ipath_parse_skin have already done!")
# continue
# feat_parse = []
for j in range(len(vframe_frame)):
jpath_parse = ipath_parse.joinpath(f"frame-{j:06d}.npy")
jpath_parse_save = ipath_parse_skin.joinpath(f"frame-{j:06d}.npy")
if not jpath_parse.exists():
logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_parse}")
break
data_mask = load_mask(j, jpath_parse) # (512, 512)
np.save(jpath_parse_save, data_mask)
# feat_parse.append(data_mask)
@@ -0,0 +1,154 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:3"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for i, ipath_data in enumerate(v_dir_videos):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# 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")
ipath_frame = ipath_data.joinpath("frames_crop_512")
# ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d")
# ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
# ipath_vis = ipath_data.joinpath("DECA_vis2")
# ipath_kpt2d.mkdir(parents=True, exist_ok=True)
# ipath_kpt3d.mkdir(parents=True, exist_ok=True)
ipath_coeff.mkdir(parents=True, exist_ok=True)
# ipath_vis.mkdir(parents=True, exist_ok=True)
# load video info
if not ipath_infor.exists():
print(f"\n ERROR: info.json not existing {ipath_infor}")
continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real != nframes:
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_coeff.glob("*.npy")))
if nkpt2d + 10 > nframes:
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector, device=device)
dataloader = DataLoader(datatest, batch_size=128, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
batch_names = ibatch_data["names"]
batch_image = ibatch_data["image"].to(device)
if i%10 == 0:
print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5])
codedict = deca.encode(batch_image) # encoder
# opdict, visdict = deca.decode(codedict, batch_image) # decoder
for j, jname in enumerate(batch_names):
# jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt")
# jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt")
jpath_coeff = ipath_coeff.joinpath(f"{jname}.json")
# np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f")
# np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f")
# save coeff
jcodedict = {}
for key, value in codedict.items():
jcodedict[key] = value[j].cpu().numpy()
# print("json = ", jcodedict)
np.save(jpath_coeff, jcodedict)
# # save render
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# if vis_name not in visdict.keys():
# continue
# img = util.tensor2image(visdict[vis_name][j])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# save vis
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict))
# break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation')
parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str,
help='path to the test data, can be image folder, image path, image list, video')
parser.add_argument('-d', '--device', default='cuda:0', type=str,
help='set device, cpu for using cpu' )
# process test images
parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to crop input image, set false only when the test image are well cropped' )
parser.add_argument('--detector', default='fan', type=str,
help='detector for cropping face, check decalib/detectors.py for details' )
# save
parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to use FLAME texture model to generate uv texture map, \
set it to True only if you downloaded texture model' )
parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization of output' )
parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save 2D and 3D keypoints' )
parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save depth image' )
parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \
Note that saving objs could be slow' )
parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .mat' )
parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization output as seperate images' )
main(parser.parse_args())
+28 -19
View File
@@ -5,30 +5,39 @@ import librosa
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"feature-3dmm-{sub_folder}")
# path data
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
logger.info(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
logger.info(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
# ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists():
continue
@@ -38,28 +47,28 @@ if __name__ == "__main__":
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
logger.info(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
logger.info(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
logger.info(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
logger.info(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
logger.info(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
# if ipath_save_exp.exists() and ipath_save_pos.exists():
# logger.info(f"ipath_save_exp have already save > {ipath_save_exp}")
# continue
feat_exp = []
feat_pos = []
@@ -69,7 +78,7 @@ if __name__ == "__main__":
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
logger.info(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
@@ -91,10 +100,10 @@ if __name__ == "__main__":
np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn)
print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
logger.info(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
logger.info("ERROR, skip! ")
+103
View File
@@ -0,0 +1,103 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
from scipy.signal import savgol_filter
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor = "Actor5"
sub_folder = "processing" # smile, processing, processing2
# logger
logger = Logger(f"./data/{actor}", postfix=f"concat-coeff-{sub_folder}")
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
# ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_coeff = ipath_data.joinpath("deca_coeff_512")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy")
# if ipath_save_coeff.exists():
# print(f"ipath_save_exp have already save > {ipath_save_coeff}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
feat_coeff = []
params = ['shape', 'tex', 'exp', 'pose', 'cam', 'light']
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
codedict = np.load(jpath_coeff, allow_pickle=True).item()
# dim of shape = 100, tex = 50, exp = 50, pose = 6, cam = 3, light = 27
coeff = []
for ikey in params:
coeff += list(codedict[ikey].reshape(-1))
assert len(coeff) == 236, f"coeff len = {len(coeff)} should be 236 !"
feat_coeff.append(np.array(coeff))
# concate
feat_coeff = np.array(feat_coeff) # (N, 236)
# smooth it
feat_coeff = savgol_filter(feat_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
if nframes == feat_coeff.shape[0]:
np.save(ipath_save_coeff, feat_coeff)
print(f"SAVE OK! feat shape = {feat_coeff.shape}, nframe={nframes}\n save to -> {ipath_save_coeff}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
+105
View File
@@ -0,0 +1,105 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
def load_mask(path_parse):
parsing_anno = np.load(path_parse) # (512, 512)
mask = np.zeros_like(parsing_anno).astype(np.uint8) # (512, 512)
atts = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
'nose', 'mouth', 'u_lip', 'l_lip', 'neck', 'neck_l', 'cloth', 'hair', 'hat']
# atts_selected = ['skin', 'l_brow', 'r_brow', 'nose', 'u_lip', 'l_lip']
atts_selected = ['skin', 'l_brow', 'r_brow', 'l_eye', 'r_eye', 'eye_g', 'l_ear', 'r_ear', 'ear_r',
'nose', 'mouth', 'u_lip', 'l_lip', ]
class_contains = np.unique(parsing_anno)
for iclass, iatt in enumerate(atts, 1):
if (iatt in atts_selected) and (iclass in class_contains):
index = np.where(parsing_anno == iclass)
mask[index[0], index[1]] = 1
return mask
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor5/smile")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_parse = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_parse = ipath_data.joinpath("frames_crop_parse_512")
ipath_parse_skin = ipath_data.joinpath("frames_crop_parse_skin_512")
ipath_parse_skin.mkdir(parents=True, exist_ok=True)
# if ipath_save_parse.exists():
# print(f"ipath_save_exp have already save > {ipath_save_parse}")
# continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check equal
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_parse = list(ipath_parse.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_parse={len(vframe_parse)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_parse += len(vframe_parse) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_parse={duration_parse} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
# check have done
# vframe_parse = list(ipath_parse_skin.glob("*.npy"))
# if len(vframe_parse) == nframes:
# print(f"ipath_parse_skin have already done!")
# continue
# feat_parse = []
for j in range(len(vframe_frame)):
jpath_parse = ipath_parse.joinpath(f"frame-{j:06d}.npy")
jpath_parse_save = ipath_parse_skin.joinpath(f"frame-{j:06d}.npy")
if not jpath_parse.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_parse}")
break
data_mask = load_mask(jpath_parse) # (512, 512)
np.save(jpath_parse_save, data_mask)
# feat_parse.append(data_mask)
# feat_parse = np.stack(feat_parse, axis=0)
# if nframes == feat_parse.shape[0]:
# np.save(ipath_save_parse, feat_parse)
# print(f"SAVE OK! feat shape = {feat_parse.shape}, dtype={feat_parse.dtype}, nframe={nframes}\n save to -> {ipath_save_parse}") # (nframe, 68, 2)
# else:
# print("ERROR, skip! ")
@@ -0,0 +1,173 @@
import json
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
actor= "Actor5"
sub_folder = "processing" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_save = Path(f'data/{actor}/{actor}-raw-{sub_folder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save, postfix=f"train-audio2mesh-{sub_folder}")
# get files
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
logger.info(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# logger.info(f"vids total= {vids}")
# training set
if sub_folder == "smile":
vid_test = set(["4R3A0071"])
vid_valid = set(["4R3A0071"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0063"])
vid_valid = set(["4R3A0063"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_test = [], [], []
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
logger.info(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
logger.info(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
logger.info(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
logger.info(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
logger.info(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# ####################################
# # clips 4min
# nclip = 4
# nframes = nclip * 60 * 50 # min * 60s * fps
# nsegmts = nclip * 60 * 16000 # min * 60s * sr
# data_motion = data_motion[:nframes]
# audio_raw = audio_raw[:nsegmts]
# data_idn = data_idn[:nframes]
# ####################################
if vid in vid_train:
durations_train += nframes/fps
list_train.append(vid)
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
list_valid.append(vid)
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_test} ")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
logger.info(f"--> {path_save}")
@@ -6,23 +6,25 @@ import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
subfolder = "processing" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{subfolder}")
path_save = Path(f'data/Actor5/data-list-{subfolder}-1h')
actor= "Actor5"
sub_folder = "processing" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
path_save = Path(f'data/{actor}/data-render-{sub_folder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save)
# set logging
logger = Logger(path_save, postfix=f"train-list-{sub_folder}")
# get files
v_dir_videos = sorted(path_data.glob("*"))
logger.info(f"Have {len(v_dir_videos)} dir files")
vids = set([ipath.stem for ipath in v_dir_videos])
logger.info(f"vids total= {vids}")
@@ -32,19 +34,19 @@ if __name__ == "__main__":
# vid_train = vids - vid_test - vid_valid
# actor5 smile
if subfolder == "smile":
if sub_folder == "smile":
vid_test = set(["4R3A0071"])
vid_valid = set(["4R3A0071"])
vid_train = set(["4R3A0070", "4R3A0072", "4R3A0073", "4R3A0074", "4R3A0075", "4R3A0076"])
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0063", "4R3A0071"])
vid_valid = set(["4R3A0063", "4R3A0071"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0063"])
vid_valid = set(["4R3A0063"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
@@ -61,11 +63,11 @@ if __name__ == "__main__":
logger.info(f"\n\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
# ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
ipath_coeff = ipath_data.joinpath("deca_coeff_512") # DECA coeff of shape/exp/light
ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512
ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
ipath_parse = ipath_data.joinpath("frames_crop_parse_512") # cropped mask
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") # audio path
ipath_parse = ipath_data.joinpath("frames_crop_parse_skin_512") # cropped mask
# check info existing
if not ipath_info.exists():
@@ -94,18 +96,12 @@ if __name__ == "__main__":
logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}")
continue
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
# load coeff
# ipath_feat_coeff = ipath_data.joinpath("audio/feat_DECA_trim.npy")
ipath_feat_coeff = ipath_data.joinpath("audio/feat_deca_coeff_512p.npy")
data_coeff = np.load(ipath_feat_coeff) # (nframe, 236)
data_coeff = data_coeff.astype(np.float16) # convert float16
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
logger.info(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
if vid in vid_train:
durations_train += nframes/fps
@@ -115,8 +111,8 @@ if __name__ == "__main__":
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_speech": audio_raw,
"path_data": str(ipath_data)
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
if vid in vid_valid:
@@ -127,11 +123,10 @@ if __name__ == "__main__":
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_speech": audio_raw,
"path_data": str(ipath_data)
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
@@ -140,8 +135,8 @@ if __name__ == "__main__":
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_speech": audio_raw,
"path_data": str(ipath_data)
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")