Ashrafb commited on
Commit
68850f6
·
verified ·
1 Parent(s): ea8d774

Upload vtoonify_model_encoder_align_all_parallel.py

Browse files
vtoonify/model/encoder/vtoonify_model_encoder_align_all_parallel.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)