summaryrefslogtreecommitdiff
path: root/megapixels/commands/cv/face_pose_to_csv.py
blob: ca7489de4c37e8783f6983197bc8b80042f9beb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
Crop images to prepare for training
"""

import click
# from PIL import Image, ImageOps, ImageFilter, ImageDraw

from app.settings import types
from app.utils import click_utils
from app.settings import app_cfg as cfg

color_filters = {'color': 1, 'gray': 2, 'all': 3}

@click.command()
@click.option('-f', '--files', '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.pass_context
def cli(ctx, opt_fp_files, opt_fp_rois, opt_dir_media, opt_fp_out, opt_size, 
  opt_slice, opt_force):
  """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()

  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_roi_groups = df_rois.groupby('index')
  log.debug('processing {:,} groups'.format(len(df_roi_groups)))


  poses = []

  #for df_roi_group in tqdm(df_roi_groups.itertuples(), total=len(df_roi_groups)):
  for df_roi_group_idx, df_roi_group in tqdm(df_roi_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_roi_group.x.values[0]
    y = df_roi_group.y.values[0]
    w = df_roi_group.w.values[0]
    h = df_roi_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 = face_pose.pose(landmarks, dim)
    pose['image_index'] = image_index
    poses.append(pose)


  # save date
  file_utils.mkdirs(opt_fp_out)
  df = pd.DataFrame.from_dict(poses)
  df.index.name = 'index'
  df.to_csv(opt_fp_out)