Spaces:
Runtime error
Runtime error
Added util functions
Browse files
util.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from matplotlib import pyplot as plt
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import os
|
5 |
+
import dlib
|
6 |
+
from PIL import Image
|
7 |
+
import numpy as np
|
8 |
+
import scipy
|
9 |
+
import scipy.ndimage
|
10 |
+
import torchvision.transforms as transforms
|
11 |
+
|
12 |
+
def display_image(image, size=None, mode='nearest', unnorm=False, title=''):
|
13 |
+
# image is [3,h,w] or [1,3,h,w] tensor [0,1]
|
14 |
+
if not isinstance(image, torch.Tensor):
|
15 |
+
image = transforms.ToTensor()(image).unsqueeze(0)
|
16 |
+
if image.is_cuda:
|
17 |
+
image = image.cpu()
|
18 |
+
if size is not None and image.size(-1) != size:
|
19 |
+
image = F.interpolate(image, size=(size,size), mode=mode)
|
20 |
+
if image.dim() == 4:
|
21 |
+
image = image[0]
|
22 |
+
image = image.permute(1, 2, 0).detach().numpy()
|
23 |
+
plt.figure()
|
24 |
+
plt.title(title)
|
25 |
+
plt.axis('off')
|
26 |
+
plt.imshow(image)
|
27 |
+
|
28 |
+
def get_landmark(filepath, predictor):
|
29 |
+
"""get landmark with dlib
|
30 |
+
:return: np.array shape=(68, 2)
|
31 |
+
"""
|
32 |
+
detector = dlib.get_frontal_face_detector()
|
33 |
+
|
34 |
+
img = dlib.load_rgb_image(filepath)
|
35 |
+
dets = detector(img, 1)
|
36 |
+
assert len(dets) > 0, "Face not detected, try another face image"
|
37 |
+
|
38 |
+
for k, d in enumerate(dets):
|
39 |
+
shape = predictor(img, d)
|
40 |
+
|
41 |
+
t = list(shape.parts())
|
42 |
+
a = []
|
43 |
+
for tt in t:
|
44 |
+
a.append([tt.x, tt.y])
|
45 |
+
lm = np.array(a)
|
46 |
+
return lm
|
47 |
+
|
48 |
+
def align_face(filepath, predictor, output_size=256, transform_size=1024, enable_padding=True):
|
49 |
+
|
50 |
+
"""
|
51 |
+
:param filepath: str
|
52 |
+
:return: PIL Image
|
53 |
+
"""
|
54 |
+
lm = get_landmark(filepath, predictor)
|
55 |
+
|
56 |
+
lm_chin = lm[0: 17] # left-right
|
57 |
+
lm_eyebrow_left = lm[17: 22] # left-right
|
58 |
+
lm_eyebrow_right = lm[22: 27] # left-right
|
59 |
+
lm_nose = lm[27: 31] # top-down
|
60 |
+
lm_nostrils = lm[31: 36] # top-down
|
61 |
+
lm_eye_left = lm[36: 42] # left-clockwise
|
62 |
+
lm_eye_right = lm[42: 48] # left-clockwise
|
63 |
+
lm_mouth_outer = lm[48: 60] # left-clockwise
|
64 |
+
lm_mouth_inner = lm[60: 68] # left-clockwise
|
65 |
+
|
66 |
+
# Calculate auxiliary vectors.
|
67 |
+
eye_left = np.mean(lm_eye_left, axis=0)
|
68 |
+
eye_right = np.mean(lm_eye_right, axis=0)
|
69 |
+
eye_avg = (eye_left + eye_right) * 0.5
|
70 |
+
eye_to_eye = eye_right - eye_left
|
71 |
+
mouth_left = lm_mouth_outer[0]
|
72 |
+
mouth_right = lm_mouth_outer[6]
|
73 |
+
mouth_avg = (mouth_left + mouth_right) * 0.5
|
74 |
+
eye_to_mouth = mouth_avg - eye_avg
|
75 |
+
|
76 |
+
# Choose oriented crop rectangle.
|
77 |
+
x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
|
78 |
+
x /= np.hypot(*x)
|
79 |
+
x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
|
80 |
+
y = np.flipud(x) * [-1, 1]
|
81 |
+
c = eye_avg + eye_to_mouth * 0.1
|
82 |
+
quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
|
83 |
+
qsize = np.hypot(*x) * 2
|
84 |
+
|
85 |
+
# read image
|
86 |
+
img = Image.open(filepath)
|
87 |
+
|
88 |
+
transform_size = output_size
|
89 |
+
enable_padding = True
|
90 |
+
|
91 |
+
# Shrink.
|
92 |
+
shrink = int(np.floor(qsize / output_size * 0.5))
|
93 |
+
if shrink > 1:
|
94 |
+
rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
|
95 |
+
img = img.resize(rsize, Image.ANTIALIAS)
|
96 |
+
quad /= shrink
|
97 |
+
qsize /= shrink
|
98 |
+
|
99 |
+
# Crop.
|
100 |
+
border = max(int(np.rint(qsize * 0.1)), 3)
|
101 |
+
crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
|
102 |
+
int(np.ceil(max(quad[:, 1]))))
|
103 |
+
crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
|
104 |
+
min(crop[3] + border, img.size[1]))
|
105 |
+
if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
|
106 |
+
img = img.crop(crop)
|
107 |
+
quad -= crop[0:2]
|
108 |
+
|
109 |
+
# Pad.
|
110 |
+
pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
|
111 |
+
int(np.ceil(max(quad[:, 1]))))
|
112 |
+
pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
|
113 |
+
max(pad[3] - img.size[1] + border, 0))
|
114 |
+
if enable_padding and max(pad) > border - 4:
|
115 |
+
pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
|
116 |
+
img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
|
117 |
+
h, w, _ = img.shape
|
118 |
+
y, x, _ = np.ogrid[:h, :w, :1]
|
119 |
+
mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
|
120 |
+
1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
|
121 |
+
blur = qsize * 0.02
|
122 |
+
img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
|
123 |
+
img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
|
124 |
+
img = Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
|
125 |
+
quad += pad[:2]
|
126 |
+
|
127 |
+
# Transform.
|
128 |
+
img = img.transform((transform_size, transform_size), Image.QUAD, (quad + 0.5).flatten(), Image.BILINEAR)
|
129 |
+
if output_size < transform_size:
|
130 |
+
img = img.resize((output_size, output_size), Image.ANTIALIAS)
|
131 |
+
|
132 |
+
# Return aligned image.
|
133 |
+
return img
|
134 |
+
|
135 |
+
def strip_path_extension(path):
|
136 |
+
return os.path.splitext(path)[0]
|