Skip to content

UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.

feat: Fix and test face recognition

yakhyo597c86f997fc
diff --git a/scripts/run_inference.py b/scripts/run_detection.py
similarity index 100%
rename from scripts/run_inference.py
rename to scripts/run_detection.py
diff --git a/scripts/run_recognition.py b/scripts/run_recognition.py
new file mode 100644
index 0000000..f1b82e4
--- /dev/null
+++ b/scripts/run_recognition.py
@@ -0,0 +1,59 @@
+import cv2
+import argparse
+import numpy as np
+
+from uniface.detection import RetinaFace
+from uniface.constants import RetinaFaceWeights
+from uniface.recognition import ArcFace
+
+
+def run_inference(detector, recognizer, image_path):
+ """
+ Detect faces and extract embeddings from a single image.
+
+ Args:
+ detector (RetinaFace): Initialized face detector.
+ recognizer (ArcFace): Face recognition model.
+ image_path (str): Path to the input image.
+ """
+ image = cv2.imread(image_path)
+ if image is None:
+ print(f"Error: Failed to load image from '{image_path}'")
+ return
+
+ boxes, landmarks = detector.detect(image)
+
+ if len(boxes) == 0:
+ print("No faces detected.")
+ return
+
+ print(f"Detected {len(boxes)} face(s). Extracting embeddings...")
+
+ for i, landmark in enumerate(landmarks):
+ embedding = recognizer.get_embedding(image, landmark)
+ norm = np.linalg.norm(embedding)
+ print(f"\nFace {i} embedding (L2 norm = {norm:.4f}):")
+ print(embedding)
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Extract face embeddings from a single image.")
+ parser.add_argument("--image", type=str, required=True, help="Path to the input image.")
+ parser.add_argument(
+ "--model",
+ type=str,
+ default="MNET_V2",
+ choices=[m.name for m in RetinaFaceWeights],
+ help="RetinaFace model variant to use."
+ )
+
+ args = parser.parse_args()
+
+ detector = RetinaFace(model_name=RetinaFaceWeights[args.model])
+ recognizer = ArcFace()
+
+ run_inference(detector, recognizer, args.image)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/search_face.py b/scripts/search_face.py
new file mode 100644
index 0000000..360e8b1
--- /dev/null
+++ b/scripts/search_face.py
@@ -0,0 +1,70 @@
+import cv2
+import argparse
+import numpy as np
+
+from uniface.detection import RetinaFace
+from uniface.constants import RetinaFaceWeights
+from uniface.recognition import ArcFace
+from uniface.face_utils import compute_similarity
+
+
+def extract_reference_embedding(detector, recognizer, image_path):
+ image = cv2.imread(image_path)
+ if image is None:
+ raise RuntimeError(f"Failed to load image: {image_path}")
+
+ boxes, landmarks = detector.detect(image)
+ if len(boxes) == 0:
+ raise RuntimeError("No faces found in reference image.")
+
+ embedding = recognizer.get_embedding(image, landmarks[0])
+ print(f"Reference embedding extracted (L2 norm = {np.linalg.norm(embedding):.4f})")
+ return embedding
+
+
+def run_video(detector, recognizer, ref_embedding, threshold=0.45):
+ cap = cv2.VideoCapture(0)
+ if not cap.isOpened():
+ raise RuntimeError("Webcam could not be opened.")
+
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ boxes, landmarks = detector.detect(frame)
+
+ for box, lm in zip(boxes, landmarks):
+ x1, y1, x2, y2 = map(int, box[:4])
+ embedding = recognizer.get_embedding(frame, lm)
+ sim = compute_similarity(ref_embedding, embedding)
+ label = f"Match ({sim:.2f})" if sim > threshold else f"Unknown ({sim:.2f})"
+ color = (0, 255, 0) if sim > threshold else (0, 0, 255)
+
+ cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
+ cv2.putText(frame, label, (x1, y1 - 10),
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
+
+ cv2.imshow("Face Recognition", frame)
+ if cv2.waitKey(1) & 0xFF == ord('q'):
+ break
+
+ cap.release()
+ cv2.destroyAllWindows()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Face recognition using a reference image.")
+ parser.add_argument("--image", type=str, required=True, help="Path to the reference face image.")
+ parser.add_argument("--model", type=str, default="MNET_V2",
+ choices=[m.name for m in RetinaFaceWeights], help="Face detector model.")
+ args = parser.parse_args()
+
+ detector = RetinaFace(model_name=RetinaFaceWeights[args.model])
+ recognizer = ArcFace()
+ ref_embedding = extract_reference_embedding(detector, recognizer, args.image)
+ run_video(detector, recognizer, ref_embedding)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/uniface/detection/retinaface.py b/uniface/detection/retinaface.py
index f786847..5e21dd5 100644
--- a/uniface/detection/retinaface.py
+++ b/uniface/detection/retinaface.py
@@ -23,30 +23,30 @@ from .utils import (
class RetinaFace:
"""
- A class for face detection using the RetinaFace model.
+ Face detector based on the RetinaFace architecture.
Args:
- model_name (RetinaFaceWeights): Name of the model. Defaults to "retinaface_mnet_v2".
- conf_thresh (float, optional): Confidence threshold for detections. Defaults to 0.5.
- nms_thresh (float, optional): Non-maximum suppression (NMS) threshold. Defaults to 0.4.
- pre_nms_topk (int, optional): Maximum number of detections considered before applying NMS. Defaults to 5000.
- post_nms_topk (int, optional): Maximum number of detections retained after NMS. Defaults to 750.
- dynamic_size (bool, optional): Whether to dynamically adjust anchor generation based on image size. Defaults to False.
- input_size (Tuple[int, int], optional): Static input size for the model (width, height). Used when `dynamic_size=False`. Defaults to (640, 640).
+ model_name (RetinaFaceWeights): Model weights to use. Defaults to `RetinaFaceWeights.MNET_V2`.
+ conf_thresh (float): Confidence threshold for filtering detections. Defaults to 0.5.
+ nms_thresh (float): Non-maximum suppression (NMS) threshold. Defaults to 0.4.
+ pre_nms_topk (int): Number of top-scoring boxes considered before applying NMS. Defaults to 5000.
+ post_nms_topk (int): Maximum number of final detections retained after NMS. Defaults to 750.
+ dynamic_size (bool): If True, anchors are generated dynamically per input image size. Defaults to False.
+ input_size (Tuple[int, int]): Fixed input size (width, height) used when `dynamic_size` is False. Ignored if `dynamic_size=True`.
Attributes:
- conf_thresh (float): Confidence threshold for filtering detections.
- nms_thresh (float): NMS threshold to remove duplicate detections.
- pre_nms_topk (int): Number of detections considered before applying NMS.
- post_nms_topk (int): Maximum number of detections retained after applying NMS.
- dynamic_size (bool): Whether the model dynamically adjusts input size and anchors.
- input_size (Tuple[int, int] or None): The model's fixed input size (if `dynamic_size=False`), otherwise None.
- _model_path (str): Verified path to the model weights.
- _priors (np.ndarray or None): Precomputed anchor boxes when using static input size. None if `dynamic_size=True`.
+ conf_thresh (float): Threshold for filtering detections based on confidence score.
+ nms_thresh (float): IoU threshold for NMS.
+ pre_nms_topk (int): Limit on boxes considered before NMS.
+ post_nms_topk (int): Limit on detections kept after NMS.
+ dynamic_size (bool): Whether anchors are generated dynamically.
+ input_size (Tuple[int, int]): Static input size when `dynamic_size` is False.
+ _model_path (str): Path to verified model weights. (Internal)
+ _priors (np.ndarray): Anchor boxes used for detection. Precomputed if static input size is used. (Internal)
Raises:
- ValueError: If the model weights cannot be found or verified.
- RuntimeError: If there is an error initializing the model.
+ ValueError: If model weights are invalid or not found.
+ RuntimeError: If the model fails to initialize.
"""
def __init__(
@@ -56,8 +56,8 @@ class RetinaFace:
nms_thresh: float = 0.4,
pre_nms_topk: int = 5000,
post_nms_topk: int = 750,
- dynamic_size: Optional[bool] = False,
- input_size: Optional[Tuple[int, int]] = (640, 640), # Default input size if dynamic_size=False
+ dynamic_size: bool = False,
+ input_size: Tuple[int, int] = (640, 640), # Default input size if dynamic_size=False
) -> None:
self.conf_thresh = conf_thresh
@@ -135,29 +135,26 @@ class RetinaFace:
def detect(
self,
image: np.ndarray,
- max_num: Optional[int] = 0,
+ max_num: int = 0,
metric: Literal["default", "max"] = "max",
- center_weight: Optional[float] = 2.0
+ center_weight: float = 2.0
) -> Tuple[np.ndarray, np.ndarray]:
"""
- Perform face detection on an input image and return bounding boxes and landmarks.
+ Perform face detection on an input image and return bounding boxes and facial landmarks.
Args:
- image (np.ndarray): Input image as a NumPy array of shape (height, width, channels).
- max_num (int, optional): Maximum number of detections to return. Defaults to 1.
- metric (str, optional): Metric for ranking detections when `max_num` is specified.
- Options:
+ image (np.ndarray): Input image as a NumPy array of shape (H, W, C).
+ max_num (int): Maximum number of detections to return. Use 0 to return all detections. Defaults to 0.
+ metric (Literal["default", "max"]): Metric for ranking detections when `max_num` is limited.
- "default": Prioritize detections closer to the image center.
- "max": Prioritize detections with larger bounding box areas.
- center_weight (float, optional): Weight for penalizing detections farther from the image center
+ center_weight (float): Weight for penalizing detections farther from the image center
when using the "default" metric. Defaults to 2.0.
Returns:
- Tuple[np.ndarray, np.ndarray]: Detection results containing:
- - detections (np.ndarray): Array of detected bounding boxes with confidence scores.
- Shape: (num_detections, 5), where each row is [x_min, y_min, x_max, y_max, score].
- - landmarks (np.ndarray): Array of detected facial landmarks.
- Shape: (num_detections, 5, 2), where each row contains 5 landmark points (x, y).
+ Tuple[np.ndarray, np.ndarray]:
+ - detections: Bounding boxes with confidence scores. Shape (N, 5), each row as [x_min, y_min, x_max, y_max, score].
+ - landmarks: Facial landmark coordinates. Shape (N, 5, 2), where each row contains 5 (x, y) points.
"""
original_height, original_width = image.shape[:2]
diff --git a/uniface/detection/scrfd.py b/uniface/detection/scrfd.py
index c874d67..135ed7a 100644
--- a/uniface/detection/scrfd.py
+++ b/uniface/detection/scrfd.py
@@ -1,14 +1,14 @@
# Copyright 2025 Yakhyokhuja Valikhujaev
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-# Modified from insightface repo
+# Modified from insightface repository
import os
import cv2
import numpy as np
import onnxruntime as ort
-from typing import Tuple, Optional, List, Literal
+from typing import Tuple, List, Literal
from uniface.log import Logger
from uniface.model_store import verify_model_weights
@@ -20,29 +20,29 @@ __all__ = ['SCRFD']
class SCRFD:
"""
- A class for face detection using the SCRFD model.
+ Face detector based on the SCRFD architecture.
Title: "Sample and Computation Redistribution for Efficient Face Detection"
Paper: https://arxiv.org/abs/2105.04714
Args:
- model_name (SCRFDWeights): Predefined model enum (e.g., SCRFD_10G_KPS). Specifies which SCRFD variant to load.
+ model_name (SCRFDWeights): Predefined model enum (e.g., `SCRFD_10G_KPS`). Specifies the SCRFD variant to load.
conf_thresh (float): Confidence threshold for filtering detections. Defaults to 0.5.
- nms_thresh (float): Non-Maximum Suppression threshold. Defaults to 0.4.
- input_size (Optional[Tuple[int, int]]): Input resolution (height, width) to which the image is resized. Defaults to (640, 640).
+ nms_thresh (float): Non-Maximum Suppression (NMS) threshold. Defaults to 0.4.
+ input_size (Tuple[int, int]): Target input resolution (width, height) to resize images. Defaults to (640, 640).
Attributes:
- conf_thresh (float): Confidence threshold used to filter raw detections.
- nms_thresh (float): NMS threshold to suppress overlapping detections.
- input_size (Tuple[int, int]): Target resolution for input resizing.
- _fmc (int): Number of feature map scales used in SCRFD.
- _feat_stride_fpn (List[int]): Stride values for each feature map.
- _num_anchors (int): Number of anchors per feature point.
- _center_cache (Dict): Cache of anchor centers for efficient inference.
- _model_path (str): Verified path to the downloaded model weights.
+ conf_thresh (float): Threshold used to filter low-confidence detections.
+ nms_thresh (float): Threshold used during NMS to suppress overlapping boxes.
+ input_size (Tuple[int, int]): Image size to which inputs are resized before inference.
+ _fmc (int): Number of feature map levels used in the model.
+ _feat_stride_fpn (List[int]): Feature map strides corresponding to each detection level.
+ _num_anchors (int): Number of anchors per feature location.
+ _center_cache (Dict): Cached anchor centers for efficient forward passes.
+ _model_path (str): Absolute path to the downloaded/verified model weights.
Raises:
- ValueError: If the model weights cannot be found or verified.
+ ValueError: If the model weights are invalid or not found.
RuntimeError: If the ONNX model fails to load or initialize.
"""
@@ -51,18 +51,17 @@ class SCRFD:
model_name: SCRFDWeights = SCRFDWeights.SCRFD_10G_KPS,
conf_thresh: float = 0.5,
nms_thresh: float = 0.4,
- input_size: Optional[Tuple[int, int]] = (640, 640),
+ input_size: Tuple[int, int] = (640, 640),
) -> None:
self.conf_thresh = conf_thresh
self.nms_thresh = nms_thresh
self.input_size = input_size
- # SCRFD model params --------------
+ # ------- SCRFD model params ------
self._fmc = 3
self._feat_stride_fpn = [8, 16, 32]
self._num_anchors = 2
-
self._center_cache = {}
# ---------------------------------
@@ -176,10 +175,27 @@ class SCRFD:
def detect(
self,
image: np.ndarray,
- max_num: Optional[int] = 0,
+ max_num: int = 0,
metric: Literal["default", "max"] = "max",
- center_weight: Optional[float] = 2
+ center_weight: float = 2
) -> Tuple[np.ndarray, np.ndarray]:
+ """
+ Perform face detection on an input image and return bounding boxes and facial landmarks.
+
+ Args:
+ image (np.ndarray): Input image as a NumPy array of shape (H, W, C).
+ max_num (int): Maximum number of detections to return. Use 0 to return all detections. Defaults to 0.
+ metric (Literal["default", "max"]): Metric for ranking detections when `max_num` is limited.
+ - "default": Prioritize detections closer to the image center.
+ - "max": Prioritize detections with larger bounding box areas.
+ center_weight (float): Weight for penalizing detections farther from the image center
+ when using the "default" metric. Defaults to 2.0.
+
+ Returns:
+ Tuple[np.ndarray, np.ndarray]:
+ - detections: Bounding boxes with confidence scores. Shape (N, 5), each row as [x_min, y_min, x_max, y_max, score].
+ - landmarks: Facial landmark coordinates. Shape (N, 5, 2), where each row contains 5 (x, y) points.
+ """
original_height, original_width = image.shape[:2]
@@ -237,6 +253,7 @@ class SCRFD:
return det, landmarks
+# TODO: below is only for testing, remove it later
def draw_bbox(frame, bbox, color=(0, 255, 0), thickness=2):
x1, y1, x2, y2 = bbox[:4].astype(np.int32)
@@ -251,7 +268,7 @@ def draw_keypoints(frame, points, color=(0, 0, 255), radius=2):
if __name__ == "__main__":
- detector = SCRFD()
+ detector = SCRFD(model_name=SCRFDWeights.SCRFD_500M_KPS)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
diff --git a/uniface/face_utils.py b/uniface/face_utils.py
index a3229b4..55a3e76 100644
--- a/uniface/face_utils.py
+++ b/uniface/face_utils.py
@@ -82,20 +82,23 @@ def face_alignment(image: np.ndarray, landmark: np.ndarray, image_size: int = 11
return warped, M_inv
-def compute_similarity(feat1: np.ndarray, feat2: np.ndarray) -> np.float32:
+def compute_similarity(feat1: np.ndarray, feat2: np.ndarray, normalized: bool=False) -> np.float32:
"""Computing Similarity between two faces.
Args:
- feat1 (np.ndarray): Face features.
- feat2 (np.ndarray): Face features.
+ feat1 (np.ndarray): First embedding.
+ feat2 (np.ndarray): Second embedding.
+ normalized (bool): Set True if the embeddings are already L2 normalized.
Returns:
- np.float32: Cosine similarity between face features.
+ np.float32: Cosine similarity.
"""
feat1 = feat1.ravel()
feat2 = feat2.ravel()
- similarity = np.dot(feat1, feat2) / (np.linalg.norm(feat1) * np.linalg.norm(feat2))
- return similarity
+ if normalize:
+ return np.dot(feat1, feat2)
+ else:
+ return np.dot(feat1, feat2) / (np.linalg.norm(feat1) * np.linalg.norm(feat2) + 1e-5)
def bbox_center_alignment(image, center, output_size, scale, rotation):
diff --git a/uniface/recognition/base.py b/uniface/recognition/base.py
index c793569..c82cc4e 100644
--- a/uniface/recognition/base.py
+++ b/uniface/recognition/base.py
@@ -1,6 +1,7 @@
# Copyright 2025 Yakhyokhuja Valikhujaev
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
+# Modified from insightface repository
import os
import cv2
@@ -10,11 +11,10 @@ import onnxruntime as ort
from typing import Tuple, Optional, Union, List
from dataclasses import dataclass
-
-from uniface.face_utils import compute_similarity, face_alignment
+from uniface.log import Logger
from uniface.model_store import verify_model_weights
-from uniface.constants import SphereFaceWeights, MobileFaceWeights
-from uniface.logger import Logger
+from uniface.face_utils import compute_similarity, face_alignment
+from uniface.constants import SphereFaceWeights, MobileFaceWeights, ArcFaceWeights
__all__ = ["BaseFaceEncoder", "PreprocessConfig"]
@@ -37,23 +37,30 @@ class BaseFaceEncoder:
def __init__(
self,
- model_path: Optional[SphereFaceWeights | MobileFaceWeights] = MobileFaceWeights.MNET_V2,
+ model_name: SphereFaceWeights | MobileFaceWeights | ArcFaceWeights = MobileFaceWeights.MNET_V2,
preprocessing: PreprocessConfig = PreprocessConfig(),
) -> None:
"""
Initializes the FaceEncoder model for inference.
Args:
- model_path (Optional[SphereFaceWeights | MobileFaceWeights]): Path to the ONNX model file.
+ model_name (SphereFaceWeights | MobileFaceWeights | ArcFaceWeights): Selected model weight enum.
+ preprocessing (PreprocessConfig): Configuration for input normalization and resizing.
"""
self.input_mean = preprocessing.input_mean
self.input_std = preprocessing.input_std
- self.input_size = input_size.input_size
+ self.input_size = preprocessing.input_size
+
+ Logger.info(
+ f"Initializing Face Recognition with model={model_name}, "
+ f"input_mean={self.input_mean}, input_std={self.input_std}, input_size={self.input_size}"
+ )
# Get path to model weights
- self._model_path = verify_model_weights(model_path)
+ self._model_path = verify_model_weights(model_name)
Logger.info(f"Verfied model weights located at: {self._model_path}")
+ # Initialize model
self._initialize_model(self._model_path)
def _initialize_model(self, model_path: str) -> None:
diff --git a/uniface/recognition/models.py b/uniface/recognition/models.py
index cb41ed9..9b93176 100644
--- a/uniface/recognition/models.py
+++ b/uniface/recognition/models.py
@@ -4,8 +4,8 @@
from typing import Optional
-from .base import BaseFaceEncoder, PreprocessCo1nfig
from uniface.constants import SphereFaceWeights, MobileFaceWeights, ArcFaceWeights
+from .base import BaseFaceEncoder, PreprocessConfig
__all__ = ["SphereFace", "MobileFace", "ArcFace"]
@@ -13,7 +13,7 @@ __all__ = ["SphereFace", "MobileFace", "ArcFace"]
class SphereFace(BaseFaceEncoder):
def __init__(
- self, model_path: Optional[SphereFaceWeights] = SphereFaceWeights.SPHERE20,
+ self, model_name: SphereFaceWeights = SphereFaceWeights.SPHERE20,
preprocessing: Optional[PreprocessConfig] = None
) -> None:
if preprocessing is None:
@@ -22,12 +22,12 @@ class SphereFace(BaseFaceEncoder):
input_std=127.5,
input_size=(112, 112)
)
- super().__init__(model_path=model_path, preprocessing=preprocessing)
+ super().__init__(model_name=model_name, preprocessing=preprocessing)
class MobileFace(BaseFaceEncoder):
def __init__(
- self, model_path: Optional[MobileFaceWeights] = MobileFaceWeights.MNET_V2,
+ self, model_name: MobileFaceWeights = MobileFaceWeights.MNET_V2,
preprocessing: Optional[PreprocessConfig] = None
) -> None:
if preprocessing is None:
@@ -36,12 +36,12 @@ class MobileFace(BaseFaceEncoder):
input_std=127.5,
input_size=(112, 112)
)
- super().__init__(model_path=model_path)
+ super().__init__(model_name=model_name)
class ArcFace(BaseFaceEncoder):
def __init__(
- self, model_path: Optional[ArcFaceWeights] = ArcFaceWeights.MNET,
+ self, model_name: ArcFaceWeights = ArcFaceWeights.MNET,
preprocessing: Optional[PreprocessConfig] = None
) -> None:
if preprocessing is None:
@@ -50,4 +50,4 @@ class ArcFace(BaseFaceEncoder):
input_std=127.5,
input_size=(112, 112)
)
- super().__init__(model_path=model_path)
+ super().__init__(model_name=model_name)
diff --git a/uniface/retinaface.py b/uniface/retinaface.py
index abbc5c4..876de8d 100644
--- a/uniface/retinaface.py
+++ b/uniface/retinaface.py
@@ -7,7 +7,7 @@ import cv2
import numpy as np
import onnxruntime as ort
-from typing import Tuple, List, Optional, Literal
+from typing import Tuple, List, Literal
from uniface.log import Logger
from uniface.model_store import verify_model_weights
@@ -23,30 +23,30 @@ from uniface.common import (
class RetinaFace:
"""
- A class for face detection using the RetinaFace model.
+ Face detector based on the RetinaFace architecture.
Args:
- model_name (RetinaFaceWeights): Name of the model. Defaults to "retinaface_mnet_v2".
- conf_thresh (float, optional): Confidence threshold for detections. Defaults to 0.5.
- nms_thresh (float, optional): Non-maximum suppression (NMS) threshold. Defaults to 0.4.
- pre_nms_topk (int, optional): Maximum number of detections considered before applying NMS. Defaults to 5000.
- post_nms_topk (int, optional): Maximum number of detections retained after NMS. Defaults to 750.
- dynamic_size (bool, optional): Whether to dynamically adjust anchor generation based on image size. Defaults to False.
- input_size (Tuple[int, int], optional): Static input size for the model (width, height). Used when `dynamic_size=False`. Defaults to (640, 640).
+ model_name (RetinaFaceWeights): Model weights to use. Defaults to `RetinaFaceWeights.MNET_V2`.
+ conf_thresh (float): Confidence threshold for filtering detections. Defaults to 0.5.
+ nms_thresh (float): Non-maximum suppression (NMS) threshold. Defaults to 0.4.
+ pre_nms_topk (int): Number of top-scoring boxes considered before applying NMS. Defaults to 5000.
+ post_nms_topk (int): Maximum number of final detections retained after NMS. Defaults to 750.
+ dynamic_size (bool): If True, anchors are generated dynamically per input image size. Defaults to False.
+ input_size (Tuple[int, int]): Fixed input size (width, height) used when `dynamic_size` is False. Ignored if `dynamic_size=True`.
Attributes:
- conf_thresh (float): Confidence threshold for filtering detections.
- nms_thresh (float): NMS threshold to remove duplicate detections.
- pre_nms_topk (int): Number of detections considered before applying NMS.
- post_nms_topk (int): Maximum number of detections retained after applying NMS.
- dynamic_size (bool): Whether the model dynamically adjusts input size and anchors.
- input_size (Tuple[int, int] or None): The model's fixed input size (if `dynamic_size=False`), otherwise None.
- _model_path (str): Verified path to the model weights.
- _priors (np.ndarray or None): Precomputed anchor boxes when using static input size. None if `dynamic_size=True`.
+ conf_thresh (float): Threshold for filtering detections based on confidence score.
+ nms_thresh (float): IoU threshold for NMS.
+ pre_nms_topk (int): Limit on boxes considered before NMS.
+ post_nms_topk (int): Limit on detections kept after NMS.
+ dynamic_size (bool): Whether anchors are generated dynamically.
+ input_size (Tuple[int, int]): Static input size when `dynamic_size` is False.
+ _model_path (str): Path to verified model weights. (Internal)
+ _priors (np.ndarray): Anchor boxes used for detection. Precomputed if static input size is used. (Internal)
Raises:
- ValueError: If the model weights cannot be found or verified.
- RuntimeError: If there is an error initializing the model.
+ ValueError: If model weights are invalid or not found.
+ RuntimeError: If the model fails to initialize.
"""
def __init__(
@@ -56,8 +56,8 @@ class RetinaFace:
nms_thresh: float = 0.4,
pre_nms_topk: int = 5000,
post_nms_topk: int = 750,
- dynamic_size: Optional[bool] = False,
- input_size: Optional[Tuple[int, int]] = (640, 640), # Default input size if dynamic_size=False
+ dynamic_size: bool = False,
+ input_size: Tuple[int, int] = (640, 640), # Default input size if dynamic_size=False
) -> None:
self.conf_thresh = conf_thresh
@@ -135,29 +135,26 @@ class RetinaFace:
def detect(
self,
image: np.ndarray,
- max_num: Optional[int] = 0,
+ max_num: int = 0,
metric: Literal["default", "max"] = "max",
- center_weight: Optional[float] = 2.0
+ center_weight: float = 2.0
) -> Tuple[np.ndarray, np.ndarray]:
"""
- Perform face detection on an input image and return bounding boxes and landmarks.
+ Perform face detection on an input image and return bounding boxes and facial landmarks.
Args:
- image (np.ndarray): Input image as a NumPy array of shape (height, width, channels).
- max_num (int, optional): Maximum number of detections to return. Defaults to 1.
- metric (str, optional): Metric for ranking detections when `max_num` is specified.
- Options:
+ image (np.ndarray): Input image as a NumPy array of shape (H, W, C).
+ max_num (int): Maximum number of detections to return. Use 0 to return all detections. Defaults to 0.
+ metric (Literal["default", "max"]): Metric for ranking detections when `max_num` is limited.
- "default": Prioritize detections closer to the image center.
- "max": Prioritize detections with larger bounding box areas.
- center_weight (float, optional): Weight for penalizing detections farther from the image center
+ center_weight (float): Weight for penalizing detections farther from the image center
when using the "default" metric. Defaults to 2.0.
Returns:
- Tuple[np.ndarray, np.ndarray]: Detection results containing:
- - detections (np.ndarray): Array of detected bounding boxes with confidence scores.
- Shape: (num_detections, 5), where each row is [x_min, y_min, x_max, y_max, score].
- - landmarks (np.ndarray): Array of detected facial landmarks.
- Shape: (num_detections, 5, 2), where each row contains 5 landmark points (x, y).
+ Tuple[np.ndarray, np.ndarray]:
+ - detections: Bounding boxes with confidence scores. Shape (N, 5), each row as [x_min, y_min, x_max, y_max, score].
+ - landmarks: Facial landmark coordinates. Shape (N, 5, 2), where each row contains 5 (x, y) points.
"""
original_height, original_width = image.shape[:2]