add data processing for crop & skin-mask
This commit is contained in:
1 parent
e51d3d1a6f
commit
83f99d9ec5
33 files changed
+2262
-2524
No files matched your search
@@ -0,0 +1,82 @@
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
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)
|
||||
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_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||
ipath_frame = ipath_item.joinpath("frames")
|
||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
# check
|
||||
num_frame = len(list(ipath_frame.glob("*.jpg")))
|
||||
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
|
||||
if num_frame == num_ladmk:
|
||||
print(f"\n Skip: have already done!")
|
||||
continue
|
||||
|
||||
|
||||
dataset = ImagesDataset(ipath_frame)
|
||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||
|
||||
for k, ibatch 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
|
||||
@@ -0,0 +1,175 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pathlib2 import Path
|
||||
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):
|
||||
'''
|
||||
path_frames: folder, vpath_image, image path, video path
|
||||
'''
|
||||
|
||||
self.path_frames = Path(path_frames)
|
||||
self.path_landmk = Path(path_landmk)
|
||||
self.vpath_image = sorted(self.path_frames.glob(f"*.{suffix}"), key=lambda x: int(x.stem.split("-")[-1]), reverse=False)
|
||||
print(f'--> total have {len(self.vpath_image)} images, top: \n{self.vpath_image[:3]}')
|
||||
|
||||
self.scale = scale # 1.25
|
||||
self.crop_size = crop_size # 224
|
||||
self.roation_image =roation_image
|
||||
|
||||
def bbox2point(self, 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 __len__(self):
|
||||
return len(self.vpath_image)
|
||||
|
||||
def __getitem__(self, index):
|
||||
ipath_frame = self.vpath_image[index]
|
||||
image_name = ipath_frame.stem # (frame-0000)
|
||||
|
||||
# print(f"load ipath_frame --> {ipath_frame}")
|
||||
|
||||
ipath_ldmk = self.path_landmk.joinpath(image_name + ".txt")
|
||||
if not ipath_ldmk.exists():
|
||||
raise Exception(f"ipath_ldmk not exists --> {ipath_ldmk}")
|
||||
|
||||
# load orignal image & landmarks
|
||||
image = cv2.imread(str(ipath_frame)) # (H, W, 3), dtype=uint8
|
||||
kpt = np.loadtxt(ipath_ldmk) # (68, 2)
|
||||
|
||||
# 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])
|
||||
old_size, center = self.bbox2point(left, right, top, bottom, type='kpt68')
|
||||
|
||||
# crop transform
|
||||
size = int(old_size * self.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, self.crop_size - 1], # (left-botton corner)
|
||||
[self.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=(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} ")
|
||||
# print(f"cropped_imag dytpe = {cropped_imag.dtype}, shape = {cropped_imag.shape} ")
|
||||
# print(f"tform_params dytpe = {tform.params.dtype}, shape = {tform.params.shape} ")
|
||||
# print(f"cropped_ldmk dytpe = {cropped_ldmk.dtype}, shape = {cropped_ldmk.shape}, max={cropped_ldmk.max()}, min={cropped_ldmk.min()} ")
|
||||
# # print(f"jbatch_ldmks ={cropped_ldmk}")
|
||||
|
||||
return {'image_name': ipath_frame.stem,
|
||||
'image': image,
|
||||
'cropped_imag': cropped_imag,
|
||||
'tform_params': tform.params,
|
||||
'cropped_ldmk': cropped_ldmk,
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
# whole body need roation frame
|
||||
roation_image = True if sub_folder == "body" else False
|
||||
|
||||
# IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
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_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)
|
||||
|
||||
# check
|
||||
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
|
||||
|
||||
# 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)
|
||||
|
||||
for j, jbatch in enumerate(dloader):
|
||||
# print(f"jbatch_data shape = {jbatch_data.shape}, path={jbatch_name[:3]}")
|
||||
if j%100 == 0:
|
||||
print(f"batching {j}/{len(dloader)} ... ")
|
||||
|
||||
jbatch_name = jbatch["image_name"]
|
||||
jbatch_crop = (255*jbatch["cropped_imag"]).numpy().astype(np.uint8)
|
||||
jbatch_tfrom = jbatch["tform_params"].numpy()
|
||||
jbatch_ldmks = jbatch["cropped_ldmk"].numpy()
|
||||
|
||||
# print(f"jbatch_crop dytpe = {jbatch_crop.dtype}, shape = {jbatch_crop.shape} ")
|
||||
# print(f"jbatch_tfrom dytpe = {jbatch_tfrom.dtype}, shape = {jbatch_tfrom.shape} ")
|
||||
# print(f"jbatch_ldmks dytpe = {jbatch_ldmks.dtype}, shape = {jbatch_ldmks.shape}, max={jbatch_ldmks.max()}, min={jbatch_ldmks.min()} ")
|
||||
|
||||
# save data
|
||||
for k,kname in enumerate(jbatch_name):
|
||||
kpath_fcrop = ipath_fcrop.joinpath(kname + ".jpg")
|
||||
kpath_tfrom = ipath_tfrom.joinpath(kname + ".npy")
|
||||
kpath_lcrop = ipath_lcrop.joinpath(kname + ".txt")
|
||||
|
||||
if kpath_fcrop.exists() and kpath_tfrom.exists() and kpath_lcrop.exists():
|
||||
continue
|
||||
|
||||
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
|
||||
@@ -0,0 +1,81 @@
|
||||
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
|
||||
@@ -0,0 +1,31 @@
|
||||
|
||||
import os
|
||||
from pathlib2 import Path
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
|
||||
vpath_videos = sorted(path_data.glob("*"), reverse=False)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
|
||||
# IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# if iname not in IDs: continue
|
||||
ipath_fcrop = ipath_item.joinpath("frames_crop")
|
||||
ipath_tfrom = ipath_item.joinpath("frames_crop_tform")
|
||||
|
||||
|
||||
if ipath_fcrop.exists():
|
||||
cmd = f"rm -rf {str(ipath_fcrop)}"
|
||||
print("RUN: ", cmd)
|
||||
os.system(cmd)
|
||||
|
||||
if ipath_tfrom.exists():
|
||||
cmd = f"rm -rf {str(ipath_tfrom)}"
|
||||
print("RUN: ", cmd)
|
||||
os.system(cmd)
|
||||
Reference in new issue
Block a user