引言
人脸识别技术在许多领域都有广泛的应用,如安全监控、门禁系统、智能设备等。本文将介绍如何使用Python实现一个人脸识别系统,并将其封装为一个类库。我们将逐步扩展和完善这个类库,增加代码优化、人脸照片存储到数据库、对特殊场景(如戴口罩、眼镜)的优化,以及灵活的识别距离设置。
1. 基本人脸识别实现
1.1 安装依赖
首先,我们需要安装一些必要的库:
pip install face_recognition opencv-python psycopg2-binary dlib
1.2 基本类库实现
我们创建一个 FaceRecognition 类,实现基本的人脸识别功能。
import cv2
import face_recognition
import numpy as np
import psycopg2
from psycopg2 import sql
from PIL import Image, ImageDraw
import configparser
class FaceRecognition:
    def __init__(self, db_config, config_file='config.ini'):
        """
        初始化FaceRecognition类。
        :param db_config: 数据库配置
        :param config_file: 配置文件路径
        """
        self.db_config = db_config
        self.config = configparser.ConfigParser()
        self.config.read(config_file)
        self.tolerance = float(self.config.get('FaceRecognition', 'tolerance'))
        self.model = self.config.get('FaceRecognition', 'model')
        self.known_face_encodings, self.known_face_names, self.tolerances = self.load_faces_from_db()
    def load_faces_from_db(self):
        """
        从数据库加载已知人脸信息。
        :return: 已知人脸的编码、名称和识别距离
        """
        known_face_encodings = []
        known_face_names = []
        tolerances = []
        conn = psycopg2.connect(**self.db_config)
        cursor = conn.cursor()
        cursor.execute("SELECT name, encoding, tolerance FROM faces")
        rows = cursor.fetchall()
        for row in rows:
            name, encoding_str, tolerance = row
            encoding = np.fromstring(encoding_str, dtype=float, sep=' ')
            known_face_encodings.append(encoding)
            known_face_names.append(name)
            tolerances.append(tolerance)
        cursor.close()
        conn.close()
        return known_face_encodings, known_face_names, tolerances
    def add_face_to_db(self, image_path, name, tolerance=None):
        """
        将新的人脸信息添加到数据库。
        :param image_path: 人脸图像的路径
        :param name: 人脸的名称
        :param tolerance: 识别距离
        """
        if tolerance is None:
            tolerance = self.tolerance
        # 加载图片
        image = face_recognition.load_image_file(image_path)
        # 编码人脸
        face_encoding = face_recognition.face_encodings(image)[0]
        encoding_str = ' '.join(map(str, face_encoding))
        conn = psycopg2.connect(**self.db_config)
        cursor = conn.cursor()
        query = sql.SQL("INSERT INTO faces (name, encoding, image_path, tolerance) VALUES (%s, %s, %s, %s)")
        cursor.execute(query, (name, encoding_str, image_path, tolerance))
        conn.commit()
        cursor.close()
        conn.close()
    def real_time_face_recognition(self, camera_index=0):
        """
        实现实时人脸识别。
        :param camera_index: 摄像头索引
        """
        # 打开摄像头
        video_capture = cv2.VideoCapture(camera_index)
        while True:
            # 读取一帧
            ret, frame = video_capture.read()
            if not ret:
                continue
            # 将帧转换为RGB
            rgb_frame = frame[:, :, ::-1]
            # 检测人脸位置
            face_locations = face_recognition.face_locations(rgb_frame, model=self.model)
            if not face_locations:
                continue
            # 编码人脸
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
            # 遍历检测到的人脸
            for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
                name = "Unknown"
                min_distance = float('inf')
                best_match_index = -1
                for i, (known_encoding, known_name, known_tolerance) in enumerate(zip(self.known_face_encodings, self.known_face_names, self.tolerances)):
                    # 计算欧氏距离
                    distance = face_recognition.face_distance([known_encoding], face_encoding)[0]
                    if distance < min_distance and distance <= known_tolerance:
                        min_distance = distance
                        name = known_name
                        best_match_index = i
                # 在帧上绘制矩形和标签
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
            # 显示结果
            cv2.imshow('Video', frame)
            # 按q键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        # 释放摄像头
        video_capture.release()
        cv2.destroyAllWindows()
    def train_model(self, training_data):
        """
        训练人脸识别模型。
        :param training_data: 训练数据,格式为 [(image_path, name, tolerance)]
        """
        for image_path, name, tolerance in training_data:
            self.add_face_to_db(image_path, name, tolerance)
