Luisgust commited on
Commit
c6d57da
·
verified ·
1 Parent(s): 6cb4be4

Create vtoonify/model/encoder/align_all_parallel.py

Browse files
vtoonify/model/encoder/align_all_parallel.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from argparse import ArgumentParser
3
+ import time
4
+ import numpy as np
5
+ import PIL
6
+ import PIL.Image
7
+ import os
8
+ import scipy
9
+ import scipy.ndimage
10
+ import insightface
11
+ import multiprocessing as mp
12
+ import math
13
+
14
+ def get_landmark(filepath, face_detector):
15
+ """get landmark with InsightFace
16
+ :return: np.array shape=(68, 2)
17
+ """
18
+ if isinstance(filepath, str):
19
+ img = PIL.Image.open(filepath)
20
+ img = np.array(img)
21
+ else:
22
+ img = filepath
23
+
24
+ faces = face_detector.get(img)
25
+
26
+ if len(faces) == 0:
27
+ print('Error: no face detected!')
28
+ return None
29
+
30
+ # Assume the first detected face is the target
31
+ face = faces[0]
32
+ lm = face.landmark_2d_106[:, :2] # Use 106-point landmarks
33
+ return lm
34
+
35
+ def align_face(filepath, face_detector):
36
+ """
37
+ :param filepath: str
38
+ :return: PIL Image
39
+ """
40
+ lm = get_landmark(filepath, face_detector)
41
+ if lm is None:
42
+ return None
43
+
44
+ # Use the same landmark indices as before
45
+ lm_eye_left = lm[36: 42] # left-clockwise
46
+ lm_eye_right = lm[42: 48] # left-clockwise
47
+ lm_mouth_outer = lm[48: 60] # left-clockwise
48
+
49
+ # Calculate auxiliary vectors.
50
+ eye_left = np.mean(lm_eye_left, axis=0)
51
+ eye_right = np.mean(lm_eye_right, axis=0)
52
+ eye_avg = (eye_left + eye_right) * 0.5
53
+ eye_to_eye = eye_right - eye_left
54
+ mouth_left = lm_mouth_outer[0]
55
+ mouth_right = lm_mouth_outer[6]
56
+ mouth_avg = (mouth_left + mouth_right) * 0.5
57
+ eye_to_mouth = mouth_avg - eye_avg
58
+
59
+ # Choose oriented crop rectangle.
60
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
61
+ x /= np.hypot(*x)
62
+ x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
63
+ y = np.flipud(x) * [-1, 1]
64
+ c = eye_avg + eye_to_mouth * 0.1
65
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
66
+ qsize = np.hypot(*x) * 2
67
+
68
+ # read image
69
+ if isinstance(filepath, str):
70
+ img = PIL.Image.open(filepath)
71
+ else:
72
+ img = PIL.Image.fromarray(filepath)
73
+
74
+ output_size = 256
75
+ transform_size = 256
76
+ enable_padding = True
77
+
78
+ # Shrink.
79
+ shrink = int(np.floor(qsize / output_size * 0.5))
80
+ if shrink > 1:
81
+ rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
82
+ img = img.resize(rsize, PIL.Image.ANTIALIAS)
83
+ quad /= shrink
84
+ qsize /= shrink
85
+
86
+ # Crop.
87
+ border = max(int(np.rint(qsize * 0.1)), 3)
88
+ crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
89
+ int(np.ceil(max(quad[:, 1]))))
90
+ crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
91
+ min(crop[3] + border, img.size[1]))
92
+ if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
93
+ img = img.crop(crop)
94
+ quad -= crop[0:2]
95
+
96
+ # Pad.
97
+ pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
98
+ int(np.ceil(max(quad[:, 1]))))
99
+ pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
100
+ max(pad[3] - img.size[1] + border, 0))
101
+ if enable_padding and max(pad) > border - 4:
102
+ pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
103
+ img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
104
+ h, w, _ = img.shape
105
+ y, x, _ = np.ogrid[:h, :w, :1]
106
+ mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
107
+ 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
108
+ blur = qsize * 0.02
109
+ img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
110
+ img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
111
+ img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
112
+ quad += pad[:2]
113
+
114
+ # Transform.
115
+ img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)
116
+ if output_size < transform_size:
117
+ img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS)
118
+
119
+ return img
120
+
121
+ def chunks(lst, n):
122
+ """Yield successive n-sized chunks from lst."""
123
+ for i in range(0, len(lst), n):
124
+ yield lst[i:i + n]
125
+
126
+ def extract_on_paths(file_paths, face_detector):
127
+ pid = mp.current_process().name
128
+ print('\t{} is starting to extract on #{} images'.format(pid, len(file_paths)))
129
+ tot_count = len(file_paths)
130
+ count = 0
131
+ for file_path, res_path in file_paths:
132
+ count += 1
133
+ if count % 100 == 0:
134
+ print('{} done with {}/{}'.format(pid, count, tot_count))
135
+ try:
136
+ res = align_face(file_path, face_detector)
137
+ res = res.convert('RGB')
138
+ os.makedirs(os.path.dirname(res_path), exist_ok=True)
139
+ res.save(res_path)
140
+ except Exception:
141
+ continue
142
+ print('\tDone!')
143
+
144
+ def parse_args():
145
+ parser = ArgumentParser(add_help=False)
146
+ parser.add_argument('--num_threads', type=int, default=1)
147
+ parser.add_argument('--root_path', type=str, default='')
148
+ args = parser.parse_args()
149
+ return args
150
+
151
+ def run(args):
152
+ root_path = args.root_path
153
+ out_crops_path = root_path + '_crops'
154
+ if not os.path.exists(out_crops_path):
155
+ os.makedirs(out_crops_path, exist_ok=True)
156
+
157
+ file_paths = []
158
+ for root, dirs, files in os.walk(root_path):
159
+ for file in files:
160
+ file_path = os.path.join(root, file)
161
+ fname = os.path.join(out_crops_path, os.path.relpath(file_path, root_path))
162
+ res_path = '{}.jpg'.format(os.path.splitext(fname)[0])
163
+ if os.path.splitext(file_path)[1] == '.txt' or os.path.exists(res_path):
164
+ continue
165
+ file_paths.append((file_path, res_path))
166
+
167
+ file_chunks = list(chunks(file_paths, int(math.ceil(len(file_paths) / args.num_threads))))
168
+ print(len(file_chunks))
169
+ pool = mp.Pool(args.num_threads)
170
+ print('Running on {} paths\nHere we goooo'.format(len(file_paths)))
171
+ tic = time.time()
172
+ pool.starmap(extract_on_paths, [(chunk, face_detector) for chunk in file_chunks])
173
+ toc = time.time()
174
+ print('Mischief managed in {}s'.format(toc - tic))
175
+
176
+ if __name__ == '__main__':
177
+ # Initialize InsightFace
178
+ face_detector = insightface.app.FaceAnalysis()
179
+ face_detector.prepare(ctx_id=-1, det_size=(640, 640)) # ctx_id=-1 for CPU
180
+
181
+ args = parse_args()
182
+ run(args)