-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyunet_detector.py
More file actions
54 lines (45 loc) · 1.6 KB
/
Copy pathyunet_detector.py
File metadata and controls
54 lines (45 loc) · 1.6 KB
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
from pathlib import Path
import urllib.request
import cv2 as cv
import numpy as np
def ensure_yunet_model(model_path: Path) -> None:
if model_path.exists() and model_path.stat().st_size > 0:
return
model_path.parent.mkdir(parents=True, exist_ok=True)
url = (
"https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/"
"face_detection_yunet/face_detection_yunet_2023mar.onnx"
)
req = urllib.request.Request(
url,
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) FaceTracking/1.0"},
)
with urllib.request.urlopen(req, timeout=30) as r: # noqa: S310
data = r.read()
if len(data) < 100000:
raise SystemExit("YuNet 模型下载失败,文件大小异常。请关闭代理后重试。")
model_path.write_bytes(data)
class YuNetDetector:
def __init__(
self,
model_path: str,
input_size: tuple[int, int] = (320, 240),
score_threshold: float = 0.88,
nms_threshold: float = 0.3,
top_k: int = 1000,
) -> None:
self._detector = cv.FaceDetectorYN_create(
model_path,
"",
input_size,
score_threshold=score_threshold,
nms_threshold=nms_threshold,
top_k=top_k,
)
def set_input_size(self, size: tuple[int, int]) -> None:
self._detector.setInputSize(size)
def infer(self, image: np.ndarray) -> np.ndarray:
_, faces = self._detector.detect(image)
if faces is None:
return np.empty((0, 15), dtype=np.float32)
return faces