# 示例用法
if __name__ == "__main__":
    # 数据库配置
    db_config = {
        'dbname': 'your_dbname',
        'user': 'your_user',
        'password': 'your_password',
        'host': 'localhost',
        'port': '5432'
    }
    # 初始化FaceRecognition类
    face_recognition = FaceRecognition(db_config)
    # 添加新人脸
    face_recognition.add_face_to_db('path/to/new_face.jpg', 'New Face', tolerance=0.6)
    # 启动实时人脸识别
    face_recognition.real_time_face_recognition(camera_index=0)
    # 训练模型
    training_data = [
        ('path/to/training_face_1.jpg', 'Training Face 1', 0.6),
        ('path/to/training_face_2.jpg', 'Training Face 2', 0.5),
        # 添加更多训练数据
    ]
    face_recognition.train_model(training_data)
2. 代码优化
2.1 优化加载和编码已知人脸
我们将优化 load_and_encode_faces 方法,使其更高效且更易维护。
def load_and_encode_faces(self, image_paths):
    """
    加载并编码已知人脸图像。
    :param image_paths: 已知人脸图像的路径列表
    :return: 已知人脸的编码和名称
    """
    known_face_encodings = []
    known_face_names = []
    for image_path in image_paths:
        try:
            # 加载图片
            image = face_recognition.load_image_file(image_path)
            # 编码人脸
            face_encoding = face_recognition.face_encodings(image)[0]
            # 获取文件名作为名字
            name = image_path.split('/')[-1].split('.')[0]
            # 添加到已知人脸列表
            known_face_encodings.append(face_encoding)
            known_face_names.append(name)
        except Exception as e:
            print(f"Error processing image {image_path}: {e}")
    return known_face_encodings, known_face_names
2.2 优化实时人脸识别
我们将优化 real_time_face_recognition 方法,减少不必要的计算,提高性能。
def real_time_face_recognition(self, camera_index=0):
    """
    实现实时人脸识别。
    :param camera_index: 摄像头索引
    """
    # 打开摄像头
    video_capture = cv2.VideoCapture(camera_index)
    while True:
        # 读取一帧
        ret, frame = video_capture.read()
        if not ret:
            continue
        # 将帧转换为RGB
        rgb_frame = frame[:, :, ::-1]
        # 检测人脸位置
        face_locations = face_recognition.face_locations(rgb_frame, model=self.model)
        if not face_locations:
            continue
        # 编码人脸
        face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
        # 遍历检测到的人脸
        for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
            # 匹配已知人脸
            matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding, tolerance=self.tolerance)
            name = "Unknown"
            # 计算欧氏距离
            face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = self.known_face_names[best_match_index]
            # 在帧上绘制矩形和标签
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        # 显示结果
        cv2.imshow('Video', frame)
        # 按q键退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    # 释放摄像头
    video_capture.release()
    cv2.destroyAllWindows()
