add Actor7 support
This commit is contained in:
1 parent
a4c53e3265
commit
7aed8b140a
16 files changed
+399
-312
No files matched your search
@@ -57,7 +57,6 @@ class Audio2MeshModel(Base):
|
|||||||
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
|
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
|
||||||
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||||
|
|
||||||
|
|
||||||
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
|
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
|
||||||
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||||
|
|
||||||
|
|||||||
@@ -7,14 +7,16 @@ from pathlib2 import Path
|
|||||||
from face_alignment import FaceAlignment, LandmarksType
|
from face_alignment import FaceAlignment, LandmarksType
|
||||||
from zmq import device
|
from zmq import device
|
||||||
|
|
||||||
|
import os, sys
|
||||||
|
sys.path.insert(0, os.getcwd())
|
||||||
|
from common.logger import Logger
|
||||||
|
|
||||||
class ImagesDataset(Dataset):
|
class ImagesDataset(Dataset):
|
||||||
def __init__(self, path_folder:Path):
|
def __init__(self, path_folder:Path):
|
||||||
|
|
||||||
self.path_folder = path_folder
|
self.path_folder = path_folder
|
||||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
logger.info(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||||
|
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self.list_image)
|
return len(self.list_image)
|
||||||
@@ -28,36 +30,51 @@ class ImagesDataset(Dataset):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
actor = "Actor7"
|
||||||
|
sub_folder = "processing" # smile, processing, processing2
|
||||||
|
device = "cuda:1"
|
||||||
|
|
||||||
|
# logger
|
||||||
|
path_log = Path(f"./data/{actor}")
|
||||||
|
path_log.mkdir(parents=True, exist_ok=True)
|
||||||
|
logger = Logger(path_log, postfix=f"detect-lm68-{sub_folder}")
|
||||||
|
|
||||||
|
|
||||||
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
|
path_data.mkdir(parents=True, exist_ok=True)
|
||||||
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
||||||
print(f"Have {len(vpath_videos)} dir files")
|
logger.info(f"Have {len(vpath_videos)} dir files")
|
||||||
|
|
||||||
|
|
||||||
device = "cuda:7"
|
|
||||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||||
print(f"load FaceAlignment model in {device}")
|
logger.info(f"load FaceAlignment model in {device}")
|
||||||
|
|
||||||
# IDs = ["2-23min"]
|
# IDs = ["2-23min"]
|
||||||
# for each word
|
# for each word
|
||||||
for i, ipath_item in enumerate(vpath_videos[16:]):
|
for i, ipath_item in enumerate(vpath_videos[:16]):
|
||||||
iname = ipath_item.stem
|
iname = ipath_item.stem
|
||||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||||
|
|
||||||
# if iname not in IDs: continue
|
# if iname not in IDs: continue
|
||||||
|
|
||||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||||
ipath_frame = ipath_item.joinpath("frames")
|
ipath_frame = ipath_item.joinpath("frames")
|
||||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
# check
|
|
||||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||||
|
# check frame have exsit
|
||||||
|
if num_frame < 50:
|
||||||
|
logger.info(f"\n Skip: num_frame = {num_frame} is small!")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# check have done
|
||||||
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
||||||
if num_frame == num_ladmk:
|
if num_frame == num_ladmk:
|
||||||
print(f"\n Skip: have already done!")
|
logger.info(f"\n Skip: have already done!")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
prev_ldmk = None
|
||||||
dataset = ImagesDataset(ipath_frame)
|
dataset = ImagesDataset(ipath_frame)
|
||||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||||
|
|
||||||
@@ -65,18 +82,43 @@ if __name__ == "__main__":
|
|||||||
ibatch_name = ibatch["image_name"]
|
ibatch_name = ibatch["image_name"]
|
||||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
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
|
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]}")
|
# logger.info(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||||
if k%100 == 0:
|
if k%100 == 0:
|
||||||
print(f"batching {k}/{len(dloader)} ... ")
|
logger.info(f"batching {k}/{len(dloader)} ... ")
|
||||||
|
|
||||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
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}")
|
# logger.info(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||||
|
|
||||||
# save landmarks
|
# save landmarks
|
||||||
for jldmk, jname in zip(pred, ibatch_name):
|
for jldmk, jname in zip(pred, ibatch_name):
|
||||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||||
|
|
||||||
|
# if have multipe-landmarks
|
||||||
|
if jldmk.shape[0] > 68:
|
||||||
|
logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {jldmk.shape}, jpath_ldmk={jpath_ldmk}")
|
||||||
|
|
||||||
|
max_cos = 0
|
||||||
|
kpt_selected = None
|
||||||
|
if prev_ldmk is None:
|
||||||
|
kpt_selected = jldmk[:68]
|
||||||
|
else:
|
||||||
|
n_kpt = jldmk.shape[0] // 68
|
||||||
|
for idx in range(n_kpt):
|
||||||
|
cur_kpt = jldmk[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 jldmk, which match the prev_landmarks
|
||||||
|
logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}")
|
||||||
|
jldmk = kpt_selected
|
||||||
|
|
||||||
|
# record prev
|
||||||
|
prev_ldmk = jldmk.copy().reshape(-1) # record prev_ldmk
|
||||||
|
|
||||||
|
# save ldmks
|
||||||
|
assert jldmk.shape[0] == 68, f"jldmak shape = {jldmk.shape}, should be 68! "
|
||||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# break
|
# break
|
||||||
@@ -7,14 +7,16 @@ from pathlib2 import Path
|
|||||||
from face_alignment import FaceAlignment, LandmarksType
|
from face_alignment import FaceAlignment, LandmarksType
|
||||||
from zmq import device
|
from zmq import device
|
||||||
|
|
||||||
|
import os, sys
|
||||||
|
sys.path.insert(0, os.getcwd())
|
||||||
|
from common.logger import Logger
|
||||||
|
|
||||||
class ImagesDataset(Dataset):
|
class ImagesDataset(Dataset):
|
||||||
def __init__(self, path_folder:Path):
|
def __init__(self, path_folder:Path):
|
||||||
|
|
||||||
self.path_folder = path_folder
|
self.path_folder = path_folder
|
||||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
logger.info(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||||
|
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self.list_image)
|
return len(self.list_image)
|
||||||
@@ -28,36 +30,51 @@ class ImagesDataset(Dataset):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
actor = "Actor6"
|
||||||
|
sub_folder = "processing" # smile, processing, processing2
|
||||||
|
device = "cuda:1"
|
||||||
|
|
||||||
|
# logger
|
||||||
|
path_log = Path(f"./data/{actor}")
|
||||||
|
path_log.mkdir(parents=True, exist_ok=True)
|
||||||
|
logger = Logger(path_log, postfix=f"detect-lm68-{sub_folder}")
|
||||||
|
|
||||||
|
|
||||||
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
|
path_data.mkdir(parents=True, exist_ok=True)
|
||||||
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
||||||
print(f"Have {len(vpath_videos)} dir files")
|
logger.info(f"Have {len(vpath_videos)} dir files")
|
||||||
|
|
||||||
|
|
||||||
device = "cuda:7"
|
|
||||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||||
print(f"load FaceAlignment model in {device}")
|
logger.info(f"load FaceAlignment model in {device}")
|
||||||
|
|
||||||
# IDs = ["2-23min"]
|
# IDs = ["2-23min"]
|
||||||
# for each word
|
# for each word
|
||||||
for i, ipath_item in enumerate(vpath_videos[16:]):
|
for i, ipath_item in enumerate(vpath_videos[:16]):
|
||||||
iname = ipath_item.stem
|
iname = ipath_item.stem
|
||||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||||
|
|
||||||
# if iname not in IDs: continue
|
# if iname not in IDs: continue
|
||||||
|
|
||||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||||
ipath_frame = ipath_item.joinpath("frames")
|
ipath_frame = ipath_item.joinpath("frames")
|
||||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
# check
|
|
||||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||||
|
# check frame have exsit
|
||||||
|
if num_frame < 50:
|
||||||
|
logger.info(f"\n Skip: num_frame = {num_frame} is small!")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# check have done
|
||||||
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
||||||
if num_frame == num_ladmk:
|
if num_frame == num_ladmk:
|
||||||
print(f"\n Skip: have already done!")
|
logger.info(f"\n Skip: have already done!")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
prev_ldmk = None
|
||||||
dataset = ImagesDataset(ipath_frame)
|
dataset = ImagesDataset(ipath_frame)
|
||||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||||
|
|
||||||
@@ -65,18 +82,43 @@ if __name__ == "__main__":
|
|||||||
ibatch_name = ibatch["image_name"]
|
ibatch_name = ibatch["image_name"]
|
||||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
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
|
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]}")
|
# logger.info(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||||
if k%100 == 0:
|
if k%100 == 0:
|
||||||
print(f"batching {k}/{len(dloader)} ... ")
|
logger.info(f"batching {k}/{len(dloader)} ... ")
|
||||||
|
|
||||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
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}")
|
# logger.info(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||||
|
|
||||||
# save landmarks
|
# save landmarks
|
||||||
for jldmk, jname in zip(pred, ibatch_name):
|
for jldmk, jname in zip(pred, ibatch_name):
|
||||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||||
|
|
||||||
|
# if have multipe-landmarks
|
||||||
|
if jldmk.shape[0] > 68:
|
||||||
|
logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {jldmk.shape}, jpath_ldmk={jpath_ldmk}")
|
||||||
|
|
||||||
|
max_cos = 0
|
||||||
|
kpt_selected = None
|
||||||
|
if prev_ldmk is None:
|
||||||
|
kpt_selected = jldmk[:68]
|
||||||
|
else:
|
||||||
|
n_kpt = jldmk.shape[0] // 68
|
||||||
|
for idx in range(n_kpt):
|
||||||
|
cur_kpt = jldmk[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 jldmk, which match the prev_landmarks
|
||||||
|
logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}")
|
||||||
|
jldmk = kpt_selected
|
||||||
|
|
||||||
|
# record prev
|
||||||
|
prev_ldmk = jldmk.copy().reshape(-1) # record prev_ldmk
|
||||||
|
|
||||||
|
# save ldmks
|
||||||
|
assert jldmk.shape[0] == 68, f"jldmak shape = {jldmk.shape}, should be 68! "
|
||||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# break
|
# break
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# The data processing pipline
|
||||||
|
|
||||||
|
|
||||||
|
### Folder Tree
|
||||||
|
```
|
||||||
|
cwd:
|
||||||
|
├── data
|
||||||
|
│ ├── Actor7Data
|
||||||
|
│ │ ├── pipline.md
|
||||||
|
│ │ ├── run-00-prepare-data.py
|
||||||
|
│ │ ├── run-01-detect-lm68.py
|
||||||
|
│ │ ├── run-01-mean-bbox.py
|
||||||
|
│ │ ├── run-02-crop-transform-2.py
|
||||||
|
│ │ ├── run-02-crop-transform.py
|
||||||
|
│ │ ├── run-09-remove-files.py
|
||||||
|
│ │ ├── run-10-generate-mask.py
|
||||||
|
│ │ ├── run-20-deca-reconstruction.py
|
||||||
|
│ │ ├── run-21-features-3dmm.py
|
||||||
|
│ │ ├── run-22-concat-3dmm.py
|
||||||
|
│ │ ├── run-23-mean-coeff.py
|
||||||
|
│ │ ├── run-41-train-annodb-audio2mesh.py
|
||||||
|
│ │ └── run-42-train-annodb-ganrender.py
|
||||||
|
|
||||||
|
data_path:
|
||||||
|
/mfs/lsen/DATA/Actor7/processing/4R3A0200/
|
||||||
|
├── audio
|
||||||
|
├── frames # STEP-0结果,保存视频帧(1080p)
|
||||||
|
├── landmarks_FAN # STEP-1结果,保存1080p图像对应的landmark
|
||||||
|
└── video
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### STEP-0: 保存视频帧
|
||||||
|
|
||||||
|
- 需要旋转video(如果是横着拍摄的话)
|
||||||
|
- FPS需要保证是50,(否则会进行FPS转码)
|
||||||
|
- cut前后15s的调焦/准备拍摄片段
|
||||||
|
- 跳过小于1分钟的视频
|
||||||
|
- 保存到`{data_path}/frames`文件夹中
|
||||||
|
|
||||||
|
```
|
||||||
|
python run-01-prepare-data.py
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### STEP-1: 检测关键点
|
||||||
|
|
||||||
|
- 使用`face_alignment`库中的`sfd`检测算法
|
||||||
|
- 若检测到多个face landmarks,智能选择最接近 prev-landmarks的那个
|
||||||
|
- 保存到`{data_path}/landmarks_FAN`文件夹中
|
||||||
|
|
||||||
|
``` python
|
||||||
|
python run-01-detect-lm68.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### STEP-2: 获取全局bbox
|
||||||
|
|
||||||
|
- 用于后期crop image
|
||||||
|
- 遍历所有的frame,选择一个最大的bbox,以覆盖所以的人脸运动区域
|
||||||
|
- 数据保存在`./data/{actor}/max_bbox_{sub_folder}.npy`中
|
||||||
|
|
||||||
|
```
|
||||||
|
python run-01-mean-bbox.py
|
||||||
|
```
|
||||||
|
|
||||||
File renamed without changes.
@@ -7,13 +7,16 @@ from pathlib2 import Path
|
|||||||
from face_alignment import FaceAlignment, LandmarksType
|
from face_alignment import FaceAlignment, LandmarksType
|
||||||
from zmq import device
|
from zmq import device
|
||||||
|
|
||||||
|
import os, sys
|
||||||
|
sys.path.insert(0, os.getcwd())
|
||||||
|
from common.logger import Logger
|
||||||
|
|
||||||
class ImagesDataset(Dataset):
|
class ImagesDataset(Dataset):
|
||||||
def __init__(self, path_folder:Path):
|
def __init__(self, path_folder:Path):
|
||||||
|
|
||||||
self.path_folder = path_folder
|
self.path_folder = path_folder
|
||||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
logger.info(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self.list_image)
|
return len(self.list_image)
|
||||||
@@ -27,36 +30,51 @@ class ImagesDataset(Dataset):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
actor = "Actor7"
|
||||||
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
sub_folder = "processing" # smile, processing, processing2
|
||||||
print(f"Have {len(vpath_videos)} dir files")
|
device = "cuda:0"
|
||||||
|
|
||||||
|
# logger
|
||||||
|
path_log = Path(f"./data/{actor}")
|
||||||
|
path_log.mkdir(parents=True, exist_ok=True)
|
||||||
|
logger = Logger(path_log, postfix=f"detect-lm68-{sub_folder}")
|
||||||
|
|
||||||
|
|
||||||
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
|
path_data.mkdir(parents=True, exist_ok=True)
|
||||||
|
vpath_videos = sorted(path_data.glob("*"), reverse=False)
|
||||||
|
logger.info(f"Have {len(vpath_videos)} dir files")
|
||||||
|
|
||||||
|
|
||||||
device = "cuda:7"
|
|
||||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||||
print(f"load FaceAlignment model in {device}")
|
logger.info(f"load FaceAlignment model in {device}")
|
||||||
|
|
||||||
# IDs = ["2-23min"]
|
# IDs = ["2-23min"]
|
||||||
# for each word
|
# for each word
|
||||||
for i, ipath_item in enumerate(vpath_videos[16:]):
|
for i, ipath_item in enumerate(vpath_videos):
|
||||||
iname = ipath_item.stem
|
iname = ipath_item.stem
|
||||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||||
|
|
||||||
# if iname not in IDs: continue
|
# if iname not in IDs: continue
|
||||||
|
|
||||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||||
ipath_frame = ipath_item.joinpath("frames")
|
ipath_frame = ipath_item.joinpath("frames")
|
||||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
# check
|
|
||||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||||
|
# check frame have exsit
|
||||||
|
if num_frame < 50:
|
||||||
|
logger.info(f"\n Skip: num_frame = {num_frame} is small!")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# check have done
|
||||||
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
||||||
if num_frame == num_ladmk:
|
if num_frame == num_ladmk:
|
||||||
print(f"\n Skip: have already done!")
|
logger.info(f"\n Skip: have already done!")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
prev_ldmk = None
|
||||||
dataset = ImagesDataset(ipath_frame)
|
dataset = ImagesDataset(ipath_frame)
|
||||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||||
|
|
||||||
@@ -64,18 +82,43 @@ if __name__ == "__main__":
|
|||||||
ibatch_name = ibatch["image_name"]
|
ibatch_name = ibatch["image_name"]
|
||||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
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
|
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]}")
|
# logger.info(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||||
if k%100 == 0:
|
if k%100 == 0:
|
||||||
print(f"batching {k}/{len(dloader)} ... ")
|
logger.info(f"batching {k}/{len(dloader)} ... ")
|
||||||
|
|
||||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
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}")
|
# logger.info(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||||
|
|
||||||
# save landmarks
|
# save landmarks
|
||||||
for jldmk, jname in zip(pred, ibatch_name):
|
for jldmk, jname in zip(pred, ibatch_name):
|
||||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||||
|
|
||||||
|
# if have multipe-landmarks
|
||||||
|
if jldmk.shape[0] > 68:
|
||||||
|
logger.info(f"ERROR: > use first 68-kpts, cropped_ldmk = {jldmk.shape}, jpath_ldmk={jpath_ldmk}")
|
||||||
|
|
||||||
|
max_cos = 0
|
||||||
|
kpt_selected = None
|
||||||
|
if prev_ldmk is None:
|
||||||
|
kpt_selected = jldmk[:68]
|
||||||
|
else:
|
||||||
|
n_kpt = jldmk.shape[0] // 68
|
||||||
|
for idx in range(n_kpt):
|
||||||
|
cur_kpt = jldmk[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 jldmk, which match the prev_landmarks
|
||||||
|
logger.info(f"\t SELETCT: max_cos = {max_cos} --> {kpt_selected.reshape(-1)[::10]}")
|
||||||
|
jldmk = kpt_selected
|
||||||
|
|
||||||
|
# record prev
|
||||||
|
prev_ldmk = jldmk.copy().reshape(-1) # record prev_ldmk
|
||||||
|
|
||||||
|
# save ldmks
|
||||||
|
assert jldmk.shape[0] == 68, f"jldmak shape = {jldmk.shape}, should be 68! "
|
||||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# break
|
# break
|
||||||
@@ -31,14 +31,19 @@ def bbox2point(left, right, top, bottom, type='bbox'):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
actor = "Actor7"
|
||||||
sub_folder = "processing" # processing, processing2
|
sub_folder = "processing" # processing, processing2
|
||||||
|
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/Actor6/{sub_folder}")
|
# logger
|
||||||
|
path_log = Path(f"./data/{actor}")
|
||||||
|
path_log.mkdir(parents=True, exist_ok=True)
|
||||||
|
logger = Logger(path_log, postfix=f"max-bbox-{sub_folder}")
|
||||||
|
|
||||||
logger = Logger("./data/Actor6", postfix=f"max_bbox_{sub_folder}")
|
|
||||||
path_mean_bbox = Path(f"./data/Actor6/max_bbox_{sub_folder}.npy")
|
|
||||||
|
|
||||||
|
|
||||||
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
|
path_mean_bbox = Path(f"./data/{actor}/max_bbox_{sub_folder}.npy")
|
||||||
|
|
||||||
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
||||||
logger.info(f"Have {len(vpath_videos)} dir files")
|
logger.info(f"Have {len(vpath_videos)} dir files")
|
||||||
|
|
||||||
@@ -57,24 +62,18 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# check
|
# check
|
||||||
vpath_ldmks = list(ipath_ldmks.glob("*.txt"))
|
vpath_ldmks = list(ipath_ldmks.glob("*.txt"))
|
||||||
|
|
||||||
kmean_bbox = []
|
kmean_bbox = []
|
||||||
for k, kpath_ldmk in enumerate(vpath_ldmks):
|
for k, kpath_ldmk in enumerate(vpath_ldmks):
|
||||||
# if k%1000 == 0:
|
# if k%1000 == 0:
|
||||||
# logger.info(f"batching {k}/{len(vpath_ldmks)} ... ")
|
# logger.info(f"batching {k}/{len(vpath_ldmks)} ... ")
|
||||||
|
|
||||||
|
|
||||||
kpt = np.loadtxt(kpath_ldmk) # (68, 2)
|
kpt = np.loadtxt(kpath_ldmk) # (68, 2)
|
||||||
|
assert kpt.shape[0] == 68, f"ERROR: > kpt = {kpt.shape} should be 68, ipath_ldmk={kpath_ldmk}"
|
||||||
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])
|
left = np.min(kpt[:,0]); right = np.max(kpt[:,0])
|
||||||
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
|
top = np.min(kpt[:,1]); bottom = np.max(kpt[:,1])
|
||||||
kmean_bbox.append([left, right, top, bottom])
|
kmean_bbox.append([left, right, top, bottom])
|
||||||
|
|
||||||
|
|
||||||
if len(vpath_ldmks) > 0:
|
if len(vpath_ldmks) > 0:
|
||||||
kmean_bbox = np.array(kmean_bbox)
|
kmean_bbox = np.array(kmean_bbox)
|
||||||
# kmean_bbox = kmean_bbox.max(axis=0)
|
# kmean_bbox = kmean_bbox.max(axis=0)
|
||||||
@@ -83,6 +82,7 @@ if __name__ == "__main__":
|
|||||||
mean_bbox.append([left, right, top, bottom])
|
mean_bbox.append([left, right, top, bottom])
|
||||||
logger.info(f"\t max bbox ={[left, right, top, bottom]}")
|
logger.info(f"\t max bbox ={[left, right, top, bottom]}")
|
||||||
|
|
||||||
|
|
||||||
# get toatl mean bbox
|
# get toatl mean bbox
|
||||||
mean_bbox = np.array(mean_bbox)
|
mean_bbox = np.array(mean_bbox)
|
||||||
# mean_bbox = mean_bbox.max(axis=0).astype(np.int32)
|
# mean_bbox = mean_bbox.max(axis=0).astype(np.int32)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import os, sys
|
|||||||
sys.path.insert(0, os.getcwd())
|
sys.path.insert(0, os.getcwd())
|
||||||
from common.logger import Logger
|
from common.logger import Logger
|
||||||
|
|
||||||
|
|
||||||
def bbox2point(left, right, top, bottom, type='bbox'):
|
def bbox2point(left, right, top, bottom, type='bbox'):
|
||||||
''' bbox from detector and landmarks are different
|
''' bbox from detector and landmarks are different
|
||||||
'''
|
'''
|
||||||
@@ -32,6 +33,7 @@ def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ip
|
|||||||
vpath_image = sorted(ipath_frame.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
|
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]}')
|
logger.info(f'--> total have {len(vpath_image)} images, top: \n{vpath_image[:3]}')
|
||||||
|
|
||||||
|
|
||||||
# set prev_ldmk
|
# set prev_ldmk
|
||||||
prev_ldmk = None
|
prev_ldmk = None
|
||||||
|
|
||||||
@@ -43,11 +45,10 @@ def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ip
|
|||||||
for j, jpath_frame in enumerate(vpath_image):
|
for j, jpath_frame in enumerate(vpath_image):
|
||||||
image_name = jpath_frame.stem # (frame-0000)
|
image_name = jpath_frame.stem # (frame-0000)
|
||||||
|
|
||||||
if j%100 == 0:
|
if j%200 == 0:
|
||||||
logger.info(f"load jpath_frame --> {jpath_frame}")
|
logger.info(f"load jpath_frame --> {jpath_frame}")
|
||||||
|
|
||||||
# if j < 19300: continu
|
# if j < 19300: continu
|
||||||
|
|
||||||
ipath_ldmk = ipath_ldmks.joinpath(image_name + ".txt")
|
ipath_ldmk = ipath_ldmks.joinpath(image_name + ".txt")
|
||||||
if not ipath_ldmk.exists():
|
if not ipath_ldmk.exists():
|
||||||
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
|
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
|
||||||
@@ -88,11 +89,6 @@ def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ip
|
|||||||
# record prev
|
# record prev
|
||||||
prev_ldmk = kpt.copy().reshape(-1) # record prev_ldmk
|
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:
|
if use_same_bbox:
|
||||||
left, right = same_bbox[0], same_bbox[1]
|
left, right = same_bbox[0], same_bbox[1]
|
||||||
top, bottom = same_bbox[2], same_bbox[3]
|
top, bottom = same_bbox[2], same_bbox[3]
|
||||||
@@ -113,41 +109,50 @@ def processing_one_folder(ipath_frame, ipath_ldmks, ipath_fcrop, ipath_tfrom, ip
|
|||||||
[0, crop_size - 1], # (left-botton corner)
|
[0, crop_size - 1], # (left-botton corner)
|
||||||
[crop_size - 1, 0]]) # (right-top corner)
|
[crop_size - 1, 0]]) # (right-top corner)
|
||||||
|
|
||||||
|
# logger.info(f"estimate_transform - 3")
|
||||||
# tform_params dytpe = float64, shape = (3, 3)
|
# tform_params dytpe = float64, shape = (3, 3)
|
||||||
tform = estimate_transform('similarity', src_pts, DST_PTS)
|
tform = estimate_transform('similarity', src_pts, DST_PTS)
|
||||||
|
|
||||||
# image = image/255.
|
# logger.info(f"estimate_transform - 3 - 2")
|
||||||
# (crop_size, crop_size, 3) ,float64
|
|
||||||
cropped_imag = warp(image, tform.inverse, output_shape=(crop_size, crop_size)) # scale to (0~1)
|
## use skimage (crop_size, crop_size, 3) ,float64, 0~1
|
||||||
|
# cropped_imag = warp(image, tform.inverse, output_shape=(crop_size, crop_size)) # scale to (0~1)
|
||||||
|
# cropped_imag = (255*cropped_imag).astype(np.uint8)
|
||||||
|
|
||||||
|
## use cv2.warpAffine
|
||||||
|
# (crop_size, crop_size, 3) ,uint8, 0~255
|
||||||
|
cropped_imag = cv2.warpAffine(image, tform.params[:2,:], (crop_size, crop_size), flags=cv2.INTER_LANCZOS4) # (dtype=uint, 0~255)
|
||||||
|
cv2.imwrite(str(kpath_fcrop), cropped_imag)
|
||||||
|
|
||||||
|
|
||||||
|
# logger.info(f"estimate_transform - 3 - 3")
|
||||||
cropped_ldmk = np.dot(tform.params, np.hstack([kpt, np.ones([kpt.shape[0],1])]).T).T # (68,3)
|
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 = cropped_ldmk[:, :2]
|
||||||
|
|
||||||
# logger.info(f"image dytpe = {image.dtype}, shape = {image.shape} ")
|
# 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"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"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()} ")
|
# logger.info(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
|
||||||
|
|
||||||
|
# logger.info(f"save np - 4")
|
||||||
np.save(kpath_tfrom, tform.params)
|
np.save(kpath_tfrom, tform.params)
|
||||||
np.savetxt(kpath_lcrop, cropped_ldmk, fmt=" %3d")
|
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__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
actor = "Actor6"
|
actor = "Actor7"
|
||||||
sub_folder = "processing2" # smile, processing, processing2
|
sub_folder = "processing" # smile, processing, processing2
|
||||||
|
|
||||||
# logger
|
# logger
|
||||||
logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}")
|
logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}")
|
||||||
|
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
path_same_bbox = f"data/{actor}/max_bbox_{sub_folder}.npy"
|
path_same_bbox = f"data/{actor}/max_bbox_{sub_folder}.npy"
|
||||||
|
|
||||||
#
|
#
|
||||||
vpath_videos = sorted(path_data.glob("*"), reverse=False)
|
vpath_videos = sorted(path_data.glob("*"), reverse=True)
|
||||||
logger.info(f"Have {len(vpath_videos)} dir files")
|
logger.info(f"Have {len(vpath_videos)} dir files")
|
||||||
|
|
||||||
# whole body need roation frame
|
# whole body need roation frame
|
||||||
@@ -155,11 +160,11 @@ if __name__ == "__main__":
|
|||||||
logger.info(f"roation_image = {roation_image}")
|
logger.info(f"roation_image = {roation_image}")
|
||||||
|
|
||||||
# for each word
|
# for each word
|
||||||
for i, ipath_item in enumerate(vpath_videos):
|
for i, ipath_item in enumerate(vpath_videos[10:]):
|
||||||
iname = ipath_item.stem
|
iname = ipath_item.stem
|
||||||
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||||
|
|
||||||
if iname not in ["4R3A0139"]: continue
|
# if iname not in ["4R3A0139"]: continue
|
||||||
|
|
||||||
# if iname not in IDs: continue
|
# if iname not in IDs: continue
|
||||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||||
@@ -174,11 +179,17 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||||
|
|
||||||
|
|
||||||
|
# check frame have exsit
|
||||||
|
if num_frame < 50:
|
||||||
|
logger.info(f"\n Skip: num_frame = {num_frame} is small!")
|
||||||
|
continue
|
||||||
|
|
||||||
# check have done
|
# check have done
|
||||||
# num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
|
num_fcrop = len(list(ipath_fcrop.glob("*.jpg")))
|
||||||
# if num_frame == num_fcrop:
|
if num_frame == num_fcrop:
|
||||||
# logger.info(f"\n Skip: have already done!")
|
logger.info(f"\n Skip: have already done!")
|
||||||
# continue
|
continue
|
||||||
|
|
||||||
# check landmarks have exists
|
# check landmarks have exists
|
||||||
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
|
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
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 = "Actor6"
|
|
||||||
sub_folder = "processing2" # 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)
|
|
||||||
@@ -17,18 +17,18 @@ from decalib.utils.config import cfg as deca_cfg
|
|||||||
def main(args):
|
def main(args):
|
||||||
|
|
||||||
# device = args.device
|
# device = args.device
|
||||||
device = "cuda:9"
|
device = "cuda:0"
|
||||||
# run DECA
|
# run DECA
|
||||||
deca_cfg.model.use_tex = args.useTex
|
deca_cfg.model.use_tex = args.useTex
|
||||||
deca = DECA(config = deca_cfg, device=device)
|
deca = DECA(config = deca_cfg, device=device)
|
||||||
|
|
||||||
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
|
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
|
||||||
path_data = Path("/ssdata1/lsen/DATA/Actor6/processing2")
|
# path_data = Path("/ssdata1/lsen/DATA/Actor6/processing2")
|
||||||
|
path_data = Path("/mfs/lsen/DATA/Actor7/processing")
|
||||||
|
|
||||||
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
|
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
||||||
print(f"Have {len(v_dir_videos)} dir files")
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
|
||||||
# IDs = ["actor-2HD", "actor-3HD"]
|
# IDs = ["actor-2HD", "actor-3HD"]
|
||||||
# IDs = ["clip_full"]
|
# IDs = ["clip_full"]
|
||||||
|
|
||||||
|
|||||||
@@ -13,14 +13,14 @@ from common.logger import Logger
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
|
||||||
actor = "Actor6"
|
actor = "Actor7"
|
||||||
sub_folder = "processing2" # smile, processing, processing2
|
sub_folder = "processing" # smile, processing, processing2
|
||||||
|
|
||||||
# logger
|
# logger
|
||||||
logger = Logger(f"./data/{actor}", postfix=f"feature-3dmm-{sub_folder}")
|
logger = Logger(f"./data/{actor}", postfix=f"feature-3dmm-{sub_folder}")
|
||||||
|
|
||||||
# path data
|
# path data
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
||||||
logger.info(f"Have {len(v_dir_videos)} dir files")
|
logger.info(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
|||||||
@@ -13,14 +13,14 @@ from common.logger import Logger
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
actor = "Actor6"
|
actor = "Actor7"
|
||||||
sub_folder = "processing2" # smile, processing, processing2
|
sub_folder = "processing" # smile, processing, processing2
|
||||||
|
|
||||||
# logger
|
# logger
|
||||||
logger = Logger(f"./data/{actor}", postfix=f"concat-coeff-{sub_folder}")
|
logger = Logger(f"./data/{actor}", postfix=f"concat-coeff-{sub_folder}")
|
||||||
|
|
||||||
|
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
||||||
print(f"Have {len(v_dir_videos)} dir files")
|
print(f"Have {len(v_dir_videos)} dir files")
|
||||||
|
|
||||||
|
|||||||
@@ -10,16 +10,16 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
|
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
|
||||||
# fid = "4R3A0071"
|
# fid = "4R3A0071"
|
||||||
actor= "Actor6"
|
actor= "Actor7"
|
||||||
sub_folder = "processing2" # processing, smile, body
|
sub_folder = "processing" # processing, smile, body
|
||||||
fid = '4R3A0140'
|
fid = '4R3A0178'
|
||||||
|
|
||||||
|
|
||||||
# logger
|
# logger
|
||||||
logger = Logger(f"./data/{actor}", postfix=f"mean-coeff-{sub_folder}")
|
logger = Logger(f"./data/{actor}", postfix=f"mean-coeff-{sub_folder}")
|
||||||
|
|
||||||
# data
|
# data
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}/{fid}")
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}/{fid}")
|
||||||
path_save = Path(f"./data/{actor}/mean_deca_coeff_{actor}_{sub_folder}.npy")
|
path_save = Path(f"./data/{actor}/mean_deca_coeff_{actor}_{sub_folder}.npy")
|
||||||
path_save.parent.mkdir(parents=True, exist_ok=True)
|
path_save.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|||||||
@@ -11,11 +11,11 @@ from common.logger import Logger
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
actor= "Actor6"
|
actor= "Actor7"
|
||||||
sub_folder = "processing2" # processing, smile, body
|
sub_folder = "processing" # processing, smile, body
|
||||||
|
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
path_save = Path(f'data/{actor}/{actor}-raw-{sub_folder}-1h')
|
path_save = Path(f'data/{actor}/{actor}-raw-{sub_folder}-2h')
|
||||||
path_save.mkdir(parents=True, exist_ok=True)
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
# set logging
|
# set logging
|
||||||
@@ -30,18 +30,15 @@ if __name__ == "__main__":
|
|||||||
# logger.info(f"vids total= {vids}")
|
# logger.info(f"vids total= {vids}")
|
||||||
|
|
||||||
# training set
|
# training set
|
||||||
if sub_folder == "processing2":
|
if sub_folder == "processing":
|
||||||
vid_test = set(["4R3A0139", "4R3A0140"])
|
vid_test = set(["4R3A0178", "4R3A0179"])
|
||||||
vid_valid = set(["4R3A0139", "4R3A0140"])
|
vid_valid = set(["4R3A0178", "4R3A0179"])
|
||||||
vid_train = vids - vid_test - vid_valid
|
vid_train = vids - vid_test - vid_valid
|
||||||
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
|
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
|
||||||
logger.info(f"vid train= {vid_train}")
|
logger.info(f"vid train= {vid_train}")
|
||||||
else:
|
else:
|
||||||
vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"])
|
pass
|
||||||
vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"])
|
|
||||||
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
|
# for each video
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ from common.logger import Logger
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
actor= "Actor6"
|
actor= "Actor7"
|
||||||
sub_folder = "processing2" # processing, smile, body
|
sub_folder = "processing" # processing, smile, body
|
||||||
|
|
||||||
path_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}")
|
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||||
path_save = Path(f'data/{actor}/data-render-{sub_folder}-2h')
|
path_save = Path(f'data/{actor}/data-render-{sub_folder}-2h')
|
||||||
path_save.mkdir(parents=True, exist_ok=True)
|
path_save.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
@@ -35,18 +35,14 @@ if __name__ == "__main__":
|
|||||||
# vid_train = vids - vid_test - vid_valid
|
# vid_train = vids - vid_test - vid_valid
|
||||||
|
|
||||||
# actor5 smile
|
# actor5 smile
|
||||||
if sub_folder == "processing2":
|
if sub_folder == "processing":
|
||||||
vid_test = set(["4R3A0139", "4R3A0140"])
|
vid_test = set(["4R3A0178", "4R3A0179"])
|
||||||
vid_valid = set(["4R3A0139", "4R3A0140"])
|
vid_valid = set(["4R3A0178", "4R3A0179"])
|
||||||
vid_train = vids - vid_test - vid_valid
|
vid_train = vids - vid_test - vid_valid
|
||||||
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
|
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
|
||||||
logger.info(f"vid train= {vid_train}")
|
logger.info(f"vid train= {vid_train}")
|
||||||
else:
|
else:
|
||||||
vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"])
|
pass
|
||||||
vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"])
|
|
||||||
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
|
# for each video
|
||||||
@@ -106,19 +102,20 @@ if __name__ == "__main__":
|
|||||||
data_coeff = data_coeff.astype(np.float16) # convert float16
|
data_coeff = data_coeff.astype(np.float16) # convert float16
|
||||||
|
|
||||||
# load landmark
|
# load landmark
|
||||||
feat_ldmk = []
|
feat_ldmk = np.zeros([num_ldmks, 68, 2]) # (N, 68, 2)
|
||||||
for k in range(num_ldmks):
|
for k in range(num_ldmks):
|
||||||
kpath_ldmk = ipath_ldmks.joinpath(f"frame-{k:06d}.txt")
|
kpath_ldmk = ipath_ldmks.joinpath(f"frame-{k:06d}.txt")
|
||||||
if not kpath_ldmk.exists():
|
if not kpath_ldmk.exists():
|
||||||
logger.info(f"\n ERROR: landmark path NOT FOUND! -> {kpath_ldmk}")
|
logger.info(f"\n ERROR: landmark path NOT FOUND! -> {kpath_ldmk}")
|
||||||
break
|
break
|
||||||
|
|
||||||
kpt = np.loadtxt(kpath_ldmk) # (68, 2)
|
feat_ldmk[k] = np.loadtxt(kpath_ldmk) # (68, 2)
|
||||||
assert kpt.shape[0] == 68, f"the kpt shape ={kpt.shape}, --> {kpath_ldmk}"
|
# assert kpt.shape[0] == 68, f"the kpt shape ={kpt.shape}, --> {kpath_ldmk}"
|
||||||
feat_ldmk.append(kpt)
|
# feat_ldmk[k] = kpt[:]
|
||||||
|
# feat_ldmk.append(kpt)
|
||||||
|
|
||||||
# smooth landmark it
|
# smooth landmark it
|
||||||
feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
|
# feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
|
||||||
feat_ldmk = savgol_filter(feat_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest')
|
feat_ldmk = savgol_filter(feat_ldmk, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ from omegaconf import DictConfig
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
from pytorch_lightning import LightningModule
|
from pytorch_lightning import LightningModule
|
||||||
from torchmetrics import MaxMetric, MeanMetric, MinMetric
|
from torchmetrics import MaxMetric, MeanMetric, MinMetric
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from src.losses import WingLoss
|
from src.losses import WingLoss
|
||||||
from src.utils.debug import debug
|
|
||||||
from src.models import init_weights
|
from src.models import init_weights
|
||||||
|
|
||||||
from src.models.components import flame_mouth_idx
|
from src.models.components import flame_mouth_idx
|
||||||
@@ -23,13 +23,11 @@ class Audio2MeshModel(LightningModule):
|
|||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
lr: float = 0.001,
|
|
||||||
weight_decay: float = 0.0005 ,
|
|
||||||
opt: DictConfig = None,
|
opt: DictConfig = None,
|
||||||
opt_LOSS: DictConfig = None,
|
|
||||||
opt_netF: DictConfig = None,
|
opt_netF: DictConfig = None,
|
||||||
opt_netR: DictConfig = None,
|
opt_netR: DictConfig = None,
|
||||||
opt_netW: DictConfig = None,
|
opt_netW: DictConfig = None,
|
||||||
|
opt_loss: DictConfig = None,
|
||||||
netG: torch.nn.Module = None,
|
netG: torch.nn.Module = None,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
@@ -39,11 +37,9 @@ class Audio2MeshModel(LightningModule):
|
|||||||
# this line allows to access init params with 'self.hparams' attribute
|
# this line allows to access init params with 'self.hparams' attribute
|
||||||
# it also ensures init params will be stored in ckpt
|
# it also ensures init params will be stored in ckpt
|
||||||
# self.save_hyperparameters(logger=False)
|
# self.save_hyperparameters(logger=False)
|
||||||
self.lr = lr
|
|
||||||
self.weight_decay = weight_decay
|
|
||||||
|
|
||||||
self.opt = opt
|
self.opt = opt
|
||||||
self.opt_LOSS = opt_LOSS
|
self.opt_loss = opt_loss
|
||||||
|
|
||||||
self.netG = netG # load Audio2mesh model
|
self.netG = netG # load Audio2mesh model
|
||||||
self.netF = self._load_netF(opt_netF) # load FLAME model
|
self.netF = self._load_netF(opt_netF) # load FLAME model
|
||||||
@@ -82,6 +78,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
|
|
||||||
# loss function
|
# loss function
|
||||||
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
||||||
|
self.loss_func_l1 = nn.L1Loss(reduction="none")
|
||||||
|
|
||||||
|
|
||||||
# use separate metric instance for train, val and test step
|
# use separate metric instance for train, val and test step
|
||||||
# to ensure a proper reduction over the epoch
|
# to ensure a proper reduction over the epoch
|
||||||
@@ -101,8 +99,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
model = FLAME(opt_netF)
|
model = FLAME(opt_netF)
|
||||||
|
|
||||||
# set to freeze
|
# set to freeze
|
||||||
for param in model.parameters():
|
# for param in model.parameters():
|
||||||
param.requires_grad = False
|
# param.requires_grad = False
|
||||||
|
|
||||||
return model.eval()
|
return model.eval()
|
||||||
|
|
||||||
@@ -123,8 +121,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# set to freeze
|
# set to freeze
|
||||||
for param in model.parameters():
|
# for param in model.parameters():
|
||||||
param.requires_grad = False
|
# param.requires_grad = False
|
||||||
|
|
||||||
|
|
||||||
return model.eval()
|
return model.eval()
|
||||||
@@ -140,8 +138,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
extractor = Wav2Vec2Model.from_pretrained(opt_netW.path_ckpt_wav2vec)
|
extractor = Wav2Vec2Model.from_pretrained(opt_netW.path_ckpt_wav2vec)
|
||||||
|
|
||||||
# set to freeze
|
# set to freeze
|
||||||
for param in extractor.parameters():
|
# for param in extractor.parameters():
|
||||||
param.requires_grad = False
|
# param.requires_grad = False
|
||||||
|
|
||||||
return processor, extractor.eval()
|
return processor, extractor.eval()
|
||||||
|
|
||||||
@@ -163,21 +161,19 @@ class Audio2MeshModel(LightningModule):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
# optim = torch.optim.Adam(
|
# optim = torch.optim.Adam(
|
||||||
# params=self.netG.parameters(), lr=self.lr, weight_decay=self.weight_decay
|
# params=self.netG.parameters(), lr=self.opt_loss.lr, weight_decay=self.opt_loss.weight_decay
|
||||||
# )
|
# )
|
||||||
|
|
||||||
optim = torch.optim.Adam(
|
optim = torch.optim.Adam(
|
||||||
params=filter(lambda p: p.requires_grad, self.netG.parameters()),
|
params=filter(lambda p: p.requires_grad, self.netG.parameters()),
|
||||||
lr=self.lr, weight_decay=self.weight_decay
|
lr=self.opt_loss.lr,
|
||||||
|
weight_decay=self.opt_loss.weight_decay
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# logging.info(f"\n[configure_optimizers] self.device = {self.device}")
|
# logging.info(f"\n[configure_optimizers] self.device = {self.device}")
|
||||||
|
|
||||||
return optim
|
return optim
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def set_input(self, batch:Any):
|
def set_input(self, batch:Any):
|
||||||
|
|
||||||
@@ -185,7 +181,7 @@ class Audio2MeshModel(LightningModule):
|
|||||||
|
|
||||||
# motion data
|
# motion data
|
||||||
data = batch["data"].float() # (B, nsteps, nc_motion)
|
data = batch["data"].float() # (B, nsteps, nc_motion)
|
||||||
debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
logging.info(f"data = {data.shape}, dtype={data.dtype}")
|
||||||
|
|
||||||
# batch information
|
# batch information
|
||||||
batch_info = {
|
batch_info = {
|
||||||
@@ -194,19 +190,19 @@ class Audio2MeshModel(LightningModule):
|
|||||||
"interv": batch['frame_interval']
|
"interv": batch['frame_interval']
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# speech data
|
# speech data
|
||||||
cond = None
|
|
||||||
raw_speech = batch["cond"].cpu().numpy() # (B, nsegments)
|
raw_speech = batch["cond"].cpu().numpy() # (B, nsegments)
|
||||||
debug(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
logging.info(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
|
||||||
|
|
||||||
# padding half frame length for bed and end
|
# padding half frame length for bed and end
|
||||||
npad = int(0.5 * self.opt.sr * ( 1 / self.opt.fps) + 0.5)
|
npad = int(0.5 * self.opt.sr * ( 1 / self.opt.fps) + 0.5)
|
||||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||||
debug(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
logging.info(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
|
||||||
|
|
||||||
inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
|
inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
|
||||||
cond = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
|
cond = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
|
||||||
debug(f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
|
logging.info(f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}")
|
||||||
|
|
||||||
# unfold speech data
|
# unfold speech data
|
||||||
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
|
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
|
||||||
@@ -223,10 +219,10 @@ class Audio2MeshModel(LightningModule):
|
|||||||
idx_end = int((7 + self.nsteps) * self.opt.sr / self.opt.fps + 0.5)
|
idx_end = int((7 + self.nsteps) * self.opt.sr / self.opt.fps + 0.5)
|
||||||
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
|
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
|
||||||
|
|
||||||
debug(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
|
logging.info(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}")
|
||||||
debug(f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
logging.info(f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}")
|
||||||
debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
|
logging.info(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}")
|
||||||
debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
|
logging.info(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}")
|
||||||
|
|
||||||
return self.cond, self.vert, batch_info
|
return self.cond, self.vert, batch_info
|
||||||
|
|
||||||
@@ -235,44 +231,38 @@ class Audio2MeshModel(LightningModule):
|
|||||||
return self.netG(x)
|
return self.netG(x)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def step(self, batch:Any):
|
def step(self, batch:Any):
|
||||||
batch_x, batch_tgt, batch_info = self.set_input(batch)
|
batch_x, batch_tgt, batch_info = self.set_input(batch)
|
||||||
|
|
||||||
batch_pdt = self.forward(batch_x)
|
batch_pdt = self.forward(batch_x)
|
||||||
batch_pdt += self.temp_verts
|
batch_pdt += self.temp_verts
|
||||||
|
|
||||||
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
||||||
|
|
||||||
return loss, loss_dict, batch_pdt, batch_tgt, batch_info
|
return loss, loss_dict, batch_pdt, batch_tgt, batch_info
|
||||||
|
|
||||||
|
|
||||||
def get_progress_bar_dict(self):
|
|
||||||
# don't show the version number
|
|
||||||
items = super().get_progress_bar_dict() # "v_num", "loss"
|
|
||||||
items.pop("v_num", None)
|
|
||||||
|
|
||||||
# logging.info(items)
|
|
||||||
# return items
|
|
||||||
|
|
||||||
# items["test"] = '{:.6f}'.format(items["loss"])
|
|
||||||
|
|
||||||
|
|
||||||
return items
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def training_step(self, batch, batch_idx):
|
def training_step(self, batch, batch_idx):
|
||||||
|
|
||||||
loss, loss_dict, *_ = self.step(batch)
|
batch_x, batch_tgt, batch_info = self.set_input(batch)
|
||||||
|
|
||||||
|
batch_pdt = self.forward(batch_x)
|
||||||
|
batch_pdt += self.temp_verts
|
||||||
|
|
||||||
|
# get loss
|
||||||
|
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
||||||
|
|
||||||
# logging.info(f"loss_dict = {loss_dict}")
|
# logging.info(f"loss_dict = {loss_dict}")
|
||||||
# log show loss
|
# log show loss
|
||||||
self.log("train/rec", loss_dict["rec_geo"], on_step=True, on_epoch=False, prog_bar=True)
|
self.log("train/rec", loss_dict["rec_geo"], on_step=True, on_epoch=False, prog_bar=True)
|
||||||
self.log("train/vel", loss_dict["vel_geo"], on_step=True, on_epoch=False, prog_bar=True)
|
self.log("train/vel", loss_dict["vel_geo"], on_step=True, on_epoch=False, prog_bar=True)
|
||||||
|
self.log("train/ldmk", loss_dict["ldmk"], on_step=True, on_epoch=False, prog_bar=True)
|
||||||
|
self.log("train/closure_x", loss_dict["closure_x"], on_step=True, on_epoch=False, prog_bar=True)
|
||||||
|
self.log("train/closure_y", loss_dict["closure_y"], on_step=True, on_epoch=False, prog_bar=True)
|
||||||
|
|
||||||
# # # show metric
|
# add metric
|
||||||
# self.log("train/metric_rec", metric_rec, on_step=False, on_epoch=True, prog_bar=True)
|
self.train_rec(loss_dict["rec_geo"])
|
||||||
# self.log("train/metric_vel", metric_vel, on_step=False, on_epoch=True, prog_bar=True)
|
self.train_vel(loss_dict["vel_geo"])
|
||||||
|
|
||||||
return {"loss": loss}
|
return {"loss": loss}
|
||||||
|
|
||||||
@@ -281,11 +271,20 @@ class Audio2MeshModel(LightningModule):
|
|||||||
"""
|
"""
|
||||||
`outputs` is a list of dicts returned from `training_step()`
|
`outputs` is a list of dicts returned from `training_step()`
|
||||||
"""
|
"""
|
||||||
pass
|
self.log("metric/train/rec", self.train_rec.compute(), on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
self.log("metric/train/vel", self.train_vel.compute(), on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def validation_step(self, batch, batch_idx):
|
def validation_step(self, batch, batch_idx):
|
||||||
loss, loss_dict, *_ = self.step(batch)
|
|
||||||
|
batch_x, batch_tgt, batch_info = self.set_input(batch)
|
||||||
|
|
||||||
|
batch_pdt = self.forward(batch_x)
|
||||||
|
batch_pdt += self.temp_verts
|
||||||
|
|
||||||
|
# get loss
|
||||||
|
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
||||||
|
|
||||||
# show loss
|
# show loss
|
||||||
# self.log("val/total_loss", loss, on_step=False, on_epoch=False, prog_bar=False)
|
# self.log("val/total_loss", loss, on_step=False, on_epoch=False, prog_bar=False)
|
||||||
@@ -296,22 +295,17 @@ class Audio2MeshModel(LightningModule):
|
|||||||
self.valid_rec(loss_dict["rec_geo"])
|
self.valid_rec(loss_dict["rec_geo"])
|
||||||
self.valid_vel(loss_dict["vel_geo"])
|
self.valid_vel(loss_dict["vel_geo"])
|
||||||
self.val_best(loss)
|
self.val_best(loss)
|
||||||
# self.log("val/metric_rec", metric_rec, on_step=True, on_epoch=True, prog_bar=True)
|
|
||||||
# self.log("val/metric_vel", metric_vel, on_step=True, on_epoch=True, prog_bar=True)
|
|
||||||
|
|
||||||
return {"loss": loss}
|
return {"loss": loss}
|
||||||
|
|
||||||
# return {"loss": loss, "preds": batch_pdt, "targets": batch_tgt, "info": batch_info}
|
|
||||||
|
|
||||||
|
|
||||||
def validation_epoch_end(self, outputs: List[Any]):
|
def validation_epoch_end(self, outputs: List[Any]):
|
||||||
"""
|
"""
|
||||||
`outputs` is a list of dicts returned from `validation_step()`
|
`outputs` is a list of dicts returned from `validation_step()`
|
||||||
"""
|
"""
|
||||||
|
self.log("metric/val/rec", self.valid_rec.compute(), on_step=False, on_epoch=True, prog_bar=True)
|
||||||
self.log("val/rec", self.valid_rec.compute(), on_step=False, on_epoch=True, prog_bar=True)
|
self.log("metric/val/vel", self.valid_vel.compute(), on_step=False, on_epoch=True, prog_bar=True)
|
||||||
self.log("val/vel", self.valid_vel.compute(), on_step=False, on_epoch=True, prog_bar=True)
|
self.log("metric/val/best", self.val_best.compute(), on_epoch=True, prog_bar=True)
|
||||||
self.log("val/best", self.val_best.compute(), on_epoch=True, prog_bar=True)
|
|
||||||
|
|
||||||
|
|
||||||
def test_step(self, batch, batch_idx):
|
def test_step(self, batch, batch_idx):
|
||||||
@@ -321,7 +315,6 @@ class Audio2MeshModel(LightningModule):
|
|||||||
self.test_rec(loss_dict["rec_geo"])
|
self.test_rec(loss_dict["rec_geo"])
|
||||||
self.test_vel(loss_dict["vel_geo"])
|
self.test_vel(loss_dict["vel_geo"])
|
||||||
|
|
||||||
|
|
||||||
return {"loss": loss}
|
return {"loss": loss}
|
||||||
# return {"batch_pdt": batch_pdt, "batch_tgt": batch_tgt, "batch_info": batch_info}
|
# return {"batch_pdt": batch_pdt, "batch_tgt": batch_tgt, "batch_info": batch_info}
|
||||||
|
|
||||||
@@ -351,28 +344,26 @@ class Audio2MeshModel(LightningModule):
|
|||||||
loss_dict = {}
|
loss_dict = {}
|
||||||
|
|
||||||
# synthesis geo rec
|
# synthesis geo rec
|
||||||
loss = 0
|
|
||||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||||
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
|
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
|
||||||
|
|
||||||
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
||||||
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
|
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
|
||||||
# loss += loss_rec_geo.mean() * self.opt_LOSS.lambda_rec_geo
|
# loss += loss_rec_geo.mean() * self.opt_loss.lambda_rec_geo
|
||||||
loss += loss_rec_geo2.mean() * self.opt_LOSS.lambda_rec_geo
|
loss += loss_rec_geo2.mean() * self.opt_loss.lambda_rec_geo
|
||||||
|
|
||||||
# synthesis geo volocity
|
# synthesis geo volocity
|
||||||
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
||||||
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
||||||
|
|
||||||
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||||
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
|
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
|
||||||
|
|
||||||
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
||||||
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
||||||
# loss += loss_vel_geo.mean() * self.opt_LOSS.lambda_vel_geo
|
# loss += loss_vel_geo.mean() * self.opt_loss.lambda_vel_geo
|
||||||
|
|
||||||
if self.opt_LOSS.lambda_vel_geo > 0:
|
if self.opt_loss.lambda_vel_geo > 0:
|
||||||
loss += loss_vel_geo2.mean() * self.opt_LOSS.lambda_vel_geo
|
loss += loss_vel_geo2.mean() * self.opt_loss.lambda_vel_geo
|
||||||
|
|
||||||
# landmarks loss
|
# landmarks loss
|
||||||
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.num_vertices, 3)) # (B*N, 68, 3)
|
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.num_vertices, 3)) # (B*N, 68, 3)
|
||||||
@@ -380,8 +371,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
||||||
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
||||||
|
|
||||||
if self.opt_LOSS.lambda_rec_ldmk > 0:
|
if self.opt_loss.lambda_rec_ldmk > 0:
|
||||||
loss += loss_rec_ldmk.mean() * self.opt_LOSS.lambda_rec_ldmk
|
loss += loss_rec_ldmk.mean() * self.opt_loss.lambda_rec_ldmk
|
||||||
|
|
||||||
# mouth closure_x loss (left/right mouth)
|
# mouth closure_x loss (left/right mouth)
|
||||||
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
|
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
|
||||||
@@ -392,8 +383,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
|
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
|
||||||
loss_dict["closure_x"] = loss_closure_x.mean().detach()
|
loss_dict["closure_x"] = loss_closure_x.mean().detach()
|
||||||
|
|
||||||
if self.opt_LOSS.lambda_closure_x > 0:
|
if self.opt_loss.lambda_closure_x > 0:
|
||||||
loss += loss_closure_x.mean() * self.opt_LOSS.lambda_closure_x
|
loss += loss_closure_x.mean() * self.opt_loss.lambda_closure_x
|
||||||
|
|
||||||
# mouth closure_y loss (upper/lower mouth)
|
# mouth closure_y loss (upper/lower mouth)
|
||||||
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
|
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
|
||||||
@@ -404,8 +395,8 @@ class Audio2MeshModel(LightningModule):
|
|||||||
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
|
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
|
||||||
loss_dict["closure_y"] = loss_closure_y.mean().detach()
|
loss_dict["closure_y"] = loss_closure_y.mean().detach()
|
||||||
|
|
||||||
if self.opt_LOSS.lambda_closure_y > 0:
|
if self.opt_loss.lambda_closure_y > 0:
|
||||||
loss += loss_closure_y.mean() * self.opt_LOSS.lambda_closure_y
|
loss += loss_closure_y.mean() * self.opt_loss.lambda_closure_y
|
||||||
|
|
||||||
|
|
||||||
# total loss
|
# total loss
|
||||||
@@ -462,7 +453,6 @@ class Audio2MeshModel(LightningModule):
|
|||||||
return verts, ldmk2d, ldmk3d
|
return verts, ldmk2d, ldmk3d
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def render_geometry(self, verts, cam=None, device=None):
|
def render_geometry(self, verts, cam=None, device=None):
|
||||||
"""
|
"""
|
||||||
@@ -589,6 +579,17 @@ class Audio2MeshModel(LightningModule):
|
|||||||
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
||||||
|
|
||||||
|
|
||||||
|
def get_progress_bar_dict(self):
|
||||||
|
# don't show the version number
|
||||||
|
items = super().get_progress_bar_dict() # "v_num", "loss"
|
||||||
|
items.pop("v_num", None)
|
||||||
|
|
||||||
|
# logging.info(items)
|
||||||
|
# return items
|
||||||
|
# items["test"] = '{:.6f}'.format(items["loss"])
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
def tensor2image(self, tensor):
|
def tensor2image(self, tensor):
|
||||||
# image = tensor.detach().cpu().numpy()
|
# image = tensor.detach().cpu().numpy()
|
||||||
image = tensor.numpy()
|
image = tensor.numpy()
|
||||||
|
|||||||
Reference in new issue
Block a user