miguelmuzo commited on
Commit
c5a8345
·
verified ·
1 Parent(s): d456974

Create shape_predictor.py

Browse files
Files changed (1) hide show
  1. utils/shape_predictor.py +193 -0
utils/shape_predictor.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import PIL
5
+ import dlib
6
+ import numpy as np
7
+ import scipy
8
+ import scipy.ndimage
9
+ import torch
10
+ from PIL import Image
11
+ from torchvision import transforms as T
12
+
13
+ from utils.drive import open_url
14
+
15
+ """
16
+ brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset)
17
+ author: lzhbrian (https://lzhbrian.me)
18
+ date: 2020.1.5
19
+ note: code is heavily borrowed from
20
+ https://github.com/NVlabs/ffhq-dataset
21
+ http://dlib.net/face_landmark_detection.py.html
22
+ requirements:
23
+ apt install cmake
24
+ conda install Pillow numpy scipy
25
+ pip install dlib
26
+ # download face landmark model from:
27
+ # http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
28
+ """
29
+
30
+
31
+ def get_landmark(filepath, predictor):
32
+ """get landmark with dlib
33
+ :return: np.array shape=(68, 2)
34
+ """
35
+ detector = dlib.get_frontal_face_detector()
36
+
37
+ img = dlib.load_rgb_image(filepath)
38
+ dets = detector(img, 1)
39
+ filepath = Path(filepath)
40
+ print(f"{filepath.name}: Number of faces detected: {len(dets)}")
41
+ shapes = [predictor(img, d) for k, d in enumerate(dets)]
42
+
43
+ lms = [np.array([[tt.x, tt.y] for tt in shape.parts()]) for shape in shapes]
44
+
45
+ return lms
46
+
47
+
48
+ def get_landmark_from_tensors(tensors: list[torch.Tensor | Image.Image | np.ndarray], predictor):
49
+ detector = dlib.get_frontal_face_detector()
50
+ transform = T.ToPILImage()
51
+ images = []
52
+ lms = []
53
+
54
+ for k, tensor in enumerate(tensors):
55
+ if isinstance(tensor, torch.Tensor):
56
+ img_pil = transform(tensor)
57
+ else:
58
+ img_pil = tensor
59
+ img = np.array(img_pil)
60
+ images.append(img_pil)
61
+
62
+ dets = detector(img, 1)
63
+ if len(dets) == 0:
64
+ raise ValueError(f"No faces detected in the image {k}.")
65
+ elif len(dets) == 1:
66
+ print(f"Number of faces detected: {len(dets)}")
67
+ else:
68
+ print(f"Number of faces detected: {len(dets)}, get largest face")
69
+
70
+ # Find the largest face
71
+ dets = sorted(dets, key=lambda det: det.width() * det.height(), reverse=True)
72
+ shape = predictor(img, dets[0])
73
+ lm = np.array([[tt.x, tt.y] for tt in shape.parts()])
74
+ lms.append(lm)
75
+
76
+ return images, lms
77
+
78
+
79
+ def align_face(data, predictor=None, is_filepath=False, return_tensors=True):
80
+ """
81
+ :param data: filepath or list torch Tensors
82
+ :return: list of PIL Images
83
+ """
84
+ if predictor is None:
85
+ predictor_path = 'shape_predictor_68_face_landmarks.dat'
86
+
87
+ if not os.path.isfile(predictor_path):
88
+ print("Downloading Shape Predictor")
89
+ data_io = open_url("https://drive.google.com/uc?id=1huhv8PYpNNKbGCLOaYUjOgR1pY5pmbJx")
90
+ with open(predictor_path, 'wb') as f:
91
+ f.write(data_io.getbuffer())
92
+
93
+ predictor = dlib.shape_predictor(predictor_path)
94
+
95
+ if is_filepath:
96
+ lms = get_landmark(data, predictor)
97
+ else:
98
+ if not isinstance(data, list):
99
+ data = [data]
100
+ images, lms = get_landmark_from_tensors(data, predictor)
101
+
102
+ imgs = []
103
+ for num_img, lm in enumerate(lms):
104
+ lm_chin = lm[0: 17] # left-right
105
+ lm_eyebrow_left = lm[17: 22] # left-right
106
+ lm_eyebrow_right = lm[22: 27] # left-right
107
+ lm_nose = lm[27: 31] # top-down
108
+ lm_nostrils = lm[31: 36] # top-down
109
+ lm_eye_left = lm[36: 42] # left-clockwise
110
+ lm_eye_right = lm[42: 48] # left-clockwise
111
+ lm_mouth_outer = lm[48: 60] # left-clockwise
112
+ lm_mouth_inner = lm[60: 68] # left-clockwise
113
+
114
+ # Calculate auxiliary vectors.
115
+ eye_left = np.mean(lm_eye_left, axis=0)
116
+ eye_right = np.mean(lm_eye_right, axis=0)
117
+ eye_avg = (eye_left + eye_right) * 0.5
118
+ eye_to_eye = eye_right - eye_left
119
+ mouth_left = lm_mouth_outer[0]
120
+ mouth_right = lm_mouth_outer[6]
121
+ mouth_avg = (mouth_left + mouth_right) * 0.5
122
+ eye_to_mouth = mouth_avg - eye_avg
123
+
124
+ # Choose oriented crop rectangle.
125
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
126
+ x /= np.hypot(*x)
127
+ x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
128
+ y = np.flipud(x) * [-1, 1]
129
+ c = eye_avg + eye_to_mouth * 0.1
130
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
131
+ qsize = np.hypot(*x) * 2
132
+
133
+ # read image
134
+ if is_filepath:
135
+ img = PIL.Image.open(data)
136
+ else:
137
+ img = images[num_img]
138
+
139
+ output_size = 1024
140
+ # output_size = 256
141
+ transform_size = 4096
142
+ enable_padding = True
143
+
144
+ # Shrink.
145
+ shrink = int(np.floor(qsize / output_size * 0.5))
146
+ if shrink > 1:
147
+ rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
148
+ img = img.resize(rsize, PIL.Image.ANTIALIAS)
149
+ quad /= shrink
150
+ qsize /= shrink
151
+
152
+ # Crop.
153
+ border = max(int(np.rint(qsize * 0.1)), 3)
154
+ crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
155
+ int(np.ceil(max(quad[:, 1]))))
156
+ crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
157
+ min(crop[3] + border, img.size[1]))
158
+ if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
159
+ img = img.crop(crop)
160
+ quad -= crop[0:2]
161
+
162
+ # Pad.
163
+ pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
164
+ int(np.ceil(max(quad[:, 1]))))
165
+ pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
166
+ max(pad[3] - img.size[1] + border, 0))
167
+ if enable_padding and max(pad) > border - 4:
168
+ pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
169
+ img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
170
+ h, w, _ = img.shape
171
+ y, x, _ = np.ogrid[:h, :w, :1]
172
+ mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
173
+ 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
174
+ blur = qsize * 0.02
175
+ img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
176
+ img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
177
+ img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
178
+ quad += pad[:2]
179
+
180
+ # Transform.
181
+ img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(),
182
+ PIL.Image.BILINEAR)
183
+ if output_size < transform_size:
184
+ img = img.resize((output_size, output_size), PIL.Image.LANCZOS)
185
+
186
+ # Save aligned image.
187
+ imgs.append(img)
188
+
189
+ if return_tensors:
190
+ transform = T.ToTensor()
191
+ tensors = [transform(img).clamp(0, 1) for img in imgs]
192
+ return tensors
193
+ return imgs