Spaces:
Runtime error
Runtime error
Arnaudding001
commited on
Commit
•
5b1f1d2
1
Parent(s):
bed6b95
Create encoder_align_all_parallel.py
Browse files- encoder_align_all_parallel.py +217 -0
encoder_align_all_parallel.py
ADDED
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset)
|
3 |
+
author: lzhbrian (https://lzhbrian.me)
|
4 |
+
date: 2020.1.5
|
5 |
+
note: code is heavily borrowed from
|
6 |
+
https://github.com/NVlabs/ffhq-dataset
|
7 |
+
http://dlib.net/face_landmark_detection.py.html
|
8 |
+
|
9 |
+
requirements:
|
10 |
+
apt install cmake
|
11 |
+
conda install Pillow numpy scipy
|
12 |
+
pip install dlib
|
13 |
+
# download face landmark model from:
|
14 |
+
# http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
|
15 |
+
"""
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
import time
|
18 |
+
import numpy as np
|
19 |
+
import PIL
|
20 |
+
import PIL.Image
|
21 |
+
import os
|
22 |
+
import scipy
|
23 |
+
import scipy.ndimage
|
24 |
+
import dlib
|
25 |
+
import multiprocessing as mp
|
26 |
+
import math
|
27 |
+
|
28 |
+
#from configs.paths_config import model_paths
|
29 |
+
SHAPE_PREDICTOR_PATH = 'shape_predictor_68_face_landmarks.dat'#model_paths["shape_predictor"]
|
30 |
+
|
31 |
+
|
32 |
+
def get_landmark(filepath, predictor):
|
33 |
+
"""get landmark with dlib
|
34 |
+
:return: np.array shape=(68, 2)
|
35 |
+
"""
|
36 |
+
detector = dlib.get_frontal_face_detector()
|
37 |
+
if type(filepath) == str:
|
38 |
+
img = dlib.load_rgb_image(filepath)
|
39 |
+
else:
|
40 |
+
img = filepath
|
41 |
+
dets = detector(img, 1)
|
42 |
+
|
43 |
+
if len(dets) == 0:
|
44 |
+
print('Error: no face detected!')
|
45 |
+
return None
|
46 |
+
|
47 |
+
shape = None
|
48 |
+
for k, d in enumerate(dets):
|
49 |
+
shape = predictor(img, d)
|
50 |
+
|
51 |
+
if shape is None:
|
52 |
+
print('Error: No face detected! If you are sure there are faces in your input, you may rerun the code several times until the face is detected. Sometimes the detector is unstable.')
|
53 |
+
t = list(shape.parts())
|
54 |
+
a = []
|
55 |
+
for tt in t:
|
56 |
+
a.append([tt.x, tt.y])
|
57 |
+
lm = np.array(a)
|
58 |
+
return lm
|
59 |
+
|
60 |
+
|
61 |
+
def align_face(filepath, predictor):
|
62 |
+
"""
|
63 |
+
:param filepath: str
|
64 |
+
:return: PIL Image
|
65 |
+
"""
|
66 |
+
|
67 |
+
lm = get_landmark(filepath, predictor)
|
68 |
+
if lm is None:
|
69 |
+
return None
|
70 |
+
|
71 |
+
lm_chin = lm[0: 17] # left-right
|
72 |
+
lm_eyebrow_left = lm[17: 22] # left-right
|
73 |
+
lm_eyebrow_right = lm[22: 27] # left-right
|
74 |
+
lm_nose = lm[27: 31] # top-down
|
75 |
+
lm_nostrils = lm[31: 36] # top-down
|
76 |
+
lm_eye_left = lm[36: 42] # left-clockwise
|
77 |
+
lm_eye_right = lm[42: 48] # left-clockwise
|
78 |
+
lm_mouth_outer = lm[48: 60] # left-clockwise
|
79 |
+
lm_mouth_inner = lm[60: 68] # left-clockwise
|
80 |
+
|
81 |
+
# Calculate auxiliary vectors.
|
82 |
+
eye_left = np.mean(lm_eye_left, axis=0)
|
83 |
+
eye_right = np.mean(lm_eye_right, axis=0)
|
84 |
+
eye_avg = (eye_left + eye_right) * 0.5
|
85 |
+
eye_to_eye = eye_right - eye_left
|
86 |
+
mouth_left = lm_mouth_outer[0]
|
87 |
+
mouth_right = lm_mouth_outer[6]
|
88 |
+
mouth_avg = (mouth_left + mouth_right) * 0.5
|
89 |
+
eye_to_mouth = mouth_avg - eye_avg
|
90 |
+
|
91 |
+
# Choose oriented crop rectangle.
|
92 |
+
x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
|
93 |
+
x /= np.hypot(*x)
|
94 |
+
x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
|
95 |
+
y = np.flipud(x) * [-1, 1]
|
96 |
+
c = eye_avg + eye_to_mouth * 0.1
|
97 |
+
quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
|
98 |
+
qsize = np.hypot(*x) * 2
|
99 |
+
|
100 |
+
# read image
|
101 |
+
if type(filepath) == str:
|
102 |
+
img = PIL.Image.open(filepath)
|
103 |
+
else:
|
104 |
+
img = PIL.Image.fromarray(filepath)
|
105 |
+
|
106 |
+
output_size = 256
|
107 |
+
transform_size = 256
|
108 |
+
enable_padding = True
|
109 |
+
|
110 |
+
# Shrink.
|
111 |
+
shrink = int(np.floor(qsize / output_size * 0.5))
|
112 |
+
if shrink > 1:
|
113 |
+
rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
|
114 |
+
img = img.resize(rsize, PIL.Image.ANTIALIAS)
|
115 |
+
quad /= shrink
|
116 |
+
qsize /= shrink
|
117 |
+
|
118 |
+
# Crop.
|
119 |
+
border = max(int(np.rint(qsize * 0.1)), 3)
|
120 |
+
crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
|
121 |
+
int(np.ceil(max(quad[:, 1]))))
|
122 |
+
crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
|
123 |
+
min(crop[3] + border, img.size[1]))
|
124 |
+
if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
|
125 |
+
img = img.crop(crop)
|
126 |
+
quad -= crop[0:2]
|
127 |
+
|
128 |
+
# Pad.
|
129 |
+
pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
|
130 |
+
int(np.ceil(max(quad[:, 1]))))
|
131 |
+
pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
|
132 |
+
max(pad[3] - img.size[1] + border, 0))
|
133 |
+
if enable_padding and max(pad) > border - 4:
|
134 |
+
pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
|
135 |
+
img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
|
136 |
+
h, w, _ = img.shape
|
137 |
+
y, x, _ = np.ogrid[:h, :w, :1]
|
138 |
+
mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
|
139 |
+
1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
|
140 |
+
blur = qsize * 0.02
|
141 |
+
img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
|
142 |
+
img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
|
143 |
+
img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
|
144 |
+
quad += pad[:2]
|
145 |
+
|
146 |
+
# Transform.
|
147 |
+
img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)
|
148 |
+
if output_size < transform_size:
|
149 |
+
img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS)
|
150 |
+
|
151 |
+
# Save aligned image.
|
152 |
+
return img
|
153 |
+
|
154 |
+
|
155 |
+
def chunks(lst, n):
|
156 |
+
"""Yield successive n-sized chunks from lst."""
|
157 |
+
for i in range(0, len(lst), n):
|
158 |
+
yield lst[i:i + n]
|
159 |
+
|
160 |
+
|
161 |
+
def extract_on_paths(file_paths):
|
162 |
+
predictor = dlib.shape_predictor(SHAPE_PREDICTOR_PATH)
|
163 |
+
pid = mp.current_process().name
|
164 |
+
print('\t{} is starting to extract on #{} images'.format(pid, len(file_paths)))
|
165 |
+
tot_count = len(file_paths)
|
166 |
+
count = 0
|
167 |
+
for file_path, res_path in file_paths:
|
168 |
+
count += 1
|
169 |
+
if count % 100 == 0:
|
170 |
+
print('{} done with {}/{}'.format(pid, count, tot_count))
|
171 |
+
try:
|
172 |
+
res = align_face(file_path, predictor)
|
173 |
+
res = res.convert('RGB')
|
174 |
+
os.makedirs(os.path.dirname(res_path), exist_ok=True)
|
175 |
+
res.save(res_path)
|
176 |
+
except Exception:
|
177 |
+
continue
|
178 |
+
print('\tDone!')
|
179 |
+
|
180 |
+
|
181 |
+
def parse_args():
|
182 |
+
parser = ArgumentParser(add_help=False)
|
183 |
+
parser.add_argument('--num_threads', type=int, default=1)
|
184 |
+
parser.add_argument('--root_path', type=str, default='')
|
185 |
+
args = parser.parse_args()
|
186 |
+
return args
|
187 |
+
|
188 |
+
|
189 |
+
def run(args):
|
190 |
+
root_path = args.root_path
|
191 |
+
out_crops_path = root_path + '_crops'
|
192 |
+
if not os.path.exists(out_crops_path):
|
193 |
+
os.makedirs(out_crops_path, exist_ok=True)
|
194 |
+
|
195 |
+
file_paths = []
|
196 |
+
for root, dirs, files in os.walk(root_path):
|
197 |
+
for file in files:
|
198 |
+
file_path = os.path.join(root, file)
|
199 |
+
fname = os.path.join(out_crops_path, os.path.relpath(file_path, root_path))
|
200 |
+
res_path = '{}.jpg'.format(os.path.splitext(fname)[0])
|
201 |
+
if os.path.splitext(file_path)[1] == '.txt' or os.path.exists(res_path):
|
202 |
+
continue
|
203 |
+
file_paths.append((file_path, res_path))
|
204 |
+
|
205 |
+
file_chunks = list(chunks(file_paths, int(math.ceil(len(file_paths) / args.num_threads))))
|
206 |
+
print(len(file_chunks))
|
207 |
+
pool = mp.Pool(args.num_threads)
|
208 |
+
print('Running on {} paths\nHere we goooo'.format(len(file_paths)))
|
209 |
+
tic = time.time()
|
210 |
+
pool.map(extract_on_paths, file_chunks)
|
211 |
+
toc = time.time()
|
212 |
+
print('Mischief managed in {}s'.format(toc - tic))
|
213 |
+
|
214 |
+
|
215 |
+
if __name__ == '__main__':
|
216 |
+
args = parse_args()
|
217 |
+
run(args)
|