hysts HF staff commited on
Commit
db0de3e
1 Parent(s): 4022fb9
Files changed (4) hide show
  1. .gitmodules +3 -0
  2. anime_face_landmark_detection +1 -0
  3. app.py +175 -0
  4. requirements.txt +3 -0
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "anime_face_landmark_detection"]
2
+ path = anime_face_landmark_detection
3
+ url = https://github.com/kanosawa/anime_face_landmark_detection
anime_face_landmark_detection ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 95231f3884fc531273c731ce4d8f583b61e5530d
app.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import functools
7
+ import os
8
+ import pathlib
9
+ import sys
10
+ import tarfile
11
+ import urllib
12
+ from typing import Callable
13
+
14
+ sys.path.insert(0, 'anime_face_landmark_detection')
15
+
16
+ import cv2
17
+ import gradio as gr
18
+ import huggingface_hub
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torchvision.transforms as T
23
+ from CFA import CFA
24
+
25
+ TOKEN = os.environ['TOKEN']
26
+
27
+ MODEL_REPO = 'hysts/anime_face_landmark_detection'
28
+ MODEL_FILENAME = 'checkpoint_landmark_191116.pth'
29
+
30
+ NUM_LANDMARK = 24
31
+ CROP_SIZE = 128
32
+
33
+
34
+ def parse_args() -> argparse.Namespace:
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument('--device', type=str, default='cpu')
37
+ parser.add_argument('--theme', type=str)
38
+ parser.add_argument('--live', action='store_true')
39
+ parser.add_argument('--share', action='store_true')
40
+ parser.add_argument('--port', type=int)
41
+ parser.add_argument('--disable-queue',
42
+ dest='enable_queue',
43
+ action='store_false')
44
+ parser.add_argument('--allow-flagging', type=str, default='never')
45
+ parser.add_argument('--allow-screenshot', action='store_true')
46
+ return parser.parse_args()
47
+
48
+
49
+ def load_sample_image_paths() -> list[pathlib.Path]:
50
+ image_dir = pathlib.Path('images')
51
+ if not image_dir.exists():
52
+ dataset_repo = 'hysts/sample-images-TADNE'
53
+ path = huggingface_hub.hf_hub_download(dataset_repo,
54
+ 'images.tar.gz',
55
+ repo_type='dataset',
56
+ use_auth_token=TOKEN)
57
+ with tarfile.open(path) as f:
58
+ f.extractall()
59
+ return sorted(image_dir.glob('*'))
60
+
61
+
62
+ def load_face_detector() -> cv2.CascadeClassifier:
63
+ url = 'https://raw.githubusercontent.com/nagadomi/lbpcascade_animeface/master/lbpcascade_animeface.xml'
64
+ path = pathlib.Path('lbpcascade_animeface.xml')
65
+ if not path.exists():
66
+ urllib.request.urlretrieve(url, path.as_posix())
67
+ return cv2.CascadeClassifier(path.as_posix())
68
+
69
+
70
+ def load_landmark_detector(device: torch.device) -> torch.nn.Module:
71
+ path = huggingface_hub.hf_hub_download(MODEL_REPO,
72
+ MODEL_FILENAME,
73
+ use_auth_token=TOKEN)
74
+ model = CFA(output_channel_num=NUM_LANDMARK + 1, checkpoint_name=path)
75
+ model.to(device)
76
+ model.eval()
77
+ return model
78
+
79
+
80
+ @torch.inference_mode()
81
+ def detect(image, face_detector: cv2.CascadeClassifier, device: torch.device,
82
+ transform: Callable,
83
+ landmark_detector: torch.nn.Module) -> np.ndarray:
84
+ image = cv2.imread(image.name)
85
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
86
+ preds = face_detector.detectMultiScale(gray,
87
+ scaleFactor=1.1,
88
+ minNeighbors=5,
89
+ minSize=(24, 24))
90
+
91
+ image_h, image_w = image.shape[:2]
92
+ pil_image = PIL.Image.fromarray(image[:, :, ::-1].copy())
93
+
94
+ res = image.copy()
95
+ for x_orig, y_orig, w_orig, h_orig in preds:
96
+
97
+ x0 = round(max(x_orig - w_orig / 8, 0))
98
+ x1 = round(min(x_orig + w_orig * 9 / 8, image_w))
99
+ y0 = round(max(y_orig - h_orig / 4, 0))
100
+ y1 = y_orig + h_orig
101
+ w = x1 - x0
102
+ h = y1 - y0
103
+
104
+ temp = pil_image.crop((x0, y0, x1, y1))
105
+ temp = temp.resize((CROP_SIZE, CROP_SIZE), PIL.Image.BICUBIC)
106
+ data = transform(temp)
107
+ data = data.to(device).unsqueeze(0)
108
+
109
+ heatmaps = landmark_detector(data)
110
+ heatmaps = heatmaps[-1].cpu().numpy()[0]
111
+
112
+ cv2.rectangle(res, (x0, y0), (x1, y1), (0, 255, 0), 2)
113
+
114
+ for i in range(NUM_LANDMARK):
115
+ heatmap = cv2.resize(heatmaps[i], (CROP_SIZE, CROP_SIZE),
116
+ interpolation=cv2.INTER_CUBIC)
117
+ pty, ptx = np.unravel_index(np.argmax(heatmap), heatmap.shape)
118
+ pt_crop = np.round(np.array([ptx * w, pty * h]) /
119
+ CROP_SIZE).astype(int)
120
+ pt = np.array([x0, y0]) + pt_crop
121
+ cv2.circle(res, tuple(pt), 2, (0, 0, 255), cv2.FILLED)
122
+
123
+ res = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)
124
+ return res
125
+
126
+
127
+ def main():
128
+ gr.close_all()
129
+
130
+ args = parse_args()
131
+ device = torch.device(args.device)
132
+
133
+ image_paths = load_sample_image_paths()
134
+ examples = [[path.as_posix()] for path in image_paths]
135
+
136
+ face_detector = load_face_detector()
137
+ landmark_detector = load_landmark_detector(device)
138
+ transform = T.Compose([
139
+ T.ToTensor(),
140
+ T.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
141
+ ])
142
+
143
+ func = functools.partial(detect,
144
+ face_detector=face_detector,
145
+ device=device,
146
+ transform=transform,
147
+ landmark_detector=landmark_detector)
148
+ func = functools.update_wrapper(func, detect)
149
+
150
+ repo_url = 'https://github.com/kanosawa/anime_face_landmark_detection'
151
+ title = 'kanosawa/anime_face_landmark_detection'
152
+ description = f'A demo for {repo_url}'
153
+ article = None
154
+
155
+ gr.Interface(
156
+ func,
157
+ gr.inputs.Image(type='file', label='Input'),
158
+ gr.outputs.Image(label='Output'),
159
+ theme=args.theme,
160
+ title=title,
161
+ description=description,
162
+ article=article,
163
+ examples=examples,
164
+ allow_screenshot=args.allow_screenshot,
165
+ allow_flagging=args.allow_flagging,
166
+ live=args.live,
167
+ ).launch(
168
+ enable_queue=args.enable_queue,
169
+ server_port=args.port,
170
+ share=args.share,
171
+ )
172
+
173
+
174
+ if __name__ == '__main__':
175
+ main()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ opencv-python-headless>=4.5.5.62
2
+ torch>=1.10.1
3
+ torchvision>=0.11.2