HairFastGAN

Форк
0
/
shape_predictor.py 
194 строки · 6.9 Кб
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

23
requirements:
24
    apt install cmake
25
    conda install Pillow numpy scipy
26
    pip install dlib
27
    # download face landmark model from:
28
    # http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
29
"""
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

38
    img = dlib.load_rgb_image(filepath)
39
    dets = detector(img, 1)
40
    filepath = Path(filepath)
41
    print(f"{filepath.name}: Number of faces detected: {len(dets)}")
42
    shapes = [predictor(img, d) for k, d in enumerate(dets)]
43

44
    lms = [np.array([[tt.x, tt.y] for tt in shape.parts()]) for shape in shapes]
45

46
    return lms
47

48

49
def get_landmark_from_tensors(tensors: list[torch.Tensor | Image.Image | np.ndarray], predictor):
50
    detector = dlib.get_frontal_face_detector()
51
    transform = T.ToPILImage()
52
    images = []
53
    lms = []
54

55
    for k, tensor in enumerate(tensors):
56
        if isinstance(tensor, torch.Tensor):
57
            img_pil = transform(tensor)
58
        else:
59
            img_pil = tensor
60
        img = np.array(img_pil)
61
        images.append(img_pil)
62

63
        dets = detector(img, 1)
64
        if len(dets) == 0:
65
            raise ValueError(f"No faces detected in the image {k}.")
66
        elif len(dets) == 1:
67
            print(f"Number of faces detected: {len(dets)}")
68
        else:
69
            print(f"Number of faces detected: {len(dets)}, get largest face")
70

71
        # Find the largest face
72
        dets = sorted(dets, key=lambda det: det.width() * det.height(), reverse=True)
73
        shape = predictor(img, dets[0])
74
        lm = np.array([[tt.x, tt.y] for tt in shape.parts()])
75
        lms.append(lm)
76

77
    return images, lms
78

79

80
def align_face(data, predictor=None, is_filepath=False, return_tensors=True):
81
    """
82
    :param data: filepath or list torch Tensors
83
    :return: list of PIL Images
84
    """
85
    if predictor is None:
86
        predictor_path = 'pretrained_models/ShapeAdaptor/shape_predictor_68_face_landmarks.dat'
87

88
        if not os.path.isfile(predictor_path):
89
            print("Downloading Shape Predictor")
90
            data_io = open_url("https://drive.google.com/uc?id=1huhv8PYpNNKbGCLOaYUjOgR1pY5pmbJx")
91
            with open(predictor_path, 'wb') as f:
92
                f.write(data_io.getbuffer())
93

94
        predictor = dlib.shape_predictor(predictor_path)
95

96
    if is_filepath:
97
        lms = get_landmark(data, predictor)
98
    else:
99
        if not isinstance(data, list):
100
            data = [data]
101
        images, lms = get_landmark_from_tensors(data, predictor)
102

103
    imgs = []
104
    for num_img, lm in enumerate(lms):
105
        lm_chin = lm[0: 17]  # left-right
106
        lm_eyebrow_left = lm[17: 22]  # left-right
107
        lm_eyebrow_right = lm[22: 27]  # left-right
108
        lm_nose = lm[27: 31]  # top-down
109
        lm_nostrils = lm[31: 36]  # top-down
110
        lm_eye_left = lm[36: 42]  # left-clockwise
111
        lm_eye_right = lm[42: 48]  # left-clockwise
112
        lm_mouth_outer = lm[48: 60]  # left-clockwise
113
        lm_mouth_inner = lm[60: 68]  # left-clockwise
114

115
        # Calculate auxiliary vectors.
116
        eye_left = np.mean(lm_eye_left, axis=0)
117
        eye_right = np.mean(lm_eye_right, axis=0)
118
        eye_avg = (eye_left + eye_right) * 0.5
119
        eye_to_eye = eye_right - eye_left
120
        mouth_left = lm_mouth_outer[0]
121
        mouth_right = lm_mouth_outer[6]
122
        mouth_avg = (mouth_left + mouth_right) * 0.5
123
        eye_to_mouth = mouth_avg - eye_avg
124

125
        # Choose oriented crop rectangle.
126
        x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
127
        x /= np.hypot(*x)
128
        x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
129
        y = np.flipud(x) * [-1, 1]
130
        c = eye_avg + eye_to_mouth * 0.1
131
        quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
132
        qsize = np.hypot(*x) * 2
133

134
        # read image
135
        if is_filepath:
136
            img = PIL.Image.open(data)
137
        else:
138
            img = images[num_img]
139

140
        output_size = 1024
141
        # output_size = 256
142
        transform_size = 4096
143
        enable_padding = True
144

145
        # Shrink.
146
        shrink = int(np.floor(qsize / output_size * 0.5))
147
        if shrink > 1:
148
            rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
149
            img = img.resize(rsize, PIL.Image.ANTIALIAS)
150
            quad /= shrink
151
            qsize /= shrink
152

153
        # Crop.
154
        border = max(int(np.rint(qsize * 0.1)), 3)
155
        crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
156
                int(np.ceil(max(quad[:, 1]))))
157
        crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
158
                min(crop[3] + border, img.size[1]))
159
        if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
160
            img = img.crop(crop)
161
            quad -= crop[0:2]
162

163
        # Pad.
164
        pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
165
               int(np.ceil(max(quad[:, 1]))))
166
        pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
167
               max(pad[3] - img.size[1] + border, 0))
168
        if enable_padding and max(pad) > border - 4:
169
            pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
170
            img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
171
            h, w, _ = img.shape
172
            y, x, _ = np.ogrid[:h, :w, :1]
173
            mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
174
                              1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
175
            blur = qsize * 0.02
176
            img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
177
            img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
178
            img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
179
            quad += pad[:2]
180

181
        # Transform.
182
        img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(),
183
                            PIL.Image.BILINEAR)
184
        if output_size < transform_size:
185
            img = img.resize((output_size, output_size), PIL.Image.LANCZOS)
186

187
        # Save aligned image.
188
        imgs.append(img)
189

190
    if return_tensors:
191
        transform = T.ToTensor()
192
        tensors = [transform(img).clamp(0, 1) for img in imgs]
193
        return tensors
194
    return imgs
195

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.