用 face_recognition 做一个人脸识别小工具:从单张比对到持久化人脸库
需求很朴素:摄像头对着门口,识别画面里是不是”登记过的那个人”。第一版只做了单张比对——拍一张存下来,后面实时比对是不是同一个人。用起来发现问题:程序一关就忘了,每次都得重新拍。
于是有了第二版:多个人脸、带名字、存盘、能删。这篇把两版放在一起讲,重点说清中间踩的坑。GUI 用 Tkinter,识别用 face_recognition(就是 dlib 那个)。
仅作技术记录,代码不含任何真实人脸数据或身份信息。
一、依赖与一个大坑
pip install face_recognition opencv-python pillow numpy
face_recognition 底层是 dlib。Linux 上装 dlib 会现场编译,几分钟起步;Windows 上更麻烦,经常因为缺 CMake / Visual Studio Build Tools 直接失败。
省事的办法是用预编译 wheel:
# Windows 可以先装这个,跳过编译
pip install dlib-bin
pip install face_recognition
dlib-bin 提供现成的二进制包,装完 face_recognition 就能直接 import。这一步卡过很久,值得先记下来。
二、第一版:单张比对
核心逻辑就三步:
face_locations()找到脸在哪face_encodings()把脸转成 128 维向量face_distance()算两个向量的距离,小于阈值就算同一个人
def capture_face(self):
ret, frame = self.cap.read()
if not ret:
return
face_locations = face_recognition.face_locations(frame)
if face_locations:
face_encodings = face_recognition.face_encodings(frame, face_locations)
self.target_face_encoding = face_encodings[0]
比对:
matches = face_recognition.compare_faces(
[self.target_face_encoding], face_encodings[0])
distance = face_recognition.face_distance(
[self.target_face_encoding], face_encodings[0])
result_text = "人脸信息一致" if matches[0] else "不一致"
compare_faces 默认阈值 0.6。距离越小越像,超过 0.6 判为不同人。
中文显示要借 PIL 画:
pil_image = Image.fromarray(rgb_frame)
draw = ImageDraw.Draw(pil_image)
draw.rectangle([left, top, right, bottom], outline=color, width=2)
draw.text((left, top - 30), result_text, font=self.font, fill=color)
rgb_frame = np.array(pil_image)
OpenCV 的 putText 不支持中文,只能转 PIL 再转回来。顺带的好处是能用 TrueType 字体,字号可控。
字体路径要跨平台兜底:
font_paths = [
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", # Linux
"/System/Library/Fonts/PingFang.ttc", # macOS
"C:/Windows/Fonts/simhei.ttf", # Windows
"C:/Windows/Fonts/microsoftyahei.ttf", # Windows
]
三、第一版的问题
跑起来之后暴露三件事:
问题一:存下来的人脸图偏蓝
# 原文写法
cv2.imwrite("faces/target_face.jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
cv2.VideoCapture.read() 返回的 frame 本来就是 BGR。再走一遍 RGB2BGR 等于把通道调换了两次中的一次——存下来 R 和 B 互换,人脸发青发蓝。
# 正确:直接存
cv2.imwrite("faces/target_face.jpg", frame)
只有从 PIL(RGB)转过来的图才需要 RGB2BGR。这个错很容易犯,因为”OpenCV 要 BGR”这句话记住了,但忘了读进来的已经是 BGR。
问题二:画面只认第一张脸
matches = face_recognition.compare_faces([encoding], face_encodings[0])
face_encodings[0] 只取画面里第一张脸,其余全忽略。如果框里还有别人,画面上只有第一个被判定,其他脸连框都不画。
问题三:root.after(10, ...) 把界面拖死
def update_frame(self):
...
self.root.after(10, self.update_frame) # 每 10ms 一次
face_recognition.face_locations() 单帧在 CPU 上大概 100~300ms。定时器 10ms 触发一次,但每次处理要几百毫秒,Tk 的事件队列越积越多,最后界面完全卡死——点了没反应,窗口拖不动。
改成按”上一帧处理完再排下一帧”,并且把间隔调大:
self.root.after(30, self.update_frame)
更彻底的做法是把检测丢到单独线程,主线程只管画。但对这个场景,先把频率降下来就够了。
四、第二版:做成人脸库
第二版要解决四件事:
- 存多个人,每人有名字
- 关掉程序不丢
- 能看列表、能删
- 阈值可调
数据结构很简单,一个 list of dict:
# encoding 是 face_recognition 给出的 128 维向量
self.known_faces = [
{"name": "张三", "encoding": np.zeros(128, dtype=np.float64)},
]
持久化用 npy:
np.save("faces/known_faces.npy", self.known_faces)
读取:
self.known_faces = np.load("faces/known_faces.npy", allow_pickle=True).tolist()
这里必须 allow_pickle=True。原因是 list 里装的是 dict,dict 里又是 ndarray——numpy 存不了同质数组,只能退化成 object array,也就是 pickle。不加这个参数直接报错。
代价是别去加载来路不明的 npy 文件,pickle 反序列化能执行任意代码。自己程序写的文件无所谓。
还有个更稳的思路(我在新版里加了):npy 只是缓存,丢了就从图片重建。
def load_all_saved_faces(self):
# 先试缓存
if os.path.exists("faces/known_faces.npy"):
try:
self.known_faces = np.load("faces/known_faces.npy", allow_pickle=True).tolist()
return
except Exception:
pass
# 缓存坏了就扫图片重新提特征
self.known_faces = []
for filename in os.listdir("faces"):
if filename.endswith(".jpg"):
name = os.path.splitext(filename)[0]
image = face_recognition.load_image_file(os.path.join("faces", filename))
encodings = face_recognition.face_encodings(image)
if encodings:
self.known_faces.append({"name": name, "encoding": encodings[0]})
if self.known_faces:
np.save("faces/known_faces.npy", self.known_faces)
图片是真相,npy 是缓存。这个设计比纯 npy 可靠——npy 版本不兼容、pickle 出问题、文件写了一半断电,都能靠图片恢复。
五、多人匹配:找最近的那个
第一版是”跟一个比对”,第二版要”跟一堆比对,取最像的”:
name = "未知人脸"
color = (255, 0, 0)
best_distance = 1.0
best_match_index = -1
for i, face in enumerate(self.known_faces):
distances = face_recognition.face_distance([face["encoding"]], face_encodings[0])
if distances[0] < best_distance:
best_distance = distances[0]
best_match_index = i
然后按阈值判:
if len(self.known_faces) == 1:
adjusted_threshold = max(0.4, self.recognition_threshold - 0.05)
if best_distance < adjusted_threshold:
name = self.known_faces[best_match_index]["name"]
color = (0, 255, 0)
else:
if best_distance < self.recognition_threshold:
name = self.known_faces[best_match_index]["name"]
color = (0, 255, 0)
“只有一个人时阈值再收紧 0.05”这个处理有道理——库里只有一个候选,就没有”选错人”的可能,只有”认错成这个人”的可能,所以该更严格。
顺带一个效率优化:face_distance 支持一次传整个矩阵。库里有 20 个人时,逐个 face_distance 要调 20 次,可以合成一次:
known = np.array([f["encoding"] for f in self.known_faces])
dists = face_recognition.face_distance(known, face_encodings[0])
best_match_index = int(np.argmin(dists))
best_distance = float(dists[best_match_index])
六、还有几处坑
坑:close_camera 之后必须把 cap 置 None
def close_camera(self):
self.running = False
if self.cap is not None:
self.cap.release()
# 少了这行
# self.cap = None
release() 只是释放设备,对象还在。下次 open_camera 判断 if self.cap is None or not self.cap.isOpened(),理论上能靠 isOpened() 兜住,但有些平台 release() 后 isOpened() 行为不一致,最稳还是置 None。
坑:关窗口时 after 还在跑
root.after() 排的任务不会因为窗口关闭自动取消。on_close 里应该先停掉标志位,再 destroy(),否则 Tk 可能在已销毁的控件上回调,报一堆 TclError: invalid command name。
坑:名字直接当文件名
img_path = f"faces/{name}.jpg"
名字里带 /、\、: 或者长度超限就写不进去。至少做个过滤:
safe = re.sub(r'[\\/:*?"<>|]', "_", name).strip()
坑:拍摄时不检查人脸数量
第二版要求”画面里只有一张脸”:
if face_locations and len(face_locations) == 1:
这是对的。如果框进两张脸却只取了 face_encodings[0],存下来的可能是别人。
七、完整脚本(第二版,修好上述问题)
import os
import re
import tkinter as tk
from tkinter import messagebox, simpledialog
import cv2
import face_recognition
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageTk
FACES_DIR = "faces"
NPY_PATH = os.path.join(FACES_DIR, "known_faces.npy")
def load_chinese_font(size=20):
for path in (
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/System/Library/Fonts/PingFang.ttc",
"C:/Windows/Fonts/simhei.ttf",
"C:/Windows/Fonts/microsoftyahei.ttf",
):
if os.path.exists(path):
try:
return ImageFont.truetype(path, size)
except OSError:
continue
return ImageFont.load_default()
def safe_name(name):
return re.sub(r'[\\/:*?"<>|]', "_", name).strip()
class FaceApp:
def __init__(self, root):
self.root = root
self.root.title("人脸识别")
self.root.geometry("820x620")
self.cap = None
self.running = False
self.recognizing = False
self.threshold = 0.55
self.known_faces = []
self.font = load_chinese_font()
os.makedirs(FACES_DIR, exist_ok=True)
self.load_faces()
self.build_ui()
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
# ---------- 人脸库 ----------
def load_faces(self):
if os.path.exists(NPY_PATH):
try:
self.known_faces = np.load(NPY_PATH, allow_pickle=True).tolist()
return
except Exception:
pass
for fn in os.listdir(FACES_DIR):
if not fn.lower().endswith((".jpg", ".jpeg", ".png")):
continue
name = os.path.splitext(fn)[0]
encs = face_recognition.face_encodings(
face_recognition.load_image_file(os.path.join(FACES_DIR, fn))
)
if encs:
self.known_faces.append({"name": name, "encoding": encs[0]})
if self.known_faces:
self.save_faces()
def save_faces(self):
np.save(NPY_PATH, self.known_faces)
# ---------- 界面 ----------
def build_ui(self):
main = tk.Frame(self.root)
main.pack(fill=tk.BOTH, expand=True)
left = tk.Frame(main, width=200, bg="#f0f0f0")
left.pack(side=tk.LEFT, fill=tk.Y)
style = dict(font=("SimHei", 11), width=15, height=2, bg="#4CAF50", fg="white")
self.btn_cam = tk.Button(left, text="打开摄像头", command=self.toggle_camera, **style)
self.btn_cam.pack(pady=8)
self.btn_shot = tk.Button(left, text="登记人脸", command=self.capture, state=tk.DISABLED, **style)
self.btn_shot.pack(pady=8)
self.btn_rec = tk.Button(left, text="开始识别", command=self.toggle_recognition, state=tk.DISABLED, **style)
self.btn_rec.pack(pady=8)
tk.Label(left, text="识别阈值", bg="#f0f0f0", font=("SimHei", 10)).pack(pady=(10, 0))
self.scale = tk.Scale(left, from_=0.40, to=0.70, resolution=0.01,
orient=tk.HORIZONTAL, command=self.set_threshold)
self.scale.set(self.threshold)
self.scale.pack(padx=8)
self.lbl_count = tk.Label(left, text=f"已登记: {len(self.known_faces)}", bg="#f0f0f0", font=("SimHei", 10))
self.lbl_count.pack(pady=8)
self.listbox = tk.Listbox(left, width=16, height=10, font=("SimHei", 10))
self.listbox.pack(padx=8)
self.refresh_list()
tk.Button(left, text="删除选中", command=self.delete_selected,
font=("SimHei", 10), width=15).pack(pady=8)
right = tk.Frame(main, bg="black")
right.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
self.canvas = tk.Label(right)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.status = tk.Label(self.root, text="就绪", bg="#e0e0e0", height=2, font=("SimHei", 10))
self.status.pack(side=tk.BOTTOM, fill=tk.X)
def refresh_list(self):
self.listbox.delete(0, tk.END)
for f in self.known_faces:
self.listbox.insert(tk.END, f["name"])
self.lbl_count.config(text=f"已登记: {len(self.known_faces)}")
self.btn_rec.config(state=tk.NORMAL if self.running and self.known_faces else tk.DISABLED)
def set_threshold(self, v):
self.threshold = float(v)
# ---------- 摄像头 ----------
def toggle_camera(self):
if self.cap is not None and self.cap.isOpened():
self.stop_camera()
else:
self.start_camera()
def start_camera(self):
cap = cv2.VideoCapture(0)
if not cap.isOpened():
messagebox.showerror("错误", "打不开摄像头")
return
self.cap = cap
self.running = True
self.btn_cam.config(text="关闭摄像头")
self.btn_shot.config(state=tk.NORMAL)
self.refresh_list()
self.status.config(text="摄像头已打开")
self.loop()
def stop_camera(self):
self.running = False
self.recognizing = False
if self.cap is not None:
self.cap.release()
self.cap = None # 关键:置 None
self.canvas.config(image="")
self.btn_cam.config(text="打开摄像头")
self.btn_shot.config(state=tk.DISABLED)
self.btn_rec.config(state=tk.DISABLED, text="开始识别")
self.status.config(text="摄像头已关闭")
def capture(self):
if self.cap is None:
return
ok, frame = self.cap.read()
if not ok:
return
locs = face_recognition.face_locations(frame)
if len(locs) != 1:
messagebox.showwarning("提示", "画面里要正好有一个人脸")
return
name = simpledialog.askstring("登记", "请输入姓名:")
if not name or not name.strip():
return
name = safe_name(name)
if any(f["name"] == name for f in self.known_faces):
if not messagebox.askyesno("确认", f"{name} 已存在,覆盖吗?"):
return
self.known_faces = [f for f in self.known_faces if f["name"] != name]
# frame 本来就是 BGR,直接写
cv2.imwrite(os.path.join(FACES_DIR, f"{name}.jpg"), frame)
enc = face_recognition.face_encodings(frame, locs)[0]
self.known_faces.append({"name": name, "encoding": enc})
self.save_faces()
self.refresh_list()
self.status.config(text=f"已登记 {name}")
def delete_selected(self):
sel = self.listbox.curselection()
if not sel:
return
name = self.known_faces[sel[0]]["name"]
if not messagebox.askyesno("确认", f"删除 {name}?"):
return
del self.known_faces[sel[0]]
img = os.path.join(FACES_DIR, f"{name}.jpg")
if os.path.exists(img):
os.remove(img)
if self.known_faces:
self.save_faces()
elif os.path.exists(NPY_PATH):
os.remove(NPY_PATH)
self.refresh_list()
def toggle_recognition(self):
if not self.known_faces:
return
self.recognizing = not self.recognizing
self.btn_rec.config(text="停止识别" if self.recognizing else "开始识别")
# ---------- 主循环 ----------
def loop(self):
if not self.running:
return
ok, frame = self.cap.read()
if not ok:
self.stop_camera()
return
if self.recognizing and self.known_faces:
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
locs = face_recognition.face_locations(rgb)
encs = face_recognition.face_encodings(rgb, locs)
known = np.array([f["encoding"] for f in self.known_faces])
pil = Image.fromarray(rgb)
draw = ImageDraw.Draw(pil)
for (top, right, bottom, left), enc in zip(locs, encs):
dists = face_recognition.face_distance(known, enc)
idx = int(np.argmin(dists))
best = float(dists[idx])
hit = best < self.threshold
label = f"{self.known_faces[idx]['name']} {1 - best:.2f}" if hit else "未知"
color = (0, 200, 0) if hit else (255, 0, 0)
draw.rectangle([left, top, right, bottom], outline=color, width=2)
draw.text((left, max(top - 22, 0)), label, font=self.font, fill=color)
frame = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR)
img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
imgtk = ImageTk.PhotoImage(image=img)
self.canvas.imgtk = imgtk
self.canvas.config(image=imgtk)
# 处理完再排下一次,避免堆积
self.root.after(30, self.loop)
def on_close(self):
self.running = False
if self.cap is not None:
self.cap.release()
self.cap = None
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
FaceApp(root)
root.mainloop()
八、效果与局限
跑起来是能用的:登记两三个人,正面、光线均匀的情况下识别稳,距离 0.3~0.45 之间。
但它有明显边界:
- 侧脸、低头、遮挡就不行。dlib 的 HOG 模型只对正脸友好,侧脸基本检不到。要改善得换 CNN 模型:
face_recognition.face_locations(img, model="cnn"),代价是要 GPU,CPU 上慢十倍 - 活体检测完全没有。拿张照片对着摄像头也能通过。真要做门禁,这版是不够的
- 光照敏感。逆光、暗光下编码会漂移,同一个人距离可能跑到 0.6 以上
- 128 维编码不是加密特征。理论上可以从编码反推近似人脸,别把 npy 当安全凭证
如果只是做个”认出熟人”的小玩具,这套足够。要往生产走,建议直接上 InsightFace 或者现成的 SDK,人脸检测、对齐、活体、质量评估都是一整套的。
小结
这篇的两个教训,跟人脸识别本身关系不大:
一是单位搞错。cv2.VideoCapture 给的是 BGR,imwrite 要的也是 BGR,中间不该再转一次。这种”多转了一次”的错最隐蔽——不报错,只是颜色不对。
二是定时器不能硬刚耗时操作。after(10, ...) 遇上 200ms 的检测,必然堆积。要么降频,要么丢线程。GUI 里所有”卡死”问题,八成都是这条。
至于持久化,把原始数据当真相、把缓存当加速这个原则,比纠结 npy 还是 json 重要得多。
评论 · 讨论
评论由 GitHub Discussions 承载 · 去讨论区留言 →