### Install face-alignment using pip Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Install the face-alignment library using pip. Ensure Python 3.9+ and PyTorch (>=2.0) are installed. ```bash pip install face-alignment ``` -------------------------------- ### Install Face Alignment Dependencies and Package Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Install the required dependencies and the Face Alignment library from source. This follows cloning the repository. ```bash pip install -r requirements.txt pip install . ``` -------------------------------- ### Clone Face Alignment Source Code Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Clone the Face Alignment repository from GitHub to build from source. Requires Git to be installed. ```bash git clone https://github.com/1adrianb/face-alignment ``` -------------------------------- ### Specify Face Detector (SFD) Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Detect facial landmarks using the SFD face detector, which is the default and most accurate option. No additional setup is required for SFD. ```python import face_alignment fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, face_detector='sfd') ``` -------------------------------- ### Get Landmarks from Batch Source: https://context7.com/1adrianb/face-alignment/llms.txt Process multiple images efficiently in a batch using `get_landmarks_from_batch`. This method accepts a torch tensor of shape (N, C, H, W) and is suitable for video or image collection processing. ```python import face_alignment import torch import numpy as np import cv2 fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) ``` -------------------------------- ### Detect 2D Facial Landmarks Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Use this snippet to detect 2D facial landmarks from an image. Ensure the 'face_alignment' and 'scikit-image' libraries are installed. ```python import face_alignment from skimage import io fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, flip_input=False) input = io.imread('../test/assets/aflw-test.jpg') preds = fa.get_landmarks(input) ``` -------------------------------- ### Get Landmarks from Image Source: https://context7.com/1adrianb/face-alignment/llms.txt Extract facial landmarks from a single image using `get_landmarks_from_image`. Supports file paths, numpy arrays, or torch tensors. Can optionally return bounding boxes and confidence scores. Pre-computed bounding boxes can be provided to skip face detection. ```python import face_alignment from skimage import io import numpy as np fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda', flip_input=False ) # From file path landmarks = fa.get_landmarks_from_image('path/to/image.jpg') # From numpy array image = io.imread('path/to/image.jpg') landmarks = fa.get_landmarks_from_image(image) # With bounding boxes and confidence scores landmarks, scores, bboxes = fa.get_landmarks_from_image( image, return_bboxes=True, return_landmark_score=True ) # Process results if landmarks is not None: for i, face_landmarks in enumerate(landmarks): print(f"Face {i}: {face_landmarks.shape}") # (68, 2) for 2D print(f"Confidence scores: {scores[i].shape}") # (68,) print(f"Bounding box: {bboxes[i]}") # [x1, y1, x2, y2, score] # With pre-computed bounding boxes (skip face detection) detected_faces = [ np.array([100, 100, 300, 300, 0.99]), # [x1, y1, x2, y2, confidence] ] landmarks = fa.get_landmarks_from_image(image, detected_faces=detected_faces) ``` -------------------------------- ### Configure Face Detector Backend Source: https://context7.com/1adrianb/face-alignment/llms.txt Initializes the FaceAlignment class with different face detector backends, allowing for trade-offs between speed and accuracy. Includes options for SFD, BlazeFace, RetinaFace, YuNet, SCRFD, and custom thresholding. ```python import face_alignment # SFD (default) - most accurate, slower fa_sfd = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='sfd' ) # BlazeFace - very fast, good for real-time fa_blazeface = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='blazeface' ) # BlazeFace with back camera model (better for distant faces) fa_blazeface_back = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='blazeface', face_detector_kwargs={'back_model': True} ) # RetinaFace - good balance of speed and accuracy fa_retina = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='retinaface' ) # YuNet - fastest (CPU only, uses OpenCV DNN) fa_yunet = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cpu', face_detector='yunet' ) # SCRFD - requires: pip install onnxruntime fa_scrfd = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='scrfd' ) # Custom detector threshold fa_custom = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='sfd', face_detector_kwargs={'filter_threshold': 0.8} ) # Pre-computed bounding boxes from files fa_folder = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, face_detector='folder' ) ``` -------------------------------- ### Build Docker Image for Face Alignment Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Build a Docker image for the face-alignment project, including CUDA support. Assumes a Dockerfile is present in the current directory. ```bash docker build -t face-alignment . ``` -------------------------------- ### Initialize FaceAlignment Class Source: https://context7.com/1adrianb/face-alignment/llms.txt Instantiate the FaceAlignment class with options for landmark type, device, precision, and face detector. Supports CPU, CUDA, and MPS acceleration. `torch.compile` is enabled by default for optimized inference. ```python import face_alignment import torch # Basic 2D landmark detection on GPU fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) # 3D landmark detection with custom settings fa_3d = face_alignment.FaceAlignment( face_alignment.LandmarksType.THREE_D, device='cuda', dtype=torch.bfloat16, # Use bfloat16 for faster inference flip_input=True, # Enable test-time augmentation face_detector='blazeface', # Use BlazeFace for faster detection compile=True, # Enable torch.compile (default) max_batch_size=8 # Process up to 8 faces in parallel ) # CPU-only with instant startup (skip compilation) fa_cpu = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cpu', compile=False ) # Apple Silicon (MPS) support fa_mps = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='mps' ) ``` -------------------------------- ### Initialize Face Alignment with Max Batch Size Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Initialize the FaceAlignment class with specific landmark type, device, and a maximum batch size. Useful for managing memory on low-memory GPUs. ```python fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device='cuda', max_batch_size=8) ``` -------------------------------- ### FaceAlignment Class Initialization Source: https://context7.com/1adrianb/face-alignment/llms.txt Initialize the FaceAlignment class with different configurations for landmark type, device, and other settings. ```APIDOC ## FaceAlignment Class Initialization The main entry point for the library. Creates a face alignment instance with configurable landmark type (2D, 2.5D, or 3D), face detector backend, device placement, and precision settings. ### Basic 2D landmark detection on GPU ```python import face_alignment import torch fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) ``` ### 3D landmark detection with custom settings ```python import face_alignment import torch fa_3d = face_alignment.FaceAlignment( face_alignment.LandmarksType.THREE_D, device='cuda', dtype=torch.bfloat16, # Use bfloat16 for faster inference flip_input=True, # Enable test-time augmentation face_detector='blazeface', # Use BlazeFace for faster detection compile=True, # Enable torch.compile (default) max_batch_size=8 # Process up to 8 faces in parallel ) ``` ### CPU-only with instant startup (skip compilation) ```python import face_alignment fa_cpu = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cpu', compile=False ) ``` ### Apple Silicon (MPS) support ```python import face_alignment fa_mps = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='mps' ) ``` ``` -------------------------------- ### Specify Device and Compilation Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Control the execution device (CUDA, MPS, or CPU) and disable model compilation for faster startup if needed. The landmark network is compiled with torch.compile by default for performance. ```python import torch import face_alignment # cuda for CUDA, mps for Apple M GPUs. fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, dtype=torch.bfloat16, device='cuda') ``` ```python # Skip compilation for instant startup fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device='cpu', compile=False) ``` -------------------------------- ### Use Alternative Face Detectors Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Configure the face-alignment library to use alternative face detectors like BlazeFace, YuNet, RetinaFace, or SCRFD for different speed/accuracy trade-offs. SCRFD requires the 'onnxruntime' package. ```python # BlazeFace back camera model (larger input, better for distant faces) fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, face_detector='blazeface', face_detector_kwargs={'back_model': True}) ``` ```python # SCRFD (requires: pip install onnxruntime) fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, face_detector='scrfd') ``` ```python # Use pre-computed bounding boxes from files alongside images fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, face_detector='folder') ``` -------------------------------- ### Real-time 2D Landmark Detection with OpenCV Source: https://context7.com/1adrianb/face-alignment/llms.txt Processes video frames from a webcam or file in real-time to detect and draw 2D facial landmarks. Uses BlazeFace detector for performance and OpenCV for video I/O and drawing. Press 'q' to quit. ```python import face_alignment import cv2 import numpy as np # Use BlazeFace for real-time performance fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda', face_detector='blazeface', flip_input=False, compile=True ) cap = cv2.VideoCapture(0) # Webcam, or use 'video.mp4' for file while True: ret, frame = cap.read() if not ret: break # Convert BGR to RGB rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Detect landmarks landmarks = fa.get_landmarks_from_image(rgb_frame) # Draw landmarks if landmarks is not None: for face_landmarks in landmarks: for (x, y) in face_landmarks.astype(int): cv2.circle(frame, (x, y), 2, (0, 255, 0), -1) cv2.imshow('Face Alignment', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` -------------------------------- ### Initialize BlazeFace Detector Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Initializes the FaceAlignment class using the BlazeFace face detector and the TWO_D landmarks type on the CPU. ```python fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device='cpu', face_detector='blazeface') ``` -------------------------------- ### Initialize S3FD Face Detector Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Initializes the FaceAlignment class using the S3FD face detector and the TWO_HALF_D landmarks type on the CPU. ```python fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_HALF_D, device='cpu', face_detector='sfd') ``` -------------------------------- ### Visualize Landmarks on Single Image (BlazeFace) Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Displays the first frame and plots the detected facial landmarks using Matplotlib. Assumes 'preds' contains landmark data. ```python plt.imshow(frames[0]) for detection in preds: plt.scatter(detection[:,0], detection[:,1], 2) ``` -------------------------------- ### Detect Landmarks on Batch with BlazeFace Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Prepares a batch of frames (up to 2) for processing, converts it to a PyTorch tensor, detects facial landmarks using the BlazeFace detector, and measures the execution time. ```python batch = np.stack(frames) batch = batch.transpose(0, 3, 1, 2) batch = torch.Tensor(batch[:2]) t_start = time.time() preds = fa.get_landmarks_from_batch(batch) print(f'BlazeFace: Execution time for a batch of 2 images: {time.time() - t_start}') ``` -------------------------------- ### Detect Landmarks on Batch with S3FD Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Prepares a batch of frames (up to 2) for processing, converts it to a PyTorch tensor, detects facial landmarks using the S3FD detector, and measures the execution time. ```python batch = np.stack(frames) batch = batch.transpose(0, 3, 1, 2) batch = torch.Tensor(batch[:2]) t_start = time.time() preds = fa.get_landmarks_from_batch(batch) print(f'SFD: Execution time for a batch of 2 images: {time.time() - t_start}') ``` -------------------------------- ### Visualize Landmarks on Batch (BlazeFace) Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Displays frames from the batch and plots the detected facial landmarks for each frame using Matplotlib. Assumes 'preds' contains landmark data for the batch. The subplot layout is adjusted for potentially more frames. ```python fig = plt.figure(figsize=(10, 25)) for i, pred in enumerate(preds): plt.subplot(5, 2, i + 1) plt.imshow(frames[i]) plt.title(f'frame[{i}]') for detection in pred: plt.scatter(detection[:,0], detection[:,1], 2) ``` -------------------------------- ### Process Images from Directory for Face Landmarks Source: https://context7.com/1adrianb/face-alignment/llms.txt Scans a directory for images, processes them to detect facial landmarks, and returns a dictionary mapping file paths to results. Supports recursive scanning and progress bar display. Can also return bounding boxes and scores. ```python import face_alignment fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) # Basic directory processing predictions = fa.get_landmarks_from_directory( 'path/to/images/', extensions=['.jpg', '.png', '.jpeg'], recursive=True, show_progress_bar=True ) # Access results by file path for image_path, landmarks in predictions.items(): if landmarks is not None: print(f"{image_path}: {len(landmarks)} faces") for face_idx, face_landmarks in enumerate(landmarks): print(f" Face {face_idx}: {face_landmarks.shape}") # With bounding boxes and scores predictions = fa.get_landmarks_from_directory( 'path/to/images/', return_bboxes=True, return_landmark_score=True ) for image_path, (landmarks, bboxes, scores) in predictions.items(): if landmarks is not None: for i in range(len(landmarks)): print(f"{image_path} - Face {i}: bbox={bboxes[i][:4]}") ``` -------------------------------- ### Visualize Landmarks on Batch (S3FD) Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Displays the first two frames from the batch and plots the detected facial landmarks for each frame using Matplotlib. Assumes 'preds' contains landmark data for the batch. ```python fig = plt.figure(figsize=(10, 5)) for i, pred in enumerate(preds): plt.subplot(1, 2, i + 1) plt.imshow(frames[1]) plt.title(f'frame[{i}]') for detection in pred: plt.scatter(detection[:,0], detection[:,1], 2) ``` -------------------------------- ### get_landmarks_from_batch Source: https://context7.com/1adrianb/face-alignment/llms.txt Processes multiple images in a batch for efficient inference on videos or image collections. ```APIDOC ## get_landmarks_from_batch Processes multiple images in a batch for efficient inference on videos or image collections. Accepts a torch tensor of shape (N, C, H, W) and returns landmarks for all detected faces in each image. ```python import face_alignment import torch import numpy as np import cv2 fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) # Example usage with a batch of images (assuming images are loaded and preprocessed) # batch_images = torch.randn(4, 3, 256, 256) # Example batch of 4 images # landmarks_batch = fa.get_landmarks_from_batch(batch_images) ``` ``` -------------------------------- ### Import Libraries for Face Alignment Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Imports necessary libraries for face alignment, including face_alignment, OpenCV, NumPy, PyTorch, and Matplotlib. ```python import face_alignment import cv2 import numpy as np import torch import matplotlib.pyplot as plt ``` -------------------------------- ### Visualize Landmarks on Single Image (S3FD) Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Displays the first frame and plots the detected facial landmarks using Matplotlib. Assumes 'det' contains landmark data. ```python plt.imshow(frames[0]) for detection in det: plt.scatter(detection[:,0], detection[:,1], 2) ``` -------------------------------- ### Process Directory for Landmarks Source: https://github.com/1adrianb/face-alignment/blob/master/README.md Efficiently detect facial landmarks for all images within a specified directory. This method processes an entire directory in one go. ```python import face_alignment from skimage import io fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, flip_input=False) preds = fa.get_landmarks_from_directory('../test/assets/') ``` -------------------------------- ### Load Video Frames Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Reads frames from a video file ('acazlolrpz.mp4') and stores them as RGB NumPy arrays. Handles cases where the video cannot be read. ```python cap = cv2.VideoCapture('acazlolrpz.mp4') frames = [] while True: success, frame = cap.read() if not success: break frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frames.append(frame) ``` -------------------------------- ### Process Video Frames for Face Landmarks Source: https://context7.com/1adrianb/face-alignment/llms.txt Loads frames from a video file, converts them to RGB, stacks them into a batch tensor, and then extracts facial landmarks. Optionally returns bounding boxes and landmark scores. ```python import cv2 import numpy as np import torch import face_alignment cap = cv2.VideoCapture('video.mp4') frames = [] while len(frames) < 10: success, frame = cap.read() if not success: break frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frames.append(frame) cap.release() # Create batch tensor (N, C, H, W) batch = np.stack(frames) batch = batch.transpose(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) batch_tensor = torch.Tensor(batch) # Process batch fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D) landmarks = fa.get_landmarks_from_batch(batch_tensor) # With scores and bounding boxes landmarks, scores, bboxes = fa.get_landmarks_from_batch( batch_tensor, return_bboxes=True, return_landmark_score=True ) # Process results per frame for frame_idx, frame_landmarks in enumerate(landmarks): if frame_landmarks is not None and len(frame_landmarks) > 0: print(f"Frame {frame_idx}: {frame_landmarks.shape[0]} faces detected") ``` -------------------------------- ### Visualize 3D Landmarks with Matplotlib Source: https://context7.com/1adrianb/face-alignment/llms.txt Plots detected 3D facial landmarks on an image using Matplotlib. Requires `face_alignment`, `matplotlib`, and `scikit-image`. Landmarks are categorized into standard facial regions for visualization. ```python import face_alignment import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from skimage import io import collections fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.THREE_D, device='cuda', flip_input=True ) image = io.imread('path/to/image.jpg') landmarks = fa.get_landmarks_from_image(image) if landmarks is not None: preds = landmarks[0] # First face # Define facial regions with colors pred_type = collections.namedtuple('prediction_type', ['slice', 'color']) pred_types = { 'face': pred_type(slice(0, 17), (0.682, 0.780, 0.909, 0.5)), 'eyebrow1': pred_type(slice(17, 22), (1.0, 0.498, 0.055, 0.4)), 'eyebrow2': pred_type(slice(22, 27), (1.0, 0.498, 0.055, 0.4)), 'nose': pred_type(slice(27, 31), (0.345, 0.239, 0.443, 0.4)), 'nostril': pred_type(slice(31, 36), (0.345, 0.239, 0.443, 0.4)), 'eye1': pred_type(slice(36, 42), (0.596, 0.875, 0.541, 0.3)), 'eye2': pred_type(slice(42, 48), (0.596, 0.875, 0.541, 0.3)), 'lips': pred_type(slice(48, 60), (0.596, 0.875, 0.541, 0.3)), 'teeth': pred_type(slice(60, 68), (0.596, 0.875, 0.541, 0.4)) } plot_style = dict(marker='o', markersize=4, linestyle='-', lw=2) fig = plt.figure(figsize=plt.figaspect(0.5)) # 2D plot ax = fig.add_subplot(1, 2, 1) ax.imshow(image) for pt in pred_types.values(): ax.plot(preds[pt.slice, 0], preds[pt.slice, 1], color=pt.color, **plot_style) ax.axis('off') # 3D plot ax = fig.add_subplot(1, 2, 2, projection='3d') ax.scatter(preds[:, 0] * 1.2, preds[:, 1], preds[:, 2], c='cyan', alpha=1.0, edgecolor='b') for pt in pred_types.values(): ax.plot3D(preds[pt.slice, 0] * 1.2, preds[pt.slice, 1], preds[pt.slice, 2], color='blue') ax.view_init(elev=90., azim=90.) ax.set_xlim(ax.get_xlim()[::-1]) plt.show() ``` -------------------------------- ### Detect 3D Facial Landmarks Source: https://github.com/1adrianb/face-alignment/blob/master/README.md This code detects 3D facial landmarks from an image. It requires the 'face_alignment' and 'scikit-image' libraries. ```python import face_alignment from skimage import io fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.THREE_D, flip_input=False) input = io.imread('../test/assets/aflw-test.jpg') preds = fa.get_landmarks(input) ``` -------------------------------- ### get_landmarks_from_image Source: https://context7.com/1adrianb/face-alignment/llms.txt Detects facial landmarks from a single image. Supports file paths, numpy arrays, or torch tensors. ```APIDOC ## get_landmarks_from_image Detects facial landmarks from a single image. Accepts file paths, numpy arrays, or torch tensors. Returns a list of 68-point landmark arrays, one per detected face, with optional bounding boxes and confidence scores. ### From file path ```python import face_alignment from skimage import io fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda', flip_input=False ) landmarks = fa.get_landmarks_from_image('path/to/image.jpg') ``` ### From numpy array ```python import face_alignment from skimage import io import numpy as np fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda', flip_input=False ) image = io.imread('path/to/image.jpg') landmarks = fa.get_landmarks_from_image(image) ``` ### With bounding boxes and confidence scores ```python import face_alignment from skimage import io import numpy as np fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda', flip_input=False ) image = io.imread('path/to/image.jpg') landmarks, scores, bboxes = fa.get_landmarks_from_image( image, return_bboxes=True, return_landmark_score=True ) # Process results if landmarks is not None: for i, face_landmarks in enumerate(landmarks): print(f"Face {i}: {face_landmarks.shape}") # (68, 2) for 2D print(f"Confidence scores: {scores[i].shape}") # (68,) print(f"Bounding box: {bboxes[i]}") # [x1, y1, x2, y2, score] ``` ### With pre-computed bounding boxes (skip face detection) ```python import face_alignment import numpy as np fa = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda', flip_input=False ) image = io.imread('path/to/image.jpg') detected_faces = [ np.array([100, 100, 300, 300, 0.99]), # [x1, y1, x2, y2, confidence] ] landmarks = fa.get_landmarks_from_image(image, detected_faces=detected_faces) ``` ``` -------------------------------- ### Detect Landmarks on Single Image with BlazeFace Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Detects facial landmarks from the first frame using the BlazeFace detector and measures the execution time. This snippet may raise an IndexError if the 'frames' list is empty. ```python t_start = time.time() preds = fa.get_landmarks_from_image(frames[0]) print(f'BlazeFace: Execution time for a single image: {time.time() - t_start}') ``` -------------------------------- ### Detect Landmarks on Single Image with S3FD Source: https://github.com/1adrianb/face-alignment/blob/master/examples/demo.ipynb Detects facial landmarks from the first frame using the S3FD detector and measures the execution time. This snippet may raise an IndexError if the 'frames' list is empty. ```python import time t_start = time.time() det = fa.get_landmarks_from_image(frames[0]) print(f'SFD: Execution time for a single image: {time.time() - t_start}') ``` -------------------------------- ### LandmarksType Enumeration Source: https://context7.com/1adrianb/face-alignment/llms.txt Use the LandmarksType enumeration to specify the desired facial landmark output. TWO_D provides (x, y) coordinates, TWO_HALF_D projects 3D points to 2D, and THREE_D returns full (x, y, z) coordinates. ```python import face_alignment # 2D landmarks - (x, y) coordinates following visible face contour fa_2d = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) # 2.5D landmarks - 3D points projected to 2D fa_2half = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_HALF_D, device='cuda' ) # 3D landmarks - full (x, y, z) coordinates fa_3d = face_alignment.FaceAlignment( face_alignment.LandmarksType.THREE_D, device='cuda' ) # Output shape: (68, 3) for 3D landmarks per face ``` -------------------------------- ### LandmarksType Enumeration Source: https://context7.com/1adrianb/face-alignment/llms.txt Defines the type of facial landmarks to detect: TWO_D, TWO_HALF_D, or THREE_D. ```APIDOC ## LandmarksType Enumeration Defines the type of facial landmarks to detect. TWO_D returns (x, y) coordinates following the visible face contour, TWO_HALF_D projects 3D points into 2D, and THREE_D returns full (x, y, z) coordinates in 3D space. ### 2D landmarks ```python import face_alignment fa_2d = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_D, device='cuda' ) ``` ### 2.5D landmarks ```python import face_alignment fa_2half = face_alignment.FaceAlignment( face_alignment.LandmarksType.TWO_HALF_D, device='cuda' ) ``` ### 3D landmarks ```python import face_alignment fa_3d = face_alignment.FaceAlignment( face_alignment.LandmarksType.THREE_D, device='cuda' ) # Output shape: (68, 3) for 3D landmarks per face ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.