diff options
Diffstat (limited to 'megapixels/commands/processor/face_pose.py')
| -rw-r--r-- | megapixels/commands/processor/face_pose.py | 164 |
1 files changed, 164 insertions, 0 deletions
diff --git a/megapixels/commands/processor/face_pose.py b/megapixels/commands/processor/face_pose.py new file mode 100644 index 00000000..cb7ec56c --- /dev/null +++ b/megapixels/commands/processor/face_pose.py @@ -0,0 +1,164 @@ +""" +NB: This only works with the DLIB 68-point landmarks. + +Converts ROIs to pose: yaw, roll, pitch +pitch: looking down or up in yes gesture +roll: tilting head towards shoulder +yaw: twisting head left to right in no gesture + +""" + +""" +TODO +- check compatibility with MTCNN 68 point detector +- improve accuracy by using MTCNN 5-point +- refer to https://github.com/jerryhouuu/Face-Yaw-Roll-Pitch-from-Pose-Estimation-using-OpenCV/ +""" + +import click + +from app.settings import types +from app.utils import click_utils +from app.settings import app_cfg as cfg + +@click.command() +@click.option('-i', '--input', 'opt_fp_in', default=None, + help='Override enum input filename CSV') +@click.option('-o', '--output', 'opt_fp_out', default=None, + help='Override enum output filename CSV') +@click.option('-m', '--media', 'opt_dir_media', default=None, + help='Override enum media directory') +@click.option('--store', 'opt_data_store', + type=cfg.DataStoreVar, + default=click_utils.get_default(types.DataStore.HDD), + show_default=True, + help=click_utils.show_help(types.Dataset)) +@click.option('--dataset', 'opt_dataset', + type=cfg.DatasetVar, + required=True, + show_default=True, + help=click_utils.show_help(types.Dataset)) +@click.option('--size', 'opt_size', + type=(int, int), default=(300, 300), + help='Output image size') +@click.option('--slice', 'opt_slice', type=(int, int), default=(None, None), + help='Slice list of files') +@click.option('-f', '--force', 'opt_force', is_flag=True, + help='Force overwrite file') +@click.option('-d', '--display', 'opt_display', is_flag=True, + help='Display image for debugging') +@click.pass_context +def cli(ctx, opt_fp_in, opt_fp_out, opt_dir_media, opt_data_store, opt_dataset, opt_size, + opt_slice, opt_force, opt_display): + """Converts ROIs to pose: roll, yaw, pitch""" + + import sys + import os + from os.path import join + from pathlib import Path + from glob import glob + + from tqdm import tqdm + import numpy as np + import dlib # must keep a local reference for dlib + import cv2 as cv + import pandas as pd + + from app.models.bbox import BBox + from app.utils import logger_utils, file_utils, im_utils, display_utils, draw_utils + from app.processors.face_landmarks import Dlib2D_68 + from app.processors.face_pose import FacePoseDLIB + from app.models.data_store import DataStore + + # ------------------------------------------------- + # init here + + log = logger_utils.Logger.getLogger() + + # set data_store + data_store = DataStore(opt_data_store, opt_dataset) + + # get filepath out + fp_out = data_store.metadata(types.Metadata.FACE_POSE) if opt_fp_out is None else opt_fp_out + if not opt_force and Path(fp_out).exists(): + log.error('File exists. Use "-f / --force" to overwite') + return + + # init face processors + face_pose = FacePoseDLIB() + face_landmarks = Dlib2D_68() + + # ------------------------------------------------- + # load data + + fp_record = data_store.metadata(types.Metadata.FILE_RECORD) + df_record = pd.read_csv(fp_record, dtype=cfg.FILE_RECORD_DTYPES).set_index('index') + # load ROI data + fp_roi = data_store.metadata(types.Metadata.FACE_ROI) + df_roi = pd.read_csv(fp_roi).set_index('index') + # slice if you want + if opt_slice: + df_roi = df_roi[opt_slice[0]:opt_slice[1]] + # group by image index (speedup if multiple faces per image) + df_img_groups = df_roi.groupby('record_index') + log.debug('processing {:,} groups'.format(len(df_img_groups))) + + # store poses and convert to DataFrame + results = [] + + # ------------------------------------------------- + # iterate groups with file/record index as key + for record_index, df_img_group in tqdm(df_img_groups): + + # access the file_record + file_record = df_record.iloc[record_index] # pands.DataSeries + + # load image + fp_im = data_store.face(file_record.subdir, file_record.fn, file_record.ext) + im = cv.imread(fp_im) + im_resized = im_utils.resize(im, width=opt_size[0], height=opt_size[1]) + + # iterate image group dataframe with roi index as key + for roi_index, df_img in df_img_group.iterrows(): + + # get bbox + x, y, w, h = df_img.x, df_img.y, df_img.w, df_img.h + #dim = (file_record.width, file_record.height) + dim = im_resized.shape[:2][::-1] + bbox_norm = BBox.from_xywh(x, y, w, h) + bbox_dim = bbox_norm.to_dim(dim) + + # get pose + landmarks = face_landmarks.landmarks(im_resized, bbox_norm) + pose_data = face_pose.pose(landmarks, dim) + #pose_degrees = pose_data['degrees'] # only keep the degrees data + #pose_degrees['points_nose'] = pose_data + + # draw landmarks if optioned + if opt_display: + draw_utils.draw_pose(im_resized, pose_data['point_nose'], pose_data['points']) + draw_utils.draw_degrees(im_resized, pose_data) + cv.imshow('', im_resized) + display_utils.handle_keyboard() + + # add image index and append to result CSV data + pose_data['roi_index'] = roi_index + for k, v in pose_data['points'].items(): + pose_data[f'point_{k}_x'] = v[0] / dim[0] + pose_data[f'point_{k}_y'] = v[1] / dim[1] + + # rearrange data structure for DataFrame + pose_data.pop('points') + pose_data['point_nose_x'] = pose_data['point_nose'][0] / dim[0] + pose_data['point_nose_y'] = pose_data['point_nose'][1] / dim[1] + pose_data.pop('point_nose') + results.append(pose_data) + + # create DataFrame and save to CSV + file_utils.mkdirs(fp_out) + df = pd.DataFrame.from_dict(results) + df.index.name = 'index' + df.to_csv(fp_out) + + # save script + file_utils.write_text(' '.join(sys.argv), '{}.sh'.format(fp_out))
\ No newline at end of file |
