Ashrafb commited on
Commit
3419c0c
·
verified ·
1 Parent(s): f647f39

Update vtoonify/model/encoder/align_all_parallel.py

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