realutils.face.insightface

This module provides a comprehensive interface to InsightFace, a 2D/3D face analysis toolkit. It includes functionalities for face detection, recognition, gender & age estimation, and visualization.

The models are hosted on Hugging Face Hub at deepghs/insightface, original project at deepinsight/insightface.

Face

class realutils.face.insightface.Face(bbox: Tuple[float, float, float, float], det_score: float, keypoints: List[Tuple[float, float]], gender: Literal['F', 'M'] | None = None, age: int | None = None, embedding: ndarray | None = None)[source]

A dataclass representing detected face information.

This class stores information about a detected face, including its location, detection confidence, facial landmarks, and optional demographic attributes.

Parameters:
  • bbox (Tuple[float, float, float, float]) – Bounding box coordinates in format (x1, y1, x2, y2)

  • det_score (float) – Detection confidence score between 0 and 1

  • keypoints (List[Tuple[float, float]]) – List of facial keypoint coordinates as (x, y) tuples

  • gender (Optional[Literal['F', 'M']]) – Gender classification result, either ‘F’ for female or ‘M’ for male

  • age (Optional[int]) – Estimated age in years

  • embedding (Optional[np.ndarray]) – Feature embedding of this human face

Example:
>>> face = Face(
...     bbox=(100, 200, 300, 400),
...     det_score=0.99,
...     keypoints=[(150, 250), (200, 250)],
...     gender='F',
...     age=25
... )
to_det_tuple() Tuple[Tuple[float, float, float, float], str, float][source]

Convert face detection result to a standardized detection tuple format.

This method formats the face detection information into a tuple that can be used with general object detection frameworks or visualization tools.

Returns:

A tuple containing (bbox, label, confidence_score)

Return type:

Tuple[Tuple[float, float, float, float], str, float]

Example:
>>> face = Face(bbox=(100, 200, 300, 400), det_score=0.99, keypoints=[])
>>> bbox, label, score = face.to_det_tuple()

isf_detect_faces

realutils.face.insightface.isf_detect_faces(image: str | PathLike | bytes | bytearray | BinaryIO | Image, model_name: str = 'buffalo_l', input_size: Tuple[int, int] = (640, 640), det_thresh: float = 0.5, nms_thresh: float = 0.4) List[Face][source]

Detect faces in the given image using RetinaFace model.

Parameters:
  • image (Union[str, PIL.Image.Image, numpy.ndarray]) – Input image (can be path, PIL Image, or numpy array)

  • model_name (str) – Name of the detection model to use

  • input_size (tuple) – Model input size (width, height)

  • det_thresh (float) – Detection confidence threshold

  • nms_thresh (float) – Non-maximum suppression threshold

Returns:

List of detected faces with bounding boxes and keypoints

Return type:

List[Face]

Example:
>>> from realutils.face.insightface import isf_detect_faces
>>> from PIL import Image
>>>
>>> img = Image.open('path/to/image.jpg')
>>> faces = isf_detect_faces(img)
>>> for face in faces:
...     print(f"Face {face.bbox!r} detected with confidence: {face.det_score}")

isf_genderage

realutils.face.insightface.isf_genderage(image: str | PathLike | bytes | bytearray | BinaryIO | Image, face: Face | Tuple[float, float, float, float], model_name: str = 'buffalo_l', no_write: bool = False)[source]

Detect gender and age from a facial image.

This function performs gender and age detection on a given face in an image. It can work with either a Face object or raw bounding box coordinates.

Parameters:
  • image (ImageTyping) – Input image (can be path, URL, PIL Image, or numpy array)

  • face (Union[Face, Tuple[float, float, float, float]]) – Face object or bounding box coordinates (x1, y1, x2, y2)

  • model_name (str) – Name of the model to use for detection, defaults to _DEFAULT_MODEL

  • no_write (bool) – If True, don’t update the Face object with results (if face is Face object)

Returns:

Tuple of (gender, age) where gender is ‘F’ or ‘M’ and age is an integer

Return type:

tuple[str, int]

isf_extract_face

realutils.face.insightface.isf_extract_face(image: str | PathLike | bytes | bytearray | BinaryIO | Image, face: Face, model_name: str = 'buffalo_l', no_write: bool = False)[source]

Extract face embedding features from an image.

Parameters:
  • image (ImageTyping) – Input image

  • face (Face) – Face object containing keypoints

  • model_name (str) – Name of the model to use

  • no_write (bool) – If True, don’t write embedding to face object

Returns:

Face embedding vector

Return type:

np.ndarray

isf_face_batch_similarity

realutils.face.insightface.isf_face_batch_similarity(embs: List[ndarray] | ndarray)[source]

Calculate similarity matrix for a batch of face embeddings.

Parameters:

