summaryrefslogtreecommitdiff
path: root/megapixels/commands/cv/face_landmark_3d_68.py
blob: a2d14d72138ff9201889b0b80da0bbb5b78b40da (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""

"""

import click

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('-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('-d', '--detector', 'opt_detector_type',
  type=cfg.FaceLandmark3D_68Var,
  default=click_utils.get_default(types.FaceLandmark3D_68.FACE_ALIGNMENT),
  help=click_utils.show_help(types.FaceLandmark3D_68))
@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_detector_type,
  opt_size, opt_slice, opt_force, opt_display):
  """Generate 3D 68-point landmarks"""
  
  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 cv2 as cv
  import pandas as pd

  from app.utils import logger_utils, file_utils, im_utils, display_utils, draw_utils
  from app.utils import plot_utils
  from app.processors import face_landmarks
  from app.models.data_store import DataStore
  from app.models.bbox import BBox

  # --------------------------------------------------------------------------
  # init here

  log = logger_utils.Logger.getLogger()
  log.warn('not normalizing points')
  # init filepaths
  data_store = DataStore(opt_data_store, opt_dataset)
  # set file output path
  metadata_type = types.Metadata.FACE_LANDMARK_3D_68
  fp_out = data_store.metadata(metadata_type) 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 landmark processors
  if opt_detector_type == types.FaceLandmark3D_68.FACE_ALIGNMENT:
    # use FaceAlignment 68 point 3D detector
    landmark_detector = face_landmarks.FaceAlignment3D_68()
  else:
    log.error('{} not yet implemented'.format(opt_detector_type.name))
    return

  log.info(f'Using landmark detector: {opt_detector_type.name}')  

  # -------------------------------------------------------------------------
  # load data

  fp_record = data_store.metadata(types.Metadata.FILE_RECORD)  # file_record.csv
  df_record = pd.read_csv(fp_record).set_index('index')
  fp_roi = data_store.metadata(types.Metadata.FACE_ROI)  # face_roi.csv
  df_roi = pd.read_csv(fp_roi).set_index('index')
  if opt_slice:
    df_roi = df_roi[opt_slice[0]:opt_slice[1]]  # slice if you want
  df_img_groups = df_roi.groupby('record_index')  # groups by image index (load once)
  log.debug('processing {:,} groups'.format(len(df_img_groups)))

  # store landmarks in list
  results = []

  # iterate groups with file/record index as key
  for record_index, df_img_group in tqdm(df_img_groups):
    
    # acces file record
    ds_record = df_record.iloc[record_index]
    
    # load image
    fp_im = data_store.face(ds_record.subdir, ds_record.fn, ds_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 = im_resized.shape[:2][::-1]
      bbox = BBox.from_xywh(x, y, w, h).to_dim(dim)

      # get landmark points
      points = landmark_detector.landmarks(im_resized, bbox)
      # NB can't really normalize these points, but are normalized against 3D space
      #points_norm = landmark_detector.normalize(points, dim)  # normalized using 200
      points_flattenend = landmark_detector.flatten(points)

      # display to screen if optioned
      if opt_display:
        draw_utils.draw_landmarks3D(im_resized, points)
        draw_utils.draw_bbox(im_resized, bbox)
        cv.imshow('', im_resized)
        display_utils.handle_keyboard()

        #plot_utils.generate_3d_landmark_anim(points, '/home/adam/Downloads/3d.gif')

      results.append(points_flattenend)

  # 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))