3. 人脸照片存储数据库
我们将使用PostgreSQL数据库来存储人脸照片及其编码。首先,确保你已经安装了 psycopg2 库:
pip install psycopg2-binary
3.1 数据库表结构
创建一个名为 faces 的表,用于存储人脸信息:
CREATE TABLE faces (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    encoding TEXT NOT NULL,
    image_path VARCHAR(255) NOT NULL,
    tolerance FLOAT DEFAULT 0.6
);
3.2 修改类库以支持数据库操作
import cv2
import face_recognition
import numpy as np
import psycopg2
from psycopg2 import sql
from PIL import Image, ImageDraw
import configparser
class FaceRecognition:
    def __init__(self, db_config, config_file='config.ini'):
        """
        初始化FaceRecognition类。
        :param db_config: 数据库配置
        :param config_file: 配置文件路径
        """
        self.db_config = db_config
        self.config = configparser.ConfigParser()
        self.config.read(config_file)
        self.tolerance = float(self.config.get('FaceRecognition', 'tolerance'))
        self.model = self.config.get('FaceRecognition', 'model')
        self.known_face_encodings, self.known_face_names, self.tolerances = self.load_faces_from_db()
    def load_faces_from_db(self):
        """
        从数据库加载已知人脸信息。
        :return: 已知人脸的编码、名称和识别距离
        """
        known_face_encodings = []
        known_face_names = []
        tolerances = []
        conn = psycopg2.connect(**self.db_config)
        cursor = conn.cursor()
        cursor.execute("SELECT name, encoding, tolerance FROM faces")
        rows = cursor.fetchall()
        for row in rows:
            name, encoding_str, tolerance = row
            encoding = np.fromstring(encoding_str, dtype=float, sep=' ')
            known_face_encodings.append(encoding)
            known_face_names.append(name)
            tolerances.append(tolerance)
        cursor.close()
        conn.close()
        return known_face_encodings, known_face_names, tolerances
    def add_face_to_db(self, image_path, name, tolerance=None):
        """
        将新的人脸信息添加到数据库。
        :param image_path: 人脸图像的路径
        :param name: 人脸的名称
        :param tolerance: 识别距离
        """
        if tolerance is None:
            tolerance = self.tolerance
        # 加载图片
        image = face_recognition.load_image_file(image_path)
        # 编码人脸
        face_encoding = face_recognition.face_encodings(image)[0]
        encoding_str = ' '.join(map(str, face_encoding))
        conn = psycopg2.connect(**self.db_config)
        cursor = conn.cursor()
        query = sql.SQL("INSERT INTO faces (name, encoding, image_path, tolerance) VALUES (%s, %s, %s, %s)")
        cursor.execute(query, (name, encoding_str, image_path, tolerance))
        conn.commit()
        cursor.close()
        conn.close()
    def real_time_face_recognition(self, camera_index=0):
        """
        实现实时人脸识别。
        :param camera_index: 摄像头索引
        """
        # 打开摄像头
        video_capture = cv2.VideoCapture(camera_index)
        while True:
            # 读取一帧
            ret, frame = video_capture.read()
            if not ret:
                continue
            # 将帧转换为RGB
            rgb_frame = frame[:, :, ::-1]
            # 检测人脸位置
            face_locations = face_recognition.face_locations(rgb_frame, model=self.model)
            if not face_locations:
                continue
            # 编码人脸
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
            # 遍历检测到的人脸
            for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
                name = "Unknown"
                min_distance = float('inf')
                best_match_index = -1
                for i, (known_encoding, known_name, known_tolerance) in enumerate(zip(self.known_face_encodings, self.known_face_names, self.tolerances)):
                    # 计算欧氏距离
                    distance = face_recognition.face_distance([known_encoding], face_encoding)[0]
                    if distance < min_distance and distance <= known_tolerance:
                        min_distance = distance
                        name = known_name
                        best_match_index = i
                # 在帧上绘制矩形和标签
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
            # 显示结果
            cv2.imshow('Video', frame)
            # 按q键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        # 释放摄像头
        video_capture.release()
        cv2.destroyAllWindows()
    def train_model(self, training_data):
        """
        训练人脸识别模型。
        :param training_data: 训练数据,格式为 [(image_path, name, tolerance)]
        """
        for image_path, name, tolerance in training_data:
            self.add_face_to_db(image_path, name, tolerance)
