diff options
Diffstat (limited to 'megapixels/commands/cv/rois_to_pose.py')
| -rw-r--r-- | megapixels/commands/cv/rois_to_pose.py | 127 |
1 files changed, 127 insertions, 0 deletions
diff --git a/megapixels/commands/cv/rois_to_pose.py b/megapixels/commands/cv/rois_to_pose.py new file mode 100644 index 00000000..3877cecf --- /dev/null +++ b/megapixels/commands/cv/rois_to_pose.py @@ -0,0 +1,127 @@ +""" +Converts ROIs to pose: yaw, roll, pitch +""" + +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_files', required=True, + help='Input ROI CSV') +@click.option('-r', '--rois', 'opt_fp_rois', required=True, + help='Input ROI CSV') +@click.option('-m', '--media', 'opt_dir_media', required=True, + help='Input media directory') +@click.option('-o', '--output', 'opt_fp_out', required=True, + help='Output CSV') +@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_files, opt_fp_rois, opt_dir_media, opt_fp_out, 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 + from app.processors.face_landmarks import LandmarksDLIB + from app.processors.face_pose import FacePoseDLIB + + # ------------------------------------------------- + # init here + + log = logger_utils.Logger.getLogger() + + # init face processors + face_pose = FacePoseDLIB() + face_landmarks = LandmarksDLIB() + + # load datra + df_files = pd.read_csv(opt_fp_files) + df_rois = pd.read_csv(opt_fp_rois) + + if not opt_force and Path(opt_fp_out).exists(): + log.error('File exists. Use "-f / --force" to overwite') + return + + if opt_slice: + df_rois = df_rois[opt_slice[0]:opt_slice[1]] + + # ------------------------------------------------- + # process here + df_img_groups = df_rois.groupby('image_index') + log.debug('processing {:,} groups'.format(len(df_img_groups))) + + + poses = [] + + # iterate + #for df_roi_group_idx, df_roi_group in tqdm(df_roi_groups): + for image_index, df_img_group in tqdm(df_img_groups): + # make fp + #image_index = df_roi_group.image_index.values[0] + pds_file = df_files.iloc[image_index] + fp_im = join(opt_dir_media, pds_file.subdir, '{}.{}'.format(pds_file.fn, pds_file.ext)) + im = cv.imread(fp_im) + # get bbox + x = df_img_group.x.values[0] + y = df_img_group.y.values[0] + w = df_img_group.w.values[0] + h = df_img_group.h.values[0] + dim = im.shape[:2][::-1] + bbox = BBox.from_xywh(x, y, w, h).to_dim(dim) + # get pose + landmarks = face_landmarks.landmarks(im, bbox) + pose_data = face_pose.pose(landmarks, dim, project_points=opt_display) + pose_degrees = pose_data['degrees'] # only keep the degrees data + + # use the project point data if display flag set + if opt_display: + pts_im = pose_data['points_image'] + pts_model = pose_data['points_model'] + pt_nose = pose_data['point_nose'] + dst = im.copy() + face_pose.draw_pose(dst, pts_im, pts_model, pt_nose) + face_pose.draw_degrees(dst, pose_degrees) + # display to cv window + cv.imshow('', dst) + while True: + k = cv.waitKey(1) & 0xFF + if k == 27 or k == ord('q'): # ESC + cv.destroyAllWindows() + sys.exit() + elif k != 255: + # any key to continue + break + + # add image index and append to result CSV data + pose_degrees['image_index'] = image_index + poses.append(pose_degrees) + + + # save date + file_utils.mkdirs(opt_fp_out) + df = pd.DataFrame.from_dict(poses) + df.index.name = 'index' + df.to_csv(opt_fp_out)
\ No newline at end of file |
