helpers.py 10.2 KB
Newer Older
1
2
3
4
5
import bob.bio.face
from sklearn.pipeline import make_pipeline
from bob.bio.base.wrappers import wrap_sample_preprocessor
from bob.pipelines import wrap
from bob.bio.face.helpers import face_crop_solver
6
import numpy as np
7
import logging
8

9
logger = logging.getLogger(__name__)
10

11

12
13
14
15
def embedding_transformer_default_cropping(cropped_image_size, annotation_type):
    """
    Computes the default cropped positions for the FaceCropper used with Facenet-like 
    Embedding extractors, proportionally to the target image size
16

17
18
19
20
21
22

    Parameters
    ----------
       cropped_image_size : tuple
          A tuple (HEIGHT, WIDTH) describing the target size of the cropped image.

23
       annotation_type: str or list of str
24
          Type of annotations. Possible values are: `bounding-box`, `eyes-center`, 'left-profile', 
25
          'right-profile'  and None, or a combination of those as a list
26
27
28
29
30

    Returns
    -------

      cropped_positions:
31
32
         The dictionary of cropped positions that will be feeded to the FaceCropper, or a list of such dictionaries if
         ``annotation_type`` is a list
33
    """
34
    if isinstance(annotation_type, list):
35
36
37
38
        return [
            embedding_transformer_default_cropping(cropped_image_size, item)
            for item in annotation_type
        ]
39

Laurent COLBOIS's avatar
Laurent COLBOIS committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH = cropped_image_size

    if annotation_type == "bounding-box":

        TOP_LEFT_POS = (0, 0)
        BOTTOM_RIGHT_POS = (CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH)
        cropped_positions = {"topleft": TOP_LEFT_POS, "bottomright": BOTTOM_RIGHT_POS}

    elif annotation_type == "eyes-center":

        RIGHT_EYE_POS = (
            round(2 / 7 * CROPPED_IMAGE_HEIGHT),
            round(1 / 3 * CROPPED_IMAGE_WIDTH),
        )
        LEFT_EYE_POS = (
            round(2 / 7 * CROPPED_IMAGE_HEIGHT),
            round(2 / 3 * CROPPED_IMAGE_WIDTH),
        )
        cropped_positions = {"leye": LEFT_EYE_POS, "reye": RIGHT_EYE_POS}

    elif annotation_type == "left-profile":

        EYE_POS = (
            round(2 / 7 * CROPPED_IMAGE_HEIGHT),
            round(3 / 8 * CROPPED_IMAGE_WIDTH),
        )
        MOUTH_POS = (
            round(5 / 7 * CROPPED_IMAGE_HEIGHT),
            round(3 / 8 * CROPPED_IMAGE_WIDTH),
        )
        cropped_positions = {"leye": EYE_POS, "mouth": MOUTH_POS}

    elif annotation_type == "right-profile":

        EYE_POS = (
            round(2 / 7 * CROPPED_IMAGE_HEIGHT),
            round(5 / 8 * CROPPED_IMAGE_WIDTH),
        )
        MOUTH_POS = (
            round(5 / 7 * CROPPED_IMAGE_HEIGHT),
            round(5 / 8 * CROPPED_IMAGE_WIDTH),
        )
        cropped_positions = {"reye": EYE_POS, "mouth": MOUTH_POS}
83

Laurent COLBOIS's avatar
Laurent COLBOIS committed
84
    else:
85

86
87
88
        logger.warning(
            f"Annotation type {annotation_type} is not supported. Input images will be fully scaled."
        )
Laurent COLBOIS's avatar
Laurent COLBOIS committed
89
        cropped_positions = None
90

Laurent COLBOIS's avatar
Laurent COLBOIS committed
91
    return cropped_positions
92

93

94
def legacy_default_cropping(cropped_image_size, annotation_type):
95
    """
96
97
    Computes the default cropped positions for the FaceCropper used with legacy extractors, 
    proportionally to the target image size
98
99


100
101
102
103
104
105
106
    Parameters
    ----------
       cropped_image_size : tuple
          A tuple (HEIGHT, WIDTH) describing the target size of the cropped image.

       annotation_type: str
          Type of annotations. Possible values are: `bounding-box`, `eyes-center`, 'left-profile', 
107
          'right-profile' and None, or a combination of those as a list
108
109
110
111
112

    Returns
    -------

      cropped_positions:
113
114
         The dictionary of cropped positions that will be feeded to the FaceCropper, or a list of such dictionaries if
         ``annotation_type`` is a list
115
    """