# 示例用法
if __name__ == "__main__":
    # 数据库配置
    db_config = {
        'dbname': 'your_dbname',
        'user': 'your_user',
        'password': 'your_password',
        'host': 'localhost',
        'port': '5432'
    }
    # 初始化FaceRecognition类
    face_recognition = FaceRecognition(db_config)
    # 添加新人脸
    face_recognition.add_face_to_db('path/to/new_face.jpg', 'New Face', tolerance=0.6)
    # 启动实时人脸识别
    face_recognition.real_time_face_recognition(camera_index=0)
    # 训练模型
    training_data = [
        ('path/to/training_face_1.jpg', 'Training Face 1', 0.6),
        ('path/to/training_face_2.jpg', 'Training Face 2', 0.5),
        # 添加更多训练数据
    ]
    face_recognition.train_model(training_data)
4. 特殊场景优化
4.1 戴口罩优化
对于戴口罩的情况,我们可以使用面部关键点检测来辅助识别。OpenCV和dlib提供了面部关键点检测的功能。
def detect_face_keypoints(self, image):
    """
    检测面部关键点。
    :param image: 输入图像
    :return: 面部关键点
    """
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    faces = detector(gray)
    for face in faces:
        landmarks = predictor(gray, face)
        keypoints = [(landmarks.part(i).x, landmarks.part(i).y) for i in range(68)]
        return keypoints
    return None
4.2 戴眼镜优化
对于戴眼镜的情况,我们可以使用眼镜区域的关键点来辅助识别。
def is_wearing_glasses(self, keypoints):
    """
    判断是否戴眼镜。
    :param keypoints: 面部关键点
    :return: 是否戴眼镜
    """
    if keypoints:
        # 检查眼镜区域的关键点
        left_eye = keypoints[36:42]
        right_eye = keypoints[42:48]
        for point in left_eye + right_eye:
            x, y = point
            if image[y, x][0] > 100 and image[y, x][1] > 100 and image[y, x][2] > 100:
                return True
    return False
5. 灵活的识别距离设置
我们将识别距离作为系统参数来调整,并通过配置文件来管理。
5.1 配置文件
创建一个名为 config.ini 的配置文件,内容如下:
[FaceRecognition]
tolerance = 0.6
model = hog
5.2 修改类库以支持配置文件
import cv2
import face_recognition
import numpy as np
import psycopg2
from psycopg2 import sql
from PIL import Image, ImageDraw
import configparser
class FaceRecognition:
    def __init__(self, db_config, config_file='config.ini'):
        """
        初始化FaceRecognition类。
        :param db_config: 数据库配置
        :param config_file: 配置文件路径
        """
        self.db_config = db_config
        self.config = configparser.ConfigParser()
        self.config.read(config_file)
        self.tolerance = float(self.config.get('FaceRecognition', 'tolerance'))
        self.model = self.config.get('FaceRecognition', 'model')
        self.known_face_encodings, self.known_face_names, self.tolerances = self.load_faces_from_db()
    def load_faces_from_db(self):
        """
        从数据库加载已知人脸信息。
        :return: 已知人脸的编码、名称和识别距离
        """
        known_face_encodings = []
        known_face_names = []
        tolerances = []
        conn = psycopg2.connect(**self.db_config)
        cursor = conn.cursor()
        cursor.execute("SELECT name, encoding, tolerance FROM faces")
        rows = cursor.fetchall()
        for row in rows:
            name, encoding_str, tolerance = row
            encoding = np.fromstring(encoding_str, dtype=float, sep=' ')
            known_face_encodings.append(encoding)
            known_face_names.append(name)
            tolerances.append(tolerance)
        cursor.close()
        conn.close()
        return known_face_encodings, known_face_names, tolerances
    def add_face_to_db(self, image_path, name, tolerance=None):
        """
        将新的人脸信息添加到数据库。
        :param image_path: 人脸图像的路径
        :param name: 人脸的名称
        :param tolerance: 识别距离
        """
        if tolerance is None:
            tolerance = self.tolerance
        # 加载图片
        image = face_recognition.load_image_file(image_path)
        # 编码人脸
        face_encoding = face_recognition.face_encodings(image)[0]
        encoding_str = ' '.join(map(str, face_encoding))
        conn = psycopg2.connect(**self.db_config)
        cursor = conn.cursor()
        query = sql.SQL("INSERT INTO faces (name, encoding, image_path, tolerance) VALUES (%s, %s, %s, %s)")
        cursor.execute(query, (name, encoding_str, image_path, tolerance))
        conn.commit()
        cursor.close()
        conn.close()
    def real_time_face_recognition(self, camera_index=0):
        """
        实现实时人脸识别。
        :param camera_index: 摄像头索引
        """
        # 打开摄像头
        video_capture = cv2.VideoCapture(camera_index)
        while True:
            # 读取一帧
            ret, frame = video_capture.read()
            if not ret:
                continue
            # 将帧转换为RGB
            rgb_frame = frame[:, :, ::-1]
            # 检测人脸位置
            face_locations = face_recognition.face_locations(rgb_frame, model=self.model)
            if not face_locations:
                continue
            # 编码人脸
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
            # 遍历检测到的人脸
            for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
                name = "Unknown"
                min_distance = float('inf')
                best_match_index = -1
                for i, (known_encoding, known_name, known_tolerance) in enumerate(zip(self.known_face_encodings, self.known_face_names, self.tolerances)):
                    # 计算欧氏距离
                    distance = face_recognition.face_distance([known_encoding], face_encoding)[0]
                    if distance < min_distance and distance <= known_tolerance:
                        min_distance = distance
                        name = known_name
                        best_match_index = i
                # 在帧上绘制矩形和标签
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
            # 显示结果
            cv2.imshow('Video', frame)
            # 按q键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        # 释放摄像头
        video_capture.release()
        cv2.destroyAllWindows()
    def train_model(self, training_data):
        """
        训练人脸识别模型。
        :param training_data: 训练数据,格式为 [(image_path, name, tolerance)]
        """
        for image_path, name, tolerance in training_data:
            self.add_face_to_db(image_path, name, tolerance)
