__init__.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # Copyright 2025 Yakhyokhuja Valikhujaev
  2. # Author: Yakhyokhuja Valikhujaev
  3. # GitHub: https://github.com/yakhyo
  4. from typing import Any, Dict, List
  5. import numpy as np
  6. from .base import BaseDetector
  7. from .retinaface import RetinaFace
  8. from .scrfd import SCRFD
  9. # Global cache for detector instances
  10. _detector_cache: Dict[str, BaseDetector] = {}
  11. def detect_faces(image: np.ndarray, method: str = 'retinaface', **kwargs) -> List[Dict[str, Any]]:
  12. """
  13. High-level face detection function.
  14. Args:
  15. image (np.ndarray): Input image as numpy array.
  16. method (str): Detection method to use. Options: 'retinaface', 'scrfd'.
  17. **kwargs: Additional arguments passed to the detector.
  18. Returns:
  19. List[Dict[str, Any]]: A list of dictionaries, where each dictionary represents a detected face and contains:
  20. - 'bbox' (List[float]): [x1, y1, x2, y2] bounding box coordinates.
  21. - 'confidence' (float): The confidence score of the detection.
  22. - 'landmarks' (List[List[float]]): 5-point facial landmarks.
  23. Example:
  24. >>> from uniface import detect_faces
  25. >>> image = cv2.imread("your_image.jpg")
  26. >>> faces = detect_faces(image, method='retinaface', conf_thresh=0.8)
  27. >>> for face in faces:
  28. ... print(f"Found face with confidence: {face['confidence']}")
  29. ... print(f"BBox: {face['bbox']}")
  30. """
  31. method_name = method.lower()
  32. sorted_kwargs = sorted(kwargs.items())
  33. cache_key = f'{method_name}_{str(sorted_kwargs)}'
  34. if cache_key not in _detector_cache:
  35. # Pass kwargs to create the correctly configured detector
  36. _detector_cache[cache_key] = create_detector(method, **kwargs)
  37. detector = _detector_cache[cache_key]
  38. return detector.detect(image)
  39. def create_detector(method: str = 'retinaface', **kwargs) -> BaseDetector:
  40. """
  41. Factory function to create face detectors.
  42. Args:
  43. method (str): Detection method. Options:
  44. - 'retinaface': RetinaFace detector (default)
  45. - 'scrfd': SCRFD detector (fast and accurate)
  46. **kwargs: Detector-specific parameters
  47. Returns:
  48. BaseDetector: Initialized detector instance
  49. Raises:
  50. ValueError: If method is not supported
  51. Examples:
  52. >>> # Basic usage
  53. >>> detector = create_detector('retinaface')
  54. >>> # SCRFD detector with custom parameters
  55. >>> detector = create_detector(
  56. ... 'scrfd',
  57. ... model_name=SCRFDWeights.SCRFD_10G_KPS,
  58. ... conf_thresh=0.8,
  59. ... input_size=(640, 640)
  60. ... )
  61. >>> # RetinaFace detector
  62. >>> detector = create_detector(
  63. ... 'retinaface',
  64. ... model_name=RetinaFaceWeights.MNET_V2,
  65. ... conf_thresh=0.8,
  66. ... nms_thresh=0.4
  67. ... )
  68. """
  69. method = method.lower()
  70. if method == 'retinaface':
  71. return RetinaFace(**kwargs)
  72. elif method == 'scrfd':
  73. return SCRFD(**kwargs)
  74. else:
  75. available_methods = ['retinaface', 'scrfd']
  76. raise ValueError(f"Unsupported detection method: '{method}'. Available methods: {available_methods}")
  77. def list_available_detectors() -> Dict[str, Dict[str, Any]]:
  78. """
  79. List all available detection methods with their descriptions and parameters.
  80. Returns:
  81. Dict[str, Dict[str, Any]]: Dictionary of detector information
  82. """
  83. return {
  84. 'retinaface': {
  85. 'description': 'RetinaFace detector with high accuracy',
  86. 'supports_landmarks': True,
  87. 'paper': 'https://arxiv.org/abs/1905.00641',
  88. 'default_params': {
  89. 'model_name': 'mnet_v2',
  90. 'conf_thresh': 0.5,
  91. 'nms_thresh': 0.4,
  92. 'input_size': (640, 640),
  93. },
  94. },
  95. 'scrfd': {
  96. 'description': 'SCRFD detector - fast and accurate with efficient architecture',
  97. 'supports_landmarks': True,
  98. 'paper': 'https://arxiv.org/abs/2105.04714',
  99. 'default_params': {
  100. 'model_name': 'scrfd_10g_kps',
  101. 'conf_thresh': 0.5,
  102. 'nms_thresh': 0.4,
  103. 'input_size': (640, 640),
  104. },
  105. },
  106. }
  107. __all__ = [
  108. 'detect_faces',
  109. 'create_detector',
  110. 'list_available_detectors',
  111. 'SCRFD',
  112. 'RetinaFace',
  113. 'BaseDetector',
  114. ]