embs (Union[List[np.ndarray], np.ndarray]) – List or array of face embeddings

Returns:

Similarity matrix

Return type:

np.ndarray

isf_face_similarity

realutils.face.insightface.isf_face_similarity(emb1: ndarray, emb2: ndarray)[source]

Calculate similarity between two face embeddings.

Parameters:
  • emb1 (np.ndarray) – First face embedding

  • emb2 (np.ndarray) – Second face embedding

Returns:

Similarity score

Return type:

float

isf_face_batch_same

realutils.face.insightface.isf_face_batch_same(embs: List[ndarray] | ndarray, model_name: str = 'buffalo_l', threshold: float | None = None)[source]

Determine if faces in a batch are the same person using similarity threshold.

Parameters:
  • embs (Union[List[np.ndarray], np.ndarray]) – List or array of face embeddings

  • model_name (str) – Name of the model to use

  • threshold (Optional[float]) – Similarity threshold, if None uses default

Returns:

Boolean matrix indicating matching faces

Return type:

np.ndarray

isf_face_same

realutils.face.insightface.isf_face_same(emb1: ndarray, emb2: ndarray, model_name: str = 'buffalo_l', threshold: float | None = None) float[source]

Determine if two faces are the same person.

Parameters:
  • emb1 (np.ndarray) – First face embedding

  • emb2 (np.ndarray) – Second face embedding

  • model_name (str) – Name of the model to use

  • threshold (Optional[float]) – Similarity threshold, if None uses default

Returns:

Boolean indicating if faces match

Return type:

float

isf_analysis_faces

realutils.face.insightface.isf_analysis_faces(image: str | PathLike | bytes | bytearray | BinaryIO | Image, model_name: str = 'buffalo_l', input_size: Tuple[int, int] = (640, 640), det_thresh: float = 0.5, nms_thresh: float = 0.4, no_genderage: bool = False, no_extraction: bool = False, silent: bool = False) List[Face][source]

Perform comprehensive face analysis on an image, including detection, gender/age estimation, and feature extraction.

This function processes an image through multiple stages of face analysis: 1. Face detection to locate faces and their landmarks 2. Gender and age estimation (optional) 3. Face feature extraction (optional)

Parameters:
  • image (ImageTyping) – Input image for face analysis

  • model_name (str) – Name of the pre-trained model to use from Hugging Face Hub

  • input_size (Tuple[int, int]) – Size to resize input image to before processing (width, height)

  • det_thresh (float) – Detection confidence threshold for face detection

  • nms_thresh (float) – Non-maximum suppression threshold for face detection

  • no_genderage (bool) – If True, skip gender and age estimation

  • no_extraction (bool) – If True, skip face feature extraction

  • silent (bool) – If True, disable progress bar

Returns:

List of detected Face objects with analysis results

Return type:

List[Face]

isf_faces_visualize

realutils.face.insightface.isf_faces_visualize(image: str | PathLike | bytes | bytearray | BinaryIO | Image, faces: List[Face], text_padding: int = 6, fontsize: int = 12, keypoint_size: int = 12, box_color: str = '#ff00ee', max_short_edge_size: int | None = None, fp=None, no_label: bool = False)[source]

Visualize face detection results by drawing bounding boxes, keypoints and labels on an image.

This function takes an input image and a list of detected faces, then draws:

  • Bounding boxes around each detected face

  • Keypoints for facial features using randomly generated colors

  • Optional labels showing detection confidence scores

The visualization can be customized through various parameters like font size, box colors, and whether to show labels.

Parameters:
  • image (ImageTyping) – Input image to visualize detections on. Can be a PIL Image, numpy array, or path to image file.

  • faces (List[Face]) – List of detected Face objects containing bounding boxes, keypoints and scores.

  • text_padding (int) – Padding around label text in pixels.

  • fontsize (int) – Font size for label text.

  • keypoint_size (int) – Size of keypoint markers in pixels.

  • box_color (str) – Color of bounding box in hex format (e.g. ‘#ff00ee’).

  • max_short_edge_size (Optional[int]) – Maximum size of shortest image edge. If specified, image will be resized while maintaining aspect ratio.

  • fp (matplotlib.font_manager.FontProperties or None) – Font properties for matplotlib font. Only used if matplotlib is available.

  • no_label (bool) – If True, suppresses drawing of labels.

Returns:

PIL Image with visualized detection results.

Return type:

PIL.Image.Image

Example:
>>> from realutils.face.insightface import isf_faces_visualize, isf_detect_faces
>>> from PIL import Image
>>>
>>> image = Image.open('face.jpg')
>>> faces = isf_detect_faces(image)
>>> visualized = isf_faces_visualize(
...     image,
...     faces,
...     fontsize=14,
...     box_color='#00ff00'
... )
>>> visualized.show()