File size: 1,704 Bytes
21db550
 
 
 
 
 
 
 
 
 
f9cf2ba
401a860
 
21db550
f9cf2ba
 
21db550
f9cf2ba
 
401a860
 
 
21db550
 
7430609
 
 
a968fd4
 
 
 
21db550
a968fd4
21db550
 
 
f9cf2ba
2343867
21db550
7430609
f9cf2ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7430609
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python

import pathlib

import cv2
import face_alignment
import gradio as gr
import numpy as np
import torch

DESCRIPTION = "# [face-alignment](https://github.com/1adrianb/face-alignment)"

MAX_IMAGE_SIZE = 1800

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
detector = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device=device.type)


def detect(image: np.ndarray) -> np.ndarray:
    landmarks, _, boxes = detector.get_landmarks(image, return_bboxes=True)
    if landmarks is None:
        return image

    res = image.copy()
    for pts, box in zip(landmarks, boxes, strict=False):
        box_int = np.round(box[:4]).astype(int)
        cv2.rectangle(res, tuple(box_int[:2]), tuple(box_int[2:]), (0, 255, 0), 2)
        tl = pts.min(axis=0)
        br = pts.max(axis=0)
        size = (br - tl).max()
        radius = max(2, int(3 * size / 256))
        for pt in np.round(pts).astype(int):
            cv2.circle(res, tuple(pt), radius, (0, 255, 0), cv2.FILLED)
    return res


image_paths = sorted(pathlib.Path("images").glob("*.jpg"))
examples = [[path.as_posix()] for path in image_paths]

with gr.Blocks(css_paths="style.css") as demo:
    gr.Markdown(DESCRIPTION)
    with gr.Row():
        with gr.Column():
            image = gr.Image(label="Input", type="numpy")
            run_button = gr.Button()
        with gr.Column():
            output = gr.Image(label="Output")
    gr.Examples(
        examples=examples,
        inputs=image,
        outputs=output,
        fn=detect,
    )

    run_button.click(
        fn=detect,
        inputs=image,
        outputs=output,
    )

if __name__ == "__main__":
    demo.launch()