Ashrafb commited on
Commit
cdb0ff6
·
verified ·
1 Parent(s): c175957

Update vtoonify/model/encoder/align_all_parallel.py

Browse files
vtoonify/model/encoder/align_all_parallel.py CHANGED
@@ -10,17 +10,11 @@ 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!')
@@ -28,89 +22,43 @@ def get_landmark(filepath, face_detector):
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)
@@ -124,19 +72,23 @@ def chunks(lst, 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
 
@@ -166,16 +118,16 @@ def run(args):
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)
 
10
  import multiprocessing as mp
11
  import math
12
 
13
+ def get_landmark(image, face_detector):
14
+ """Get landmark with InsightFace
15
+ :return: np.array shape=(106, 2) for 106-point landmarks
16
  """
17
+ faces = face_detector.get(image)
 
 
 
 
 
 
18
 
19
  if len(faces) == 0:
20
  print('Error: no face detected!')
 
22
 
23
  # Assume the first detected face is the target
24
  face = faces[0]
25
+ lm = face.landmark_2d_106
26
  return lm
27
 
28
+ def align_face(image, face_detector):
29
  """
30
+ :param image: np.ndarray
31
  :return: PIL Image
32
  """
33
+ lm = get_landmark(image, face_detector)
34
  if lm is None:
35
+ return None
 
 
 
 
 
36
 
37
+ # Calculate auxiliary vectors for alignment
38
+ eye_left = np.mean(lm[36:42], axis=0)
39
+ eye_right = np.mean(lm[42:48], axis=0)
40
+ mouth_left = lm[48]
41
+ mouth_right = lm[54]
42
+
43
+ # Calculate transformation parameters
44
+ eye_center = (eye_left + eye_right) / 2
45
+ mouth_center = (mouth_left + mouth_right) / 2
46
  eye_to_eye = eye_right - eye_left
47
+ eye_to_mouth = mouth_center - eye_center
 
 
 
48
 
49
+ # Define the transformation matrix
50
  x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
51
  x /= np.hypot(*x)
52
+ x *= np.hypot(*eye_to_eye) * 2.0
53
  y = np.flipud(x) * [-1, 1]
54
+ c = eye_center + eye_to_mouth * 0.1
55
  quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
56
  qsize = np.hypot(*x) * 2
57
 
58
+ # Transform and crop the image
 
 
 
 
 
 
59
  transform_size = 256
60
+ output_size = 256
61
+ img = PIL.Image.fromarray(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)
63
  if output_size < transform_size:
64
  img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS)
 
72
 
73
  def extract_on_paths(file_paths, face_detector):
74
  pid = mp.current_process().name
75
+ print(f'\t{pid} is starting to extract on #{len(file_paths)} images')
76
  tot_count = len(file_paths)
77
  count = 0
78
  for file_path, res_path in file_paths:
79
  count += 1
80
  if count % 100 == 0:
81
+ print(f'{pid} done with {count}/{tot_count}')
82
  try:
83
+ img = cv2.imread(file_path, cv2.IMREAD_COLOR)
84
+ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
85
+ res = align_face(img_rgb, face_detector)
86
+ if res is not None:
87
+ res = res.convert('RGB')
88
+ os.makedirs(os.path.dirname(res_path), exist_ok=True)
89
+ res.save(res_path)
90
+ except Exception as e:
91
+ print(f"Error processing {file_path}: {e}")
92
  continue
93
  print('\tDone!')
94
 
 
118
  file_chunks = list(chunks(file_paths, int(math.ceil(len(file_paths) / args.num_threads))))
119
  print(len(file_chunks))
120
  pool = mp.Pool(args.num_threads)
121
+ print(f'Running on {len(file_paths)} paths\nHere we goooo')
122
  tic = time.time()
123
  pool.starmap(extract_on_paths, [(chunk, face_detector) for chunk in file_chunks])
124
  toc = time.time()
125
+ print(f'Mischief managed in {toc - tic}s')
126
 
127
  if __name__ == '__main__':
128
  # Initialize InsightFace
129
  face_detector = insightface.app.FaceAnalysis()
130
+ face_detector.prepare(ctx_id=-1, det_size=(640, 640)) # Use -1 for CPU
131
 
132
  args = parse_args()
133
  run(args)