跳转到主要内容

Python OpenCV 人脸识别

主标签

下面的文章先记下来。

Python OpenCV 人脸识别实战:从检测到识别全流程解析

下面抄一段:

四、人脸识别:LBPH算法实战

1. 识别原理

LBPH(Local Binary Patterns Histograms)通过比较人脸图像的LBP纹理直方图实现识别,具有光照鲁棒性。其流程为:

  1. 将人脸划分为16x16网格
  2. 计算每个网格的LBP直方图
  3. 拼接所有直方图作为特征向量
  4. 使用最近邻分类器匹配

2. 完整实现代码

import cv2
import numpy as np
import os
class FaceRecognizer:
    def __init__(self):
        self.recognizer = cv2.face.LBPHFaceRecognizer_create()
        self.labels = []
        self.faces = []
    def train(self, data_path):
        # 遍历数据集文件夹
        for person_name in os.listdir(data_path):
            person_path = os.path.join(data_path, person_name)
            if not os.path.isdir(person_path):
                continue
            # 为每个人分配标签(如"张三"->0)
            label = len(self.labels)
            self.labels.append(person_name)
            # 加载该人所有照片
            for img_name in os.listdir(person_path):
                img_path = os.path.join(person_path, img_name)
                img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
                if img is not None:
                    # 检测人脸(复用之前的检测器)
                    faces = face_cascade.detectMultiScale(img, 1.1, 4)
                    if len(faces) == 1:
                        x, y, w, h = faces[0]
                        face_roi = img[y:y+h, x:x+w]
                        self.faces.append(face_roi)
        # 训练模型
        self.recognizer.train(self.faces, np.array(range(len(self.labels))))
    def predict(self, img_path):
        img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
        faces = face_cascade.detectMultiScale(img, 1.1, 4)
        if len(faces) != 1:
            return "未检测到人脸或检测到多张人脸"
        x, y, w, h = faces[0]
        face_roi = img[y:y+h, x:x+w]
        # 预测
        label, confidence = self.recognizer.predict(face_roi)
        return f"{self.labels[label]} (置信度: {confidence:.2f})"
# 使用示例
recognizer = FaceRecognizer()
recognizer.train('dataset')  # dataset文件夹下包含按人名分类的子文件夹
print(recognizer.predict('test_face.jpg'))