116
    if isinstance(annotation_type, list):
117
118
119
120
        return [
            legacy_default_cropping(cropped_image_size, item)
            for item in annotation_type
        ]
121

Laurent COLBOIS's avatar
Laurent COLBOIS committed
122
    CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH = cropped_image_size
123

Laurent COLBOIS's avatar
Laurent COLBOIS committed
124
    if annotation_type == "bounding-box":
125

Laurent COLBOIS's avatar
Laurent COLBOIS committed
126
127
128
        TOP_LEFT_POS = (0, 0)
        BOTTOM_RIGHT_POS = (CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH)
        cropped_positions = {"topleft": TOP_LEFT_POS, "bottomright": BOTTOM_RIGHT_POS}
129

Laurent COLBOIS's avatar
Laurent COLBOIS committed
130
    elif annotation_type == "eyes-center":
131

Laurent COLBOIS's avatar
Laurent COLBOIS committed
132
133
134
        RIGHT_EYE_POS = (CROPPED_IMAGE_HEIGHT // 5, CROPPED_IMAGE_WIDTH // 4 - 1)
        LEFT_EYE_POS = (CROPPED_IMAGE_HEIGHT // 5, CROPPED_IMAGE_WIDTH // 4 * 3)
        cropped_positions = {"leye": LEFT_EYE_POS, "reye": RIGHT_EYE_POS}
135

Laurent COLBOIS's avatar
Laurent COLBOIS committed
136
137
138
139
140
    elif annotation_type == "left-profile":
        # Main reference https://gitlab.idiap.ch/bob/bob.chapter.FRICE/-/blob/master/bob/chapter/FRICE/script/pose.py
        EYE_POS = (CROPPED_IMAGE_HEIGHT // 5, CROPPED_IMAGE_WIDTH // 7 * 3 - 2)
        MOUTH_POS = (CROPPED_IMAGE_HEIGHT // 3 * 2, CROPPED_IMAGE_WIDTH // 7 * 3 - 2)
        cropped_positions = {"leye": EYE_POS, "mouth": MOUTH_POS}
141

Laurent COLBOIS's avatar
Laurent COLBOIS committed
142
143
144
145
146
    elif annotation_type == "right-profile":
        # Main reference https://gitlab.idiap.ch/bob/bob.chapter.FRICE/-/blob/master/bob/chapter/FRICE/script/pose.py
        EYE_POS = (CROPPED_IMAGE_HEIGHT // 5, CROPPED_IMAGE_WIDTH // 7 * 4 + 2)
        MOUTH_POS = (CROPPED_IMAGE_HEIGHT // 3 * 2, CROPPED_IMAGE_WIDTH // 7 * 4 + 2)
        cropped_positions = {"reye": EYE_POS, "mouth": MOUTH_POS}
147

Laurent COLBOIS's avatar
Laurent COLBOIS committed
148
    else:
149

150
151
152
        logger.warning(
            f"Annotation type {annotation_type} is not supported. Input images will be fully scaled."
        )
Laurent COLBOIS's avatar
Laurent COLBOIS committed
153
        cropped_positions = None
154

Laurent COLBOIS's avatar
Laurent COLBOIS committed
155
    return cropped_positions
156

157
158
159
160
161
162
163
164
165

def embedding_transformer(
    cropped_image_size,
    embedding,
    annotation_type,
    cropped_positions,
    fixed_positions=None,
    color_channel="rgb",
):
166
167
168
169
170
171
172
173
174
    """
    Creates a pipeline composed by and FaceCropper and an Embedding extractor.
    This transformer is suited for Facenet based architectures
    
    .. warning::
       This will resize images to the requested `image_size`
    
    """
    face_cropper = face_crop_solver(
175
176
177
178
179
        cropped_image_size,
        color_channel=color_channel,
        cropped_positions=cropped_positions,
        fixed_positions=fixed_positions,
    )
180

181
    transform_extra_arguments = (
182
183
184
        None
        if (cropped_positions is None or fixed_positions is not None)
        else (("annotations", "annotations"),)
185
    )
186
187
188
189
190
191
192
193
194
195
196

    transformer = make_pipeline(
        wrap(
            ["sample"],
            face_cropper,
            transform_extra_arguments=transform_extra_arguments,
        ),
        wrap(["sample"], embedding),
    )

    return transformer
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
197

198
199
200
201

def embedding_transformer_160x160(
    embedding, annotation_type, fixed_positions, color_channel="rgb"
):
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
202
203
204
205
206
    """
    Creates a pipeline composed by and FaceCropper and an Embedding extractor.
    This transformer is suited for Facenet based architectures
    
    .. warning::
207
       This will resize images to :math:`160 \times 160`
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
208
209
    
    """
210
211
212
    cropped_positions = embedding_transformer_default_cropping(
        (160, 160), annotation_type
    )
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
213

214
215
216
217
218
219
220
221
    return embedding_transformer(
        (160, 160),
        embedding,
        annotation_type,
        cropped_positions,
        fixed_positions,
        color_channel=color_channel,
    )
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
222
223


224
225
226
def embedding_transformer_112x112(
    embedding, annotation_type, fixed_positions, color_channel="rgb"
):
227
228
229
230
231
232
233
234
235
236
237
    """
    Creates a pipeline composed by and FaceCropper and an Embedding extractor.
    This transformer is suited for Facenet based architectures
    
    .. warning::
       This will resize images to :math:`112 \times 112`
    
    """
    cropped_image_size = (112, 112)
    if annotation_type == "eyes-center":
        # Hard coding eye positions for backward consistency
238
239
240
241
242
        cropped_positions = {
            "leye": (55, 81),
            "reye": (55, 42),
        }

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
243
    else:
244
245
246
247
        # Will use default
        cropped_positions = embedding_transformer_default_cropping(
            cropped_image_size, annotation_type
        )
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
248

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    return embedding_transformer(
        cropped_image_size,
        embedding,
        annotation_type,
        cropped_positions,
        fixed_positions,
        color_channel=color_channel,
    )


def embedding_transformer_224x224(
    embedding, annotation_type, fixed_positions, color_channel="rgb"
):
    """
    Creates a pipeline composed by and FaceCropper and an Embedding extractor.
    This transformer is suited for Facenet based architectures
    
    .. warning::
       This will resize images to :math:`112 \times 112`
    
    """
    cropped_image_size = (224, 224)
    if annotation_type == "eyes-center":
        # Hard coding eye positions for backward consistency
        cropped_positions = {"leye": (65, 150), "reye": (65, 77)}
    else:
        # Will use default
        cropped_positions = embedding_transformer_default_cropping(
            cropped_image_size, annotation_type
        )

    return embedding_transformer(
        cropped_image_size,
        embedding,
        annotation_type,
        cropped_positions,
        fixed_positions,
        color_channel=color_channel,
    )
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317


def crop_80x64(annotation_type, fixed_positions=None, color_channel="gray"):
    """
    Crops a face to :math:`80 \times 64`


    Parameters
    ----------

       annotation_type: str
          Type of annotations. Possible values are: `bounding-box`, `eyes-center` and None

       fixed_positions: tuple
          A tuple containing the annotations. This is used in case your input is already registered
          with fixed positions (eyes or bounding box)

       color_channel: str


    Returns
    -------

      face_cropper:
         A face cropper to be used
      
      transform_extra_arguments:
         The parameters to the transformer

    """
318
319
    color_channel = color_channel
    dtype = np.float64
320
321
322
323
324
325

    # Cropping
    CROPPED_IMAGE_HEIGHT = 80
    CROPPED_IMAGE_WIDTH = CROPPED_IMAGE_HEIGHT * 4 // 5
    cropped_image_size = (CROPPED_IMAGE_HEIGHT, CROPPED_IMAGE_WIDTH)

326
    cropped_positions = legacy_default_cropping(cropped_image_size, annotation_type)
327

328
    face_cropper = face_crop_solver(
329
330
331
332
333
334
335
336
        cropped_image_size,
        color_channel=color_channel,
        cropped_positions=cropped_positions,
        fixed_positions=fixed_positions,
        dtype=dtype,
    )

    transform_extra_arguments = (
337
338
339
        None
        if (cropped_positions is None or fixed_positions is not None)
        else (("annotations", "annotations"),)
340
    )
341
342

    return face_cropper, transform_extra_arguments