update
This commit is contained in:
1 parent
4a53051fee
commit
039ec3cf52
179 files changed
+22667
No files matched your search
@@ -0,0 +1,218 @@
|
||||
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%200 == 0:
|
||||
logger.info(f"load jpath_frame --> {jpath_frame}")
|
||||
|
||||
# if j < 19300: continu
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
# logger.info(f"estimate_transform - 3")
|
||||
# tform_params dytpe = float64, shape = (3, 3)
|
||||
tform = estimate_transform('similarity', src_pts, DST_PTS)
|
||||
|
||||
# logger.info(f"estimate_transform - 3 - 2")
|
||||
|
||||
## 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 = 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()} ")
|
||||
|
||||
# logger.info(f"save np - 4")
|
||||
np.save(kpath_tfrom, tform.params)
|
||||
np.savetxt(kpath_lcrop, cropped_ldmk, fmt=" %3d")
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
actor = "Actor7"
|
||||
sub_folder = "processing" # smile, processing, processing2
|
||||
|
||||
# logger
|
||||
logger = Logger(f"./data/{actor}", postfix=f"crop-transform-{sub_folder}")
|
||||
|
||||
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}")
|
||||
path_same_bbox = 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")
|
||||
|
||||
# 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[10:]):
|
||||
iname = ipath_item.stem
|
||||
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# if iname not in ["4R3A0139"]: 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 frame have exsit
|
||||
if num_frame < 50:
|
||||
logger.info(f"\n Skip: num_frame = {num_frame} is small!")
|
||||
continue
|
||||
|
||||
# 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
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user