This workflow demonstrates how to iterate through all detected faces in an image, crop them using their bounding boxes, adjust landmarks to be relative to the crop, and finally align/crop them into a standardized format.
- Detect faces and landmarks.
- Convert the PIL image to a NumPy array (OpenCV format: BGR).
- For each detection:
- Adjust bounding box coordinates to ensure they stay within image boundaries.
- Crop the face from the image.
- Calculate facial landmarks relative to the top-left corner of the crop.
- Apply
warp_and_crop_face to get the aligned face. - Convert the resulting NumPy array back to a PIL Image.
from src import detect_faces
from src.align_trans import warp_and_crop_face
from PIL import Image
import numpy as np
from tqdm import tqdm_notebook as tqdm
img = Image.open('images/jf.jpg')
bounding_boxes, landmarks = detect_faces(img)
faces = []
img_cv2 = np.array(img)[...,::-1]
for i in tqdm(range(len(bounding_boxes))):
box = bounding_boxes[i][:4].astype(np.int32).tolist()
# Boundary safety checks
for idx, coord in enumerate(box[:2]):
if coord > 1:
box[idx] -= 1
if box[2] + 1 < img_cv2.shape[1]:
box[2] += 1
if box[3] + 1 < img_cv2.shape[0]:
box[3] += 1
face = img_cv2[box[1]:box[3],box[0]:box[2]]
landmark = landmarks[i]
# Make landmarks relative to the crop
facial5points = [[landmark[j] - box[0], landmark[j+5] - box[1]] for j in range(5)]
dst_img = warp_and_crop_face(face, facial5points)
faces.append(Image.fromarray(dst_img[...,::-1]))