All articles

Learn

Face recognition in Python: a beginner's tutorial (2 ways)

Two working paths, both under 30 lines: the local library and the hosted API. Pick the one that fits your project.

By SightRadar EngineeringUpdated 10 min read Markdown

TL;DR

There are two beginner-friendly ways to do face recognition in Python. Local: the face_recognition library (built on dlib) runs on your machine — great for learning and offline work, but the install can fight you and it's slower without a GPU. API: send an image to a hosted service and get matches back — no model downloads, no GPU, works the same on any machine. This tutorial shows both in full, and when to pick each.

If you searched "face recognition in Python," you'll mostly find one library. It's a great teaching tool, so we'll cover it — and then show the API path, which is what you'd reach for when the install pain isn't worth it or you need it to just work on a deadline.

Option A — local, with the face_recognition library

This runs entirely on your machine. It's the best way to *see* the pieces: it detects faces, computes a 128-number encoding (the embedding), and compares encodings by distance.

pip install face_recognition   # pulls in dlib + numpy
Install. dlib needs a C++ toolchain — see the fixes below if it fails.
import face_recognition

# 1) Enrol: encode a known face
known = face_recognition.load_image_file("alice.jpg")
known_enc = face_recognition.face_encodings(known)[0]   # 128-d embedding

# 2) Recognise: encode an unknown photo and compare
unknown = face_recognition.load_image_file("mystery.jpg")
encs = face_recognition.face_encodings(unknown)
for enc in encs:
    match = face_recognition.compare_faces([known_enc], enc, tolerance=0.6)[0]
    dist  = face_recognition.face_distance([known_enc], enc)[0]
    print("Alice!" if match else "unknown", f"(distance={dist:.3f})")
Enrol one known face, then check an unknown photo against it.

Note: Common install pain: pip install dlib failing means you're missing a C++ compiler (install CMake + build tools first) — this is the #1 reason beginners get stuck. On a low-RAM machine dlib's build can also get killed; use a prebuilt wheel or a Colab notebook if so.

Notice tolerance=0.6 — that's a threshold on the distance, and it's exactly the knob you'd calibrate on real data rather than trust blindly. Lower is stricter (fewer false matches, more misses). This is the same tradeoff every face system has; we cover it properly in choosing a face-match threshold.

Option B — a hosted API (no setup)

When you don't want to fight installs — or you want the same code to run on a teammate's laptop and a cloud box — a hosted API does the compute. You index faces into a collection, then search with a new photo. No GPU, no model files.

import os, requests
BASE = "https://api.sightradar.com"
H = {"Authorization": f"Bearer {os.environ['SR_API_KEY']}"}

# 1) Enrol a known face into a collection (create it once, for free)
requests.post(f"{BASE}/v1/collections", headers=H, json={"collection_id": "friends"})
requests.post(f"{BASE}/v1/collections/friends/index", headers=H,
              json={"url": "https://example.com/alice.jpg", "photoId": "alice"})

# 2) Recognise: search the collection with a new photo
r = requests.post(f"{BASE}/v1/collections/friends/search", headers=H,
                  json={"url": "https://example.com/mystery.jpg", "limit": 1})
matches = r.json().get("matches", [])
print(matches[0] if matches else "no match")   # score is on a 0-1 scale
Same enrol-then-recognise idea, over HTTP. Trial credits cover a student project.

Which should you use?

Local (face_recognition)Hosted API
Setupdlib build can be painfulpip install requests — done
Runs offlineYesNo (needs a request)
Needs a GPUNo, but slow without oneNo — compute is remote
Teaches the ML internalsYes — you see the encodingsLess — it's abstracted
Scales to many photosYou manage itBatch endpoint handles it
Best forLearning, offline, ML coursesDemos, deadlines, real apps

Tip: Learning the ML? Start with Option A so you can see the 128-d encoding and the distance. Shipping a demo on a deadline? Option B skips the setup and the SDK is Python-native. Both use the same mental model: enrol faces, then compare a new one.

Use faces responsibly

Even in a tutorial project: use your own face, people who consented, or a licensed dataset. Don't scrape photos or identify strangers. If you keep a database of encodings, be able to delete it. Face data is personal data even when it's "just numbers" — more in what is a faceprint.

Try the API path with a free key and your own photos.

Open the quickstart

Frequently asked questions

How do I do face recognition in Python?

Two beginner-friendly ways. Locally, install the face_recognition library (built on dlib), encode a known face into a 128-number embedding, then compare an unknown photo's encoding by distance. Or use a hosted API: index known faces into a collection over HTTP and search it with new photos — no model downloads or GPU. The local path teaches the ML internals; the API path skips setup and just works.

Why does pip install dlib fail?

Almost always a missing C++ build toolchain — install CMake and your platform's build tools first, then retry. On a low-RAM machine the dlib compile can be killed mid-build; use a prebuilt wheel or run in a cloud notebook like Colab. If you'd rather avoid the build entirely, a hosted API needs only `pip install requests`.

Do I need a GPU for face recognition in Python?

No. The face_recognition library runs on a CPU — it's just slower for large batches or real-time video. A hosted API offloads the compute entirely, so your machine only makes HTTP requests. Reserve a GPU for training your own model or heavy local batch processing.

What does the tolerance / threshold value mean?

It's the cutoff on face distance (or similarity) that decides a match. Stricter values reduce false matches but miss more real ones; looser values do the opposite. The library's default is a starting point, not a universal truth — calibrate it on your own labelled data. Note different tools use different scales (the face_recognition library uses a distance where lower is closer; SightRadar returns a 0-1 similarity where higher is closer).

Keep reading