# 示例用法
if __name__ == "__main__":
    # 数据库配置
    db_config = {
        'dbname': 'your_dbname',
        'user': 'your_user',
        'password': 'your_password',
        'host': 'localhost',
        'port': '5432'
    }
    # 初始化FaceRecognition类
    face_recognition = FaceRecognition(db_config)
    # 添加新人脸
    face_recognition.add_face_to_db('path/to/new_face.jpg', 'New Face', tolerance=0.6)
    # 启动实时人脸识别
    face_recognition.real_time_face_recognition(camera_index=0)
    # 训练模型
    training_data = [
        ('path/to/training_face_1.jpg', 'Training Face 1', 0.6),
        ('path/to/training_face_2.jpg', 'Training Face 2', 0.5),
        # 添加更多训练数据
    ]
    face_recognition.train_model(training_data)
6. 未来工作
6.1 多摄像头支持
扩展类库以支持多个摄像头。可以通过传递多个摄像头索引来实现。
def real_time_face_recognition_multi_camera(self, camera_indices):
    """
    实现多摄像头实时人脸识别。
    :param camera_indices: 摄像头索引列表
    """
    video_captures = [cv2.VideoCapture(index) for index in camera_indices]
    while True:
        frames = []
        for capture in video_captures:
            ret, frame = capture.read()
            if not ret:
                frames.append(None)
                continue
            frames.append(frame)
        for frame in frames:
            if frame is None:
                continue
            # 将帧转换为RGB
            rgb_frame = frame[:, :, ::-1]
            # 检测人脸位置
            face_locations = face_recognition.face_locations(rgb_frame, model=self.model)
            if not face_locations:
                continue
            # 编码人脸
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
            # 遍历检测到的人脸
            for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
                name = "Unknown"
                min_distance = float('inf')
                best_match_index = -1
                for i, (known_encoding, known_name, known_tolerance) in enumerate(zip(self.known_face_encodings, self.known_face_names, self.tolerances)):
                    # 计算欧氏距离
                    distance = face_recognition.face_distance([known_encoding], face_encoding)[0]
                    if distance < min_distance and distance <= known_tolerance:
                        min_distance = distance
                        name = known_name
                        best_match_index = i
                # 在帧上绘制矩形和标签
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
            # 显示结果
            cv2.imshow('Video', frame)
            # 按q键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    # 释放摄像头
    for capture in video_captures:
        capture.release()
    cv2.destroyAllWindows()
6.2 性能优化
优化人脸检测和识别的性能,特别是在高分辨率视频流中。可以考虑使用多线程或多进程来加速处理。
from concurrent.futures import ThreadPoolExecutor
def process_frame(self, frame):
    """
    处理单帧图像。
    :param frame: 输入图像
    :return: 处理后的图像
    """
    # 将帧转换为RGB
    rgb_frame = frame[:, :, ::-1]
    # 检测人脸位置
    face_locations = face_recognition.face_locations(rgb_frame, model=self.model)
    if not face_locations:
        return frame
    # 编码人脸
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
    # 遍历检测到的人脸
    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        name = "Unknown"
        min_distance = float('inf')
        best_match_index = -1
        for i, (known_encoding, known_name, known_tolerance) in enumerate(zip(self.known_face_encodings, self.known_face_names, self.tolerances)):
            # 计算欧氏距离
            distance = face_recognition.face_distance([known_encoding], face_encoding)[0]
            if distance < min_distance and distance <= known_tolerance:
                min_distance = distance
                name = known_name
                best_match_index = i
        # 在帧上绘制矩形和标签
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
    return frame
def real_time_face_recognition_multi_camera(self, camera_indices):
    """
    实现多摄像头实时人脸识别。
    :param camera_indices: 摄像头索引列表
    """
    video_captures = [cv2.VideoCapture(index) for index in camera_indices]
    executor = ThreadPoolExecutor(max_workers=len(camera_indices))
    while True:
        frames = []
        for capture in video_captures:
            ret, frame = capture.read()
            if not ret:
                frames.append(None)
                continue
            frames.append(frame)
        processed_frames = list(executor.map(self.process_frame, frames))
        for frame in processed_frames:
            if frame is None:
                continue
            # 显示结果
            cv2.imshow('Video', frame)
            # 按q键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    # 释放摄像头
    for capture in video_captures:
        capture.release()
    cv2.destroyAllWindows()
6.3 多平台支持
确保类库在不同操作系统和硬件平台上都能正常运行。可以通过使用跨平台的库和工具来实现。
6.4 用户界面
开发一个图形用户界面(GUI),使用户更容易使用和配置人脸识别系统。可以使用 tkinter 或 PyQt 等库来实现。
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
class FaceRecognitionGUI:
    def __init__(self, master, face_recognition):
        self.master = master
        self.face_recognition = face_recognition
        self.master.title("Face Recognition System")
        self.label = tk.Label(master, text="Face Recognition System")
        self.label.pack()
        self.add_face_button = tk.Button(master, text="Add New Face", command=self.add_new_face)
        self.add_face_button.pack()
        self.start_recognition_button = tk.Button(master, text="Start Real-Time Recognition", command=self.start_real_time_recognition)
        self.start_recognition_button.pack()
    def add_new_face(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            name = filedialog.askstring("Input", "Enter the name of the person:")
            if name:
                self.face_recognition.add_face_to_db(file_path, name, tolerance=0.6)
                self.label.config(text=f"Added new face: {name}")
    def start_real_time_recognition(self):
        self.face_recognition.real_time_face_recognition(camera_index=0)
if __name__ == "__main__":
    # 数据库配置
    db_config = {
        'dbname': 'your_dbname',
        'user': 'your_user',
        'password': 'your_password',
        'host': 'localhost',
        'port': '5432'
    }
    # 初始化FaceRecognition类
    face_recognition = FaceRecognition(db_config)
    # 初始化GUI
    root = tk.Tk()
    app = FaceRecognitionGUI(root, face_recognition)
    root.mainloop()
结论
通过上述步骤,我们不仅优化了代码,还增加了人脸照片存储到数据库、对特殊场景的优化,以及灵活的识别距离设置。这些改进使得人脸识别系统更加精确和健壮。希望这篇文章对你有帮助!










