123DevOps··13 min read

Face recognition with OpenCV: YuNet, SFace, and what privacy law requires before the first face

Detect faces with cv2.FaceDetectorYN, compare and identify people with cv2.FaceRecognizerSF, build an embedding gallery with a threshold and an 'unknown' answer, and understand privacy law, bias, the EU AI Act, and production safeguards.

Data

With two small networks and about 60 lines of Python, OpenCV finds faces in an image and tells you whether two faces belong to the same person. Getting that to work is easy. Doing it lawfully, fairly, and securely is the hard part, which is why it comes before the code in this guide. Every number below is real output, tested on November 25, 2026 with Python 3.15, OpenCV 5.1.0 (opencv-python 5.1.0.95), and numpy 2.5.5.

Detection, recognition, verification, and identification

These terms get used interchangeably, but they are different tasks with different risks:

Task Question Output Example
Detection Where are the faces in this image? Boxes, landmarks, and score Blurring faces in a video
Recognition Who is this face? (umbrella term) Embedding compared with others Verification or identification
Verification (1:1) Is this person who they claim to be? Yes/no against one enrollment Selfie against the ID document photo
Identification (1:N) Who, among N enrolled people, is this? An ID or “unknown” Gallery-based access control

Detection alone identifies no one. Once you extract embeddings, you are processing biometric data. And 1:N identification makes more mistakes than 1:1, because every query gets N chances to find a “lookalike”.

Before the code: privacy law, bias, and the EU AI Act

This is not legal advice. Bring in your company’s data protection officer (DPO) and legal team before putting anything into production.

Privacy laws such as Brazil’s LGPD or the GDPR: biometrics are sensitive data

Privacy laws such as Brazil’s LGPD or the GDPR treat biometric data used to identify a person as a special, sensitive category. Using the LGPD as the worked example:

  • Art. 5, II: biometric data linked to a natural person is sensitive personal data. A face embedding tied to an enrollment falls into that category.
  • Art. 11: sensitive data may only be processed with specific, highlighted consent for specific purposes, or without consent in the cases listed in item II. One of them, letter “g”, covers fraud prevention and the data subject’s security in identification and authentication processes in electronic systems. It is the most cited basis for biometric login and anti-fraud, but it is not a blank check: data subject rights still apply.
  • DPIA: the data protection impact assessment (called RIPD in the LGPD, art. 5, XVII) documents risks and safeguards. Under art. 38, the Brazilian authority (ANPD) may require one, including for sensitive data. For biometrics, do the DPIA before the pilot, not after.
  • Children (art. 14): processing must serve the child’s best interest and requires specific, highlighted consent from at least one parent or legal guardian. Face recognition on children needs a very strong justification.

The ANPD published a Technology Radar issue on biometrics and facial recognition (2024) that flags error and discrimination risks, and it opened a public consultation on biometric data in 2025. As of this writing, we could not find a final ANPD regulation on biometrics; check the authority’s website before deciding.

Bias and false matches

Models make mistakes unevenly. NIST’s tests on demographic effects (NISTIR 8280, from 2019) found false positive rates that vary across demographic groups, with large differences in many algorithms. In 1:N identification, a false positive points at the wrong person. So:

  • test the model on your population, with samples by age range, skin tone, and gender;
  • never let a match be the only evidence for a decision that affects someone.

EU AI Act

If the system serves people in the European Union, Regulation (EU) 2024/1689 applies. Since February 2, 2025, Article 5 prohibits, among other practices:

  • creating or expanding facial recognition databases through untargeted scraping of images from the internet or CCTV;
  • real-time remote biometric identification in publicly accessible spaces for law enforcement, except for narrow exceptions;
  • emotion recognition at work and in education, except for medical or safety reasons.

Outside those bans, remote biometric identification is high-risk (Annex III). Regulation (EU) 2026/1744 (the Digital Omnibus) postponed those high-risk obligations to December 2, 2027.

Setting up the environment

python3 -m venv .venv
source .venv/bin/activate
pip install opencv-python   # tested with 5.1.0.95; pulls in numpy

mkdir -p models imgs
curl -L -o models/face_detection_yunet_2023mar.onnx \
  https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx
curl -L -o models/face_recognition_sface_2021dec.onnx \
  https://github.com/opencv/opencv_zoo/raw/main/models/face_recognition_sface/face_recognition_sface_2021dec.onnx

The files are 232,589 and 38,696,353 bytes. Licenses in opencv_zoo: YuNet under MIT and SFace under Apache 2.0. The zoo already publishes a newer YuNet, face_detection_yunet_2026may.onnx, the default in the OpenCV 5.x sample, with a dynamic input shape. We tested 2023mar; check the opencv_zoo page before switching.

About the images: we used lena.jpg and messi5.jpg, from OpenCV’s samples/data folder, for local tests only. They are photos of real people with no clear license for republication, and OpenCV itself is phasing Lena out of its tutorials. That’s why this article shows only numbers, not the photos. In your project, use images of people who have consented.

Detecting faces with FaceDetectorYN

import sys

import cv2
import numpy as np

detector = cv2.FaceDetectorYN.create(
    "models/face_detection_yunet_2023mar.onnx",
    "",           # config: empty for ONNX
    (320, 320),   # initial size; we change it for every image
    0.8,          # score_threshold
    0.3,          # nms_threshold
    5000,         # top_k
)


def detect(img):
    h, w = img.shape[:2]
    detector.setInputSize((w, h))  # required for every image
    _, faces = detector.detect(img)
    return faces if faces is not None else np.empty((0, 15), dtype=np.float32)


def draw(img, faces):
    out = img.copy()
    for f in faces:
        x, y, w, h = f[:4].astype(int)
        cv2.rectangle(out, (x, y), (x + w, y + h), (0, 255, 0), 2)
        for i in range(5):  # right eye, left eye, nose, right mouth, left mouth
            px, py = f[4 + 2 * i : 6 + 2 * i].astype(int)
            cv2.circle(out, (px, py), 3, (0, 0, 255), -1)
        cv2.putText(out, f"{f[14]:.2f}", (x, y - 6),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
    return out


if __name__ == "__main__":
    for path in sys.argv[1:]:
        img = cv2.imread(path)
        faces = detect(img)
        print(f"{path}: {len(faces)} face(s), image {img.shape[1]}x{img.shape[0]}")
        for f in faces:
            print("  bbox:", f[:4].round(0).astype(int).tolist(),
                  " score:", round(float(f[14]), 3))
            print("  landmarks:", f[4:14].round(0).astype(int).reshape(5, 2).tolist())
        cv2.imwrite(path.replace(".jpg", "_faces.jpg"), draw(img, faces))

Real output of python detect.py imgs/lena.jpg imgs/messi5.jpg:

imgs/lena.jpg: 1 face(s), image 512x512
  bbox: [208, 183, 146, 207]  score: 0.909
  landmarks: [[272, 269], [328, 276], [310, 313], [271, 342], [311, 348]]
imgs/messi5.jpg: 1 face(s), image 548x342
  bbox: [226, 93, 31, 40]  score: 0.915
  landmarks: [[239, 106], [251, 107], [248, 114], [241, 121], [251, 122]]

Before that, OpenCV 5.x prints a WARN ... setPreferableTarget Targets are not supported by the new graph engine, which is harmless. Each face is a row of 15 numbers:

index  0-3   box x, y, width, height
index  4-5   right eye (x, y)
index  6-7   left eye (x, y)
index  8-9   nose tip (x, y)
index 10-11  right mouth corner (x, y)
index 12-13  left mouth corner (x, y)
index 14     confidence score (0 to 1)

The two classic mistakes: forgetting setInputSize (boxes come out wrong or nothing is detected) and not handling faces is None when there is no face. The _faces.jpg file comes out with boxes, landmarks, and the score drawn on it.

Recognizing with FaceRecognizerSF

The pipeline has three steps: alignCrop crops and aligns the face using the landmarks, feature produces a 128-number embedding, and match compares two embeddings. The thresholds come from the official face_detect.py sample: cosine >= 0.363 or L2 distance <= 1.128 means the same person. They were calibrated on the LFW dataset; on other data the values change, so calibrate on yours.

import cv2

from detect import detect

recognizer = cv2.FaceRecognizerSF.create(
    "models/face_recognition_sface_2021dec.onnx", ""
)

COSINE_THRESHOLD = 0.363  # >= means same person (official OpenCV sample)
L2_THRESHOLD = 1.128      # <= means same person


def embedding(img, face):
    aligned = recognizer.alignCrop(img, face)  # crops and aligns using the landmarks
    return recognizer.feature(aligned)         # 1x128 float32 vector


def compare(e1, e2):
    cos = recognizer.match(e1, e2, cv2.FaceRecognizerSF_FR_COSINE)
    l2 = recognizer.match(e1, e2, cv2.FaceRecognizerSF_FR_NORM_L2)
    return cos, l2


if __name__ == "__main__":
    a = cv2.imread("imgs/lena.jpg")
    b = cv2.imread("imgs/messi5.jpg")
    ref = embedding(a, detect(a)[0])
    print("embedding:", ref.shape, ref.dtype)

    variants = {
        "smaller (80%)": cv2.resize(a, None, fx=0.8, fy=0.8),
        "brighter": cv2.convertScaleAbs(a, alpha=1.15, beta=10),
        "blurred": cv2.GaussianBlur(a, (5, 5), 0),
        "mirrored": cv2.flip(a, 1),
        "other person": b,
    }
    for name, img in variants.items():
        faces = detect(img)
        if len(faces) == 0:
            print(f"{name:<13} no face")
            continue
        cos, l2 = compare(ref, embedding(img, faces[0]))
        same = cos >= COSINE_THRESHOLD and l2 <= L2_THRESHOLD
        print(f"{name:<13} cosine={cos:.3f}  l2={l2:.3f}  same_person={same}")
embedding: (1, 128) float32
smaller (80%) cosine=0.927  l2=0.383  same_person=True
brighter      cosine=0.897  l2=0.454  same_person=True
blurred       cosine=0.976  l2=0.219  same_person=True
mirrored      cosine=0.912  l2=0.420  same_person=True
other person  cosine=0.127  l2=1.321  same_person=False

The same person scored between 0.90 and 0.98 cosine; the other person, 0.127. But note: variants of the same photo are the easy case. Different photos, taken years apart, with other lighting and another camera, land much closer to the threshold.

To identify, enroll one embedding per person and compare the query against all of them. If the best cosine falls below the threshold, the answer is “unknown”, never the “closest match”.

import cv2
import numpy as np

from detect import detect
from recognize import COSINE_THRESHOLD, embedding

FILE = "gallery.npz"


def enroll(enrollments):
    """enrollments: {id: image}. Stores only the normalized embedding, never the photo."""
    ids, vectors = [], []
    for id_, img in enrollments.items():
        faces = detect(img)
        if len(faces) != 1:
            raise ValueError(f"{id_}: expected 1 face, found {len(faces)}")
        e = embedding(img, faces[0]).flatten()
        ids.append(id_)
        vectors.append(e / np.linalg.norm(e))
    np.savez(FILE, ids=np.array(ids), vectors=np.array(vectors, dtype=np.float32))


def remove(id_):
    g = np.load(FILE)  # allow_pickle=False is the default: arrays only, no pickle
    keep = g["ids"] != id_
    np.savez(FILE, ids=g["ids"][keep], vectors=g["vectors"][keep])


def identify(img, threshold=COSINE_THRESHOLD):
    g = np.load(FILE)
    faces = detect(img)
    if len(faces) == 0:
        return "no face", 0.0
    e = embedding(img, faces[0]).flatten()
    e = e / np.linalg.norm(e)
    sims = g["vectors"] @ e          # cosine against every enrollment (1:N)
    i = int(np.argmax(sims))
    if sims[i] < threshold:
        return "unknown", float(sims[i])
    return str(g["ids"][i]), float(sims[i])


if __name__ == "__main__":
    a = cv2.imread("imgs/lena.jpg")
    b = cv2.imread("imgs/messi5.jpg")
    enroll({"Enrollment 0001": a, "Enrollment 0002": b})
    g = np.load(FILE)
    print("gallery:", g["ids"].tolist(), g["vectors"].shape)

    queries = {
        "A brighter": cv2.convertScaleAbs(a, alpha=1.15, beta=10),
        "B mirrored": cv2.flip(b, 1),
    }
    for name, img in queries.items():
        who, sim = identify(img)
        print(f"{name:<11} -> {who} (cosine {sim:.3f})")

    remove("Enrollment 0002")  # data subject's deletion request
    who, sim = identify(queries["B mirrored"])
    print(f"after removing 0002: B mirrored -> {who} (cosine {sim:.3f})")
gallery: ['Enrollment 0001', 'Enrollment 0002'] (2, 128)
A brighter  -> Enrollment 0001 (cosine 0.897)
B mirrored  -> Enrollment 0002 (cosine 0.917)
after removing 0002: B mirrored -> unknown (cosine 0.164)

With normalized vectors, the dot product is the cosine: the 0.897 matches the match result from the previous section. The last line shows the deletion flow: once the enrollment is removed, the same person becomes “unknown”. The IDs are pseudonyms; the link to a name lives in a separate database, with separate access control.

Webcam and video

The loop below was not run with a camera (the test environment has none). We validated the same logic by reading a locally generated video, without the imshow window.

import cv2

from detect import detector, draw

cap = cv2.VideoCapture(0)  # 0 = first camera; or a video file path
if not cap.isOpened():
    raise SystemExit("could not open the camera")

w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
detector.setInputSize((w, h))  # the frame size does not change during the loop

try:
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        _, faces = detector.detect(frame)
        if faces is not None:
            frame = draw(frame, faces)
        cv2.imshow("faces", frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
finally:
    cap.release()
    cv2.destroyAllWindows()

A camera in a shared space collects other people’s data: tell people about it, don’t record by default, and don’t run identification without a legal basis.

Haar cascade: the legacy option

For years, cv2.CascadeClassifier with cv2.data.haarcascades was the standard way to find faces. In OpenCV 5.x it left the main module and moved to xobjdetect, in opencv_contrib. We tested the opencv-python 5.1.0.95 package:

import os

import cv2

xml = os.path.join(cv2.data.haarcascades, "haarcascade_frontalface_default.xml")
print("OpenCV", cv2.__version__)
print("CascadeClassifier available:", hasattr(cv2, "CascadeClassifier"))
print("XML present:", os.path.exists(xml))

if hasattr(cv2, "CascadeClassifier") and os.path.exists(xml):
    cascade = cv2.CascadeClassifier(xml)
    img = cv2.imread("imgs/lena.jpg")
    gray = cv2.equalizeHist(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
    rects = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    print("faces (x, y, w, h):", [r.tolist() for r in rects])  # no score, no landmarks
else:
    print("Haar cascade is not in this package; use FaceDetectorYN.")
OpenCV 5.1.0
CascadeClassifier available: False
XML present: False
Haar cascade is not in this package; use FaceDetectorYN.

The Haar branch did not run here. On OpenCV 4.x it works with opencv-python; on 5.x, check whether opencv-contrib-python ships the class and the XML files. For new code, YuNet is the better choice:

Criterion Haar cascade YuNet (FaceDetectorYN)
Technique Haar features on a grayscale image Neural network (CNN)
Output Box only Box, 5 landmarks, and score
Aligning for SFace Not possible, no landmarks alignCrop directly
Tilted face, profile, low light Fails often Much more robust
Tuning scaleFactor and minNeighbors by trial and error One score threshold

Production safeguards

  • Liveness (anti-spoofing): without a liveness check, a printed photo, a screen, or a replayed video gets past recognition. Common approaches are passive (texture and reflection analysis on a single frame), active (challenges such as blinking or turning the head), and depth or infrared sensors. The ISO/IEC 30107-3 standard covers testing of presentation attack detection.
  • Threshold, FAR, and FRR: raising the threshold lowers false accepts (FAR) and raises false rejects (FRR). Measure both rates on your population, per demographic group, and pick the operating point based on the cost of each error. The logic is the same as precision and recall in the machine learning with scikit-learn guide.
  • Store embeddings, not photos: discard the image after enrollment unless you have a purpose and a legal basis to keep it. The embedding is still biometric data.
  • Encryption, retention, and deletion: encrypt the gallery at rest, with keys in a KMS; set a retention period; implement end-to-end deletion, backups included.
  • Logging: record the decision, score, threshold, model version, and who queried, without images. See how to organize audit trails in Kubernetes audit logging for security.
  • Human review: denying access, locking an account, or accusing someone requires review by a person and a channel for appeal.

For identity verification in onboarding and anti-fraud, see banking security and fraud analytics, which shows where biometrics fit among the other signals.

Checklist

  • I decided whether the use case is detection, 1:1 verification, or 1:N identification
  • I have a legal basis under privacy law (LGPD art. 11 or the GDPR equivalent), a completed DPIA, and the DPO involved
  • I use images of people who consented, never photos scraped from the internet
  • I call setInputSize for every image and handle faces is None
  • I calibrated the threshold on my population, measuring FAR and FRR per group
  • I store only encrypted embeddings, with retention and end-to-end deletion
  • I have liveness, image-free logs, and human review for decisions that affect people

Getting face recognition to run takes an afternoon; making it fair and lawful takes much longer. Plan the second job before you start the first.

Get updates on new posts and stay in the loop!