UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.
Python computer-visiondeep-learningface-alignmentface-analysisface-anonymizationface-anti-spoofingface-attributesface-detectionface-meshface-parsingface-quality-assessmentface-recognitionface-segmentationface-trackingfacial-landmarksgaze-estimationhead-pose-estimationonnxruntimeportrait-mattingpython
ref: Some minor changes and additional models
yakhyocee2b692add6
diff --git a/scripts/run_inference.py b/scripts/run_inference.pyindex 48c9bcc..f95376d 100644--- a/scripts/run_inference.py+++ b/scripts/run_inference.py@@ -4,7 +4,7 @@ import timeimport argparseimport numpy as np-from uniface import RetinaFace, draw_detections+from uniface.detection import RetinaFace, draw_detectionsfrom uniface.constants import RetinaFaceWeightsdiff --git a/uniface/detection/__init__.py b/uniface/detection/__init__.pynew file mode 100644index 0000000..c669d8b--- /dev/null+++ b/uniface/detection/__init__.py@@ -0,0 +1,2 @@+from .retinaface import RetinaFace+from uniface.visualization import draw_detectionsdiff --git a/uniface/detection/retinaface.py b/uniface/detection/retinaface.pynew file mode 100644index 0000000..98a86ad--- /dev/null+++ b/uniface/detection/retinaface.py@@ -0,0 +1,262 @@+# Copyright 2025 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++import os+import cv2+import numpy as np+import onnxruntime as ort++from typing import Tuple, List, Optional, Literal++from uniface.log import Logger+from uniface.model_store import verify_model_weights+from uniface.constants import RetinaFaceWeights+from .utils import (+ non_max_supression,+ resize_image,+ decode_boxes,+ generate_anchors,+ decode_landmarks+)+++class RetinaFace:+ """+ A class for face detection using the RetinaFace model.++ 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).++ 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`.++ Raises:+ ValueError: If the model weights cannot be found or verified.+ RuntimeError: If there is an error initializing the model.+ """++ def __init__(+ self,+ model_name: RetinaFaceWeights = RetinaFaceWeights.MNET_V2,+ conf_thresh: float = 0.5,+ 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+ ) -> None:++ self.conf_thresh = conf_thresh+ self.nms_thresh = nms_thresh+ self.pre_nms_topk = pre_nms_topk+ self.post_nms_topk = post_nms_topk+ self.dynamic_size = dynamic_size+ self.input_size = input_size++ Logger.info(+ f"Initializing RetinaFace with model={model_name}, conf_thresh={conf_thresh}, nms_thresh={nms_thresh}, "+ f"pre_nms_topk={pre_nms_topk}, post_nms_topk={post_nms_topk}, dynamic_size={dynamic_size}, "+ f"input_size={input_size}"+ )++ # Get path to model weights+ self._model_path = verify_model_weights(model_name)+ Logger.info(f"Verified model weights located at: {self._model_path}")++ # Precompute anchors if using static size+ if not dynamic_size and input_size is not None:+ self._priors = generate_anchors(image_size=input_size)+ Logger.debug("Generated anchors for static input size.")++ # Initialize model+ self._initialize_model(self._model_path)++ def _initialize_model(self, model_path: str) -> None:+ """+ Initializes an ONNX model session from the given path.++ Args:+ model_path (str): The file path to the ONNX model.++ Raises:+ RuntimeError: If the model fails to load, logs an error and raises an exception.+ """+ try:+ self.session = ort.InferenceSession(+ model_path,+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"]+ )+ self.input_name = self.session.get_inputs()[0].name+ Logger.info(f"Successfully initialized the model from {model_path}")+ except Exception as e:+ Logger.error(f"Failed to load model from '{model_path}': {e}", exc_info=True)+ raise RuntimeError(f"Failed to initialize model session for '{model_path}'") from e++ def preprocess(self, image: np.ndarray) -> np.ndarray:+ """Preprocess input image for model inference.++ Args:+ image (np.ndarray): Input image.++ Returns:+ np.ndarray: Preprocessed image tensor with shape (1, C, H, W)+ """+ image = np.float32(image) - np.array([104, 117, 123], dtype=np.float32)+ image = image.transpose(2, 0, 1) # HWC to CHW+ image = np.expand_dims(image, axis=0) # Add batch dimension (1, C, H, W)+ return image++ def inference(self, input_tensor: np.ndarray) -> List[np.ndarray]:+ """Perform model inference on the preprocessed image tensor.++ Args:+ input_tensor (np.ndarray): Preprocessed input tensor.++ Returns:+ Tuple[np.ndarray, np.ndarray]: Raw model outputs.+ """+ return self.session.run(None, {self.input_name: input_tensor})++ def detect(+ self,+ image: np.ndarray,+ max_num: Optional[int] = 0,+ metric: Literal["default", "max"] = "default",+ center_weight: Optional[float] = 2.0+ ) -> Tuple[np.ndarray, np.ndarray]:+ """+ Perform face detection on an input image and return bounding boxes and 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:+ - "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+ 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).+ """++ if self.dynamic_size:+ height, width, _ = image.shape+ self._priors = generate_anchors(image_size=(height, width)) # generate anchors for each input image+ resize_factor = 1.0 # No resizing+ else:+ image, resize_factor = resize_image(image, target_shape=self.input_size)++ height, width, _ = image.shape+ image_tensor = self.preprocess(image)++ # ONNXRuntime inference+ outputs = self.inference(image_tensor)++ # Postprocessing+ detections, landmarks = self.postprocess(outputs, resize_factor, shape=(width, height))++ if max_num > 0 and detections.shape[0] > max_num:+ # Calculate area of detections+ areas = (detections[:, 2] - detections[:, 0]) * (detections[:, 3] - detections[:, 1])++ # Calculate offsets from image center+ center = (height // 2, width // 2)+ offsets = np.vstack([+ (detections[:, 0] + detections[:, 2]) / 2 - center[1],+ (detections[:, 1] + detections[:, 3]) / 2 - center[0]+ ])+ offset_dist_squared = np.sum(np.power(offsets, 2.0), axis=0)++ # Calculate scores based on the chosen metric+ if metric == 'max':+ scores = areas+ else:+ scores = areas - offset_dist_squared * center_weight++ # Sort by scores and select top `max_num`+ sorted_indices = np.argsort(scores)[::-1][:max_num]++ detections = detections[sorted_indices]+ landmarks = landmarks[sorted_indices]++ return detections, landmarks++ def postprocess(self, outputs: List[np.ndarray], resize_factor: float, shape: Tuple[int, int]) -> Tuple[np.ndarray, np.ndarray]:+ """+ Process the model outputs into final detection results.++ Args:+ outputs (List[np.ndarray]): Raw outputs from the detection model.+ - outputs[0]: Location predictions (bounding box coordinates).+ - outputs[1]: Class confidence scores.+ - outputs[2]: Landmark predictions.+ resize_factor (float): Factor used to resize the input image during preprocessing.+ shape (Tuple[int, int]): Original shape of the image as (height, width).++ Returns:+ Tuple[np.ndarray, np.ndarray]: Processed 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).+ """+ loc, conf, landmarks = outputs[0].squeeze(0), outputs[1].squeeze(0), outputs[2].squeeze(0)++ # Decode boxes and landmarks+ boxes = decode_boxes(loc, self._priors)+ landmarks = decode_landmarks(landmarks, self._priors)++ boxes, landmarks = self._scale_detections(boxes, landmarks, resize_factor, shape=(shape[0], shape[1]))++ # Extract confidence scores for the face class+ scores = conf[:, 1]+ mask = scores > self.conf_thresh++ # Filter by confidence threshold+ boxes, landmarks, scores = boxes[mask], landmarks[mask], scores[mask]++ # Sort by scores+ order = scores.argsort()[::-1][:self.pre_nms_topk]+ boxes, landmarks, scores = boxes[order], landmarks[order], scores[order]++ # Apply NMS+ detections = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)+ keep = non_max_supression(detections, self.nms_thresh)+ detections, landmarks = detections[keep], landmarks[keep]++ # Keep top-k detections+ detections, landmarks = detections[:self.post_nms_topk], landmarks[:self.post_nms_topk]++ landmarks = landmarks.reshape(-1, 5, 2).astype(np.int32)++ return detections, landmarks++ def _scale_detections(self, boxes: np.ndarray, landmarks: np.ndarray, resize_factor: float, shape: Tuple[int, int]) -> Tuple[np.ndarray, np.ndarray]:+ """Scale bounding boxes and landmarks to the original image size."""+ bbox_scale = np.array([shape[0], shape[1]] * 2)+ boxes = boxes * bbox_scale / resize_factor++ landmark_scale = np.array([shape[0], shape[1]] * 5)+ landmarks = landmarks * landmark_scale / resize_factor++ return boxes, landmarksdiff --git a/uniface/detection/scrfd.py b/uniface/detection/scrfd.pynew file mode 100644index 0000000..bac7eeb--- /dev/null+++ b/uniface/detection/scrfd.py@@ -0,0 +1,184 @@+import os+import cv2+import numpy as np+import onnxruntime++from typing import Tuple++from uniface.logger import Logger+from .utils import non_max_supression, distance2bbox, distance2kps++__all__ = ['SCRFD']+++++class SCRFD:+ """+ Title: "Sample and Computation Redistribution for Efficient Face Detection"+ Paper: https://arxiv.org/abs/2105.04714+ """++ def __init__(+ self,+ model_path: str,+ input_size: Tuple[int] = (640, 640),+ conf_thres: float = 0.5,+ iou_thres: float = 0.4+ ) -> None:+ """SCRFD initialization++ Args:+ model_path (str): Path model .onnx file.+ input_size (int): Input image size. Defaults to (640, 640)+ max_num (int): Maximum number of detections+ conf_thres (float, optional): Confidence threshold. Defaults to 0.5.+ iou_thres (float, optional): Non-max supression (NMS) threshold. Defaults to 0.4.+ """++ self.input_size = input_size+ self.conf_thres = conf_thres+ self.iou_thres = iou_thres++ # SCRFD model params --------------+ self.fmc = 3+ self._feat_stride_fpn = [8, 16, 32]+ self._num_anchors = 2+ self.use_kps = True++ self.mean = 127.5+ self.std = 128.0++ self.center_cache = {}+ # ---------------------------------++ self._initialize_model(model_path=model_path)++ def _initialize_model(self, model_path: str):+ """Initialize the model from the given path.++ Args:+ model_path (str): Path to .onnx model.+ """+ try:+ self.session = onnxruntime.InferenceSession(+ model_path,+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"]+ )+ # Get model info+ self.output_names = [x.name for x in self.session.get_outputs()]+ self.input_names = [x.name for x in self.session.get_inputs()]+ except Exception as e:+ print(f"Failed to load the model: {e}")+ raise++ def forward(self, image, threshold):+ scores_list = []+ bboxes_list = []+ kpss_list = []+ input_size = tuple(image.shape[0:2][::-1])++ blob = cv2.dnn.blobFromImage(+ image,+ 1.0 / self.std,+ input_size,+ (self.mean, self.mean, self.mean),+ swapRB=True+ )+ outputs = self.session.run(self.output_names, {self.input_names[0]: blob})++ input_height = blob.shape[2]+ input_width = blob.shape[3]++ fmc = self.fmc+ for idx, stride in enumerate(self._feat_stride_fpn):+ scores = outputs[idx]+ bbox_preds = outputs[idx + fmc]+ bbox_preds = bbox_preds * stride+ if self.use_kps:+ kps_preds = outputs[idx + fmc * 2] * stride++ height = input_height // stride+ width = input_width // stride+ key = (height, width, stride)+ if key in self.center_cache:+ anchor_centers = self.center_cache[key]+ else:+ anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32)+ anchor_centers = (anchor_centers * stride).reshape((-1, 2))+ if self._num_anchors > 1:+ anchor_centers = np.stack([anchor_centers] * self._num_anchors, axis=1).reshape((-1, 2))+ if len(self.center_cache) < 100:+ self.center_cache[key] = anchor_centers++ pos_inds = np.where(scores >= threshold)[0]+ bboxes = distance2bbox(anchor_centers, bbox_preds)+ pos_scores = scores[pos_inds]+ pos_bboxes = bboxes[pos_inds]+ scores_list.append(pos_scores)+ bboxes_list.append(pos_bboxes)+ if self.use_kps:+ kpss = distance2kps(anchor_centers, kps_preds)+ kpss = kpss.reshape((kpss.shape[0], -1, 2))+ pos_kpss = kpss[pos_inds]+ kpss_list.append(pos_kpss)+ return scores_list, bboxes_list, kpss_list++ def detect(self, image, max_num=0, metric="max"):+ width, height = self.input_size++ im_ratio = float(image.shape[0]) / image.shape[1]+ model_ratio = height / width+ if im_ratio > model_ratio:+ new_height = height+ new_width = int(new_height / im_ratio)+ else:+ new_width = width+ new_height = int(new_width * im_ratio)++ det_scale = float(new_height) / image.shape[0]+ resized_image = cv2.resize(image, (new_width, new_height))++ det_image = np.zeros((height, width, 3), dtype=np.uint8)+ det_image[:new_height, :new_width, :] = resized_image++ scores_list, bboxes_list, kpss_list = self.forward(det_image, self.conf_thres)++ scores = np.vstack(scores_list)+ scores_ravel = scores.ravel()+ order = scores_ravel.argsort()[::-1]+ bboxes = np.vstack(bboxes_list) / det_scale++ if self.use_kps:+ kpss = np.vstack(kpss_list) / det_scale++ pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False)+ pre_det = pre_det[order, :]+ keep = non_max_supression(pre_det, iou_thres=self.iou_thres)+ det = pre_det[keep, :]+ if self.use_kps:+ kpss = kpss[order, :, :]+ kpss = kpss[keep, :, :]+ else:+ kpss = None+ if 0 < max_num < det.shape[0]:+ area = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])+ image_center = image.shape[0] // 2, image.shape[1] // 2+ offsets = np.vstack(+ [+ (det[:, 0] + det[:, 2]) / 2 - image_center[1],+ (det[:, 1] + det[:, 3]) / 2 - image_center[0],+ ]+ )+ offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)+ if metric == "max":+ values = area+ else:+ values = (area - offset_dist_squared * 2.0) # some extra weight on the centering+ bindex = np.argsort(values)[::-1]+ bindex = bindex[0:max_num]+ det = det[bindex, :]+ if kpss is not None:+ kpss = kpss[bindex, :]+ return det, kpss+diff --git a/uniface/detection/utils.py b/uniface/detection/utils.pynew file mode 100644index 0000000..f93eeca--- /dev/null+++ b/uniface/detection/utils.py@@ -0,0 +1,232 @@+# Copyright 2025 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++import cv2+import math+import itertools+import numpy as np++from typing import Tuple, List+++def resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]:+ """+ Resize an image to fit within a target shape while keeping its aspect ratio.++ Args:+ frame (np.ndarray): Input image.+ target_shape (Tuple[int, int]): Target size (width, height). Defaults to (640, 640).++ Returns:+ Tuple[np.ndarray, float]: Resized image on a blank canvas and the resize factor.+ """+ width, height = target_shape++ # Aspect-ratio preserving resize+ im_ratio = float(frame.shape[0]) / frame.shape[1]+ model_ratio = height / width+ if im_ratio > model_ratio:+ new_height = height+ new_width = int(new_height / im_ratio)+ else:+ new_width = width+ new_height = int(new_width * im_ratio)++ resize_factor = float(new_height) / frame.shape[0]+ resized_frame = cv2.resize(frame, (new_width, new_height))++ # Create blank image and place resized image on it+ image = np.zeros((height, width, 3), dtype=np.uint8)+ image[:new_height, :new_width, :] = resized_frame++ return image, resize_factor+++def generate_anchors(image_size: Tuple[int, int] = (640, 640)) -> np.ndarray:+ """+ Generate anchor boxes for a given image size.++ Args:+ image_size (Tuple[int, int]): Input image size (width, height). Defaults to (640, 640).++ Returns:+ np.ndarray: Anchor box coordinates as a NumPy array.+ """+ image_size = image_size++ steps = [8, 16, 32]+ min_sizes = [[16, 32], [64, 128], [256, 512]]++ anchors = []+ feature_maps = [+ [+ math.ceil(image_size[0] / step),+ math.ceil(image_size[1] / step)+ ] for step in steps+ ]++ for k, (map_height, map_width) in enumerate(feature_maps):+ step = steps[k]+ for i, j in itertools.product(range(map_height), range(map_width)):+ for min_size in min_sizes[k]:+ s_kx = min_size / image_size[1]+ s_ky = min_size / image_size[0]++ dense_cx = [x * step / image_size[1] for x in [j + 0.5]]+ dense_cy = [y * step / image_size[0] for y in [i + 0.5]]+ for cy, cx in itertools.product(dense_cy, dense_cx):+ anchors += [cx, cy, s_kx, s_ky]++ output = np.array(anchors, dtype=np.float32).reshape(-1, 4)+ return output+++def non_max_supression(dets: List[np.ndarray], threshold: float):+ """+ Apply Non-Maximum Suppression (NMS) to reduce overlapping bounding boxes based on a threshold.++ Args:+ dets (numpy.ndarray): Array of detections with each row as [x1, y1, x2, y2, score].+ threshold (float): IoU threshold for suppression.++ Returns:+ list: Indices of bounding boxes retained after suppression.+ """+ x1 = dets[:, 0]+ y1 = dets[:, 1]+ x2 = dets[:, 2]+ y2 = dets[:, 3]+ scores = dets[:, 4]++ areas = (x2 - x1 + 1) * (y2 - y1 + 1)+ order = scores.argsort()[::-1]++ keep = []+ while order.size > 0:+ i = order[0]+ keep.append(i)+ xx1 = np.maximum(x1[i], x1[order[1:]])+ yy1 = np.maximum(y1[i], y1[order[1:]])+ xx2 = np.minimum(x2[i], x2[order[1:]])+ yy2 = np.minimum(y2[i], y2[order[1:]])++ w = np.maximum(0.0, xx2 - xx1 + 1)+ h = np.maximum(0.0, yy2 - yy1 + 1)+ inter = w * h+ ovr = inter / (areas[i] + areas[order[1:]] - inter)++ inds = np.where(ovr <= threshold)[0]+ order = order[inds + 1]++ return keep+++def decode_boxes(loc, priors, variances=[0.1, 0.2]) -> np.ndarray:+ """+ Decode locations from predictions using priors to undo+ the encoding done for offset regression at train time.++ Args:+ loc (np.ndarray): Location predictions for loc layers, shape: [num_priors, 4]+ priors (np.ndarray): Prior boxes in center-offset form, shape: [num_priors, 4]+ variances (list[float]): Variances of prior boxes++ Returns:+ np.ndarray: Decoded bounding box predictions+ """+ # Compute centers of predicted boxes+ cxcy = priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:]++ # Compute widths and heights of predicted boxes+ wh = priors[:, 2:] * np.exp(loc[:, 2:] * variances[1])++ # Convert center, size to corner coordinates+ boxes = np.zeros_like(loc)+ boxes[:, :2] = cxcy - wh / 2 # xmin, ymin+ boxes[:, 2:] = cxcy + wh / 2 # xmax, ymax++ return boxes+++def decode_landmarks(predictions, priors, variances=[0.1, 0.2]) -> np.ndarray:+ """+ Decode landmark predictions using prior boxes.++ Args:+ predictions (np.ndarray): Landmark predictions, shape: [num_priors, 10]+ priors (np.ndarray): Prior boxes, shape: [num_priors, 4]+ variances (list): Scaling factors for landmark offsets.++ Returns:+ np.ndarray: Decoded landmarks, shape: [num_priors, 10]+ """++ # Reshape predictions to [num_priors, 5, 2] to process landmark points+ predictions = predictions.reshape(predictions.shape[0], 5, 2)++ # Expand priors to match (num_priors, 5, 2)+ priors_xy = np.repeat(priors[:, :2][:, np.newaxis, :], 5, axis=1) # (num_priors, 5, 2)+ priors_wh = np.repeat(priors[:, 2:][:, np.newaxis, :], 5, axis=1) # (num_priors, 5, 2)++ # Compute absolute landmark positions+ landmarks = priors_xy + predictions * variances[0] * priors_wh++ # Flatten back to [num_priors, 10]+ landmarks = landmarks.reshape(landmarks.shape[0], -1)++ return landmarks+++def distance2bbox(points, distance, max_shape=None):+ """Decode distance prediction to bounding box.++ Args:+ points (Tensor): Shape (n, 2), [x, y].+ distance (Tensor): Distance from the given point to 4+ boundaries (left, top, right, bottom).+ max_shape (tuple): Shape of the image.++ Returns:+ Tensor: Decoded bounding boxes with shape (n, 4).+ """+ x1 = points[:, 0] - distance[:, 0]+ y1 = points[:, 1] - distance[:, 1]+ x2 = points[:, 0] + distance[:, 2]+ y2 = points[:, 1] + distance[:, 3]+ if max_shape is not None:+ x1 = x1.clamp(min=0, max=max_shape[1])+ y1 = y1.clamp(min=0, max=max_shape[0])+ x2 = x2.clamp(min=0, max=max_shape[1])+ y2 = y2.clamp(min=0, max=max_shape[0])+ else:+ x1 = np.maximum(x1, 0)+ y1 = np.maximum(y1, 0)+ x2 = np.maximum(x2, 0)+ y2 = np.maximum(y2, 0)++ return np.stack([x1, y1, x2, y2], axis=-1)+++def distance2kps(points, distance, max_shape=None):+ """Decode distance prediction to keypoints.++ Args:+ points (Tensor): Shape (n, 2), [x, y].+ distance (Tensor): Distance from the given point to 4+ boundaries (left, top, right, bottom).+ max_shape (tuple): Shape of the image.++ Returns:+ Tensor: Decoded keypoints with shape (n, 2k).+ """+ preds = []+ for i in range(0, distance.shape[1], 2):+ px = points[:, i % 2] + distance[:, i]+ py = points[:, i % 2 + 1] + distance[:, i + 1]+ if max_shape is not None:+ px = px.clamp(min=0, max=max_shape[1])+ py = py.clamp(min=0, max=max_shape[0])+ preds.append(px)+ preds.append(py)+ return np.stack(preds, axis=-1)diff --git a/uniface/recognition/models.py b/uniface/recognition/models.pyindex 597d1b2..cb41ed9 100644--- a/uniface/recognition/models.py+++ b/uniface/recognition/models.py@@ -4,7 +4,7 @@from typing import Optional-from .base import BaseFaceEncoder, PreprocessConfig+from .base import BaseFaceEncoder, PreprocessCo1nfigfrom uniface.constants import SphereFaceWeights, MobileFaceWeights, ArcFaceWeights