Python深度学习实现人脸识别与管理系统详解

Python-基于深度学习的人脸识别与管理系统(UI界面整强版Python代码)Python版本3.8
功能:
系统实现了集识别人脸、录入人脸、管理人脸在内的多项功能:包括通过选择人脸图片、视频、摄像头进行已录入人脸的实时识别;可通过图片和摄像头检测人脸并录入新的人脸;通过系统管理和更新人脸数据等功能,检测速度快、识别精度较高。
①选择人脸照片识别。
②选择人脸视频识别。
③摄像头检测人脸识别。
④录入人脸功能。
⑤管理人脸功能。

为了实现一个基于深度学习的人脸识别与管理系统,我们可以使用Python结合一些流行的库,如OpenCV用于图像处理、dlib或face_recognition用于人脸识别、以及Pandas用于数据管理。下面是一个简化版本的代码示例,展示了如何实现你提到的功能。

安装依赖

首先,确保安装了必要的Python包:

pip install opencv-python dlib face-recognition pandas numpy

代码实现

1. 初始化和辅助函数
import cv2
import face_recognition
import os
import numpy as np
import pandas as pd

# 加载已知人脸编码和名字
def load_known_faces():
    known_face_encodings = []
    known_face_names = []
    for filename in os.listdir('known_faces'):
        if filename.endswith('.jpg') or filename.endswith('.png'):
            image = face_recognition.load_image_file(f'known_faces/{filename}')
            encoding = face_recognition.face_encodings(image)[0]
            known_face_encodings.append(encoding)
            known_face_names.append(filename.split('.')[0])
    return known_face_encodings, known_face_names

# 将新面孔保存到磁盘
def save_face(image, name):
    filename = f'known_faces/{name}.jpg'
    cv2.imwrite(filename, image)
    print(f'Saved {filename}')

# 更新数据库
def update_database(name):
    df = pd.read_csv('faces.csv')
    if name not in df['Name'].values:
        df = df.append({'Name': name}, ignore_index=True)
        df.to_csv('faces.csv', index=False)
        print(f'Updated database with new name: {name}')
2. 选择照片进行识别
def recognize_from_image(image_path):
    image = face_recognition.load_image_file(image_path)
    face_locations = face_recognition.face_locations(image)
    face_encodings = face_recognition.face_encodings(image, face_locations)

    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
        name = "Unknown"

        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]

        cv2.rectangle(image, (left, top), (right, bottom), (0, 0, 255), 2)
        cv2.putText(image, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

    cv2.imshow("Image", image)
    cv2.waitKey(0)
3. 视频流中的人脸识别
def recognize_from_video(video_path=0): # 使用摄像头时video_path设为0
    video_capture = cv2.VideoCapture(video_path)
    while True:
        ret, frame = video_capture.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            top *= 4
            right *= 4
            bottom *= 4
            left *= 4
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    video_capture.release()
    cv2.destroyAllWindows()
4. 录入新的人脸
def capture_and_save_face(name):
    video_capture = cv2.VideoCapture(0)
    while True:
        ret, frame = video_capture.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        
        face_locations = face_recognition.face_locations(rgb_small_frame)
        if len(face_locations) > 0:
            top, right, bottom, left = face_locations[0]
            face_image = frame[top*4:bottom*4, left*4:right*4]
            save_face(face_image, name)
            update_database(name)
            break
        
        cv2.imshow('Capture Face', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    video_capture.release()
    cv2.destroyAllWindows()
5. 管理人脸功能

这可以通过一个简单的界面或者命令行工具来完成,例如查看当前已录入的所有人脸名称列表,并提供删除某个特定人脸的功能等。这部分可以根据具体需求进一步开发。

总结

以上代码片段提供了一个基本框架,你可以根据自己的需要进一步扩展和完善。比如添加更多错误处理逻辑、优化性能、增加用户界面等。此外,考虑到隐私和安全问题,在实际部署这样的系统之前,请确保遵守相关的法律法规。
根据你提供的截图和需求,我们可以构建一个基于Python的人脸识别与管理系统。这个系统将包括以下几个主要功能:

  1. 选择人脸照片识别
  2. 选择人脸视频识别
  3. 摄像头检测人脸识别
  4. 录入人脸功能
  5. 管理人脸功能

我们将使用face_recognition库进行人脸识别,并使用PyQt5来构建图形用户界面(GUI)。以下是完整的代码实现。

安装依赖

首先,确保安装了必要的Python包:

pip install opencv-python face-recognition numpy pandas PyQt5

代码实现

1. 初始化和辅助函数
import cv2
import face_recognition
import os
import numpy as np
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer
from FaceRecognition_Ui import Ui_MainWindow

class FaceRecognitionSystem(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.known_face_encodings = []
        self.known_face_names = []
        self.load_known_faces()
        self.init_ui()

    def init_ui(self):
        self.pushButton_load.clicked.connect(self.load_image)
        self.pushButton_camera.clicked.connect(self.start_camera)
        self.pushButton_add.clicked.connect(self.add_face)
        self.pushButton_manage.clicked.connect(self.manage_faces)

    def load_known_faces(self):
        for filename in os.listdir('known_faces'):
            if filename.endswith('.jpg') or filename.endswith('.png'):
                image = face_recognition.load_image_file(f'known_faces/{filename}')
                encoding = face_recognition.face_encodings(image)[0]
                self.known_face_encodings.append(encoding)
                self.known_face_names.append(filename.split('.')[0])

    def load_image(self):
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png)", options=options)
        if file_name:
            self.recognize_from_image(file_name)

    def recognize_from_image(self, image_path):
        image = face_recognition.load_image_file(image_path)
        face_locations = face_recognition.face_locations(image)
        face_encodings = face_recognition.face_encodings(image, 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)
            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(image, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.putText(image, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

        qimage = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888).rgbSwapped()
        pixmap = QPixmap.fromImage(qimage)
        self.label.setPixmap(pixmap)

    def start_camera(self):
        self.cap = cv2.VideoCapture(0)
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(10)

    def update_frame(self):
        ret, frame = self.cap.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]

        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_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)
            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]

            top *= 4
            right *= 4
            bottom *= 4
            left *= 4
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

        qimage = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888).rgbSwapped()
        pixmap = QPixmap.fromImage(qimage)
        self.label.setPixmap(pixmap)

    def add_face(self):
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png)", options=options)
        if file_name:
            image = face_recognition.load_image_file(file_name)
            encoding = face_recognition.face_encodings(image)[0]
            self.known_face_encodings.append(encoding)
            name = os.path.basename(file_name).split('.')[0]
            self.known_face_names.append(name)
            cv2.imwrite(f'known_faces/{name}.jpg', image)
            QMessageBox.information(self, "Success", f"Face {name} added successfully!")

    def manage_faces(self):
        # Implement management functionality here
        pass

if __name__ == "__main__":
    app = QApplication([])
    window = FaceRecognitionSystem()
    window.show()
    app.exec_()

解释

  1. 初始化和辅助函数

  2. load_known_faces:加载已知的人脸图像并提取特征编码。
  3. recognize_from_image:从图片中识别已知人脸。
  4. start_cameraupdate_frame:从摄像头实时捕获帧并识别已知人脸。
  5. add_face:添加新的人脸到数据库。
  6. UI部分

  7. 使用PyQt5构建了一个简单的GUI,包括按钮和标签。
  8. 按钮分别用于加载图片、启动摄像头、添加新的人脸和管理人脸。
  9. 运行

  10. 运行脚本后,会显示一个窗口,可以通过点击按钮执行相应的功能。

注意事项

  • 确保在known_faces目录下有已知的人脸图像。
  • 根据需要调整路径和文件名。
  • 可以进一步扩展管理功能,例如删除人脸、更新人脸等。
  • 希望这能帮助你构建一个人脸识别与管理系统!

    ,我们可以构建一个基于Python的人脸识别与管理系统。这个系统将包括以下几个主要功能:

    1. 选择人脸照片识别
    2. 选择人脸视频识别
    3. 摄像头检测人脸识别
    4. 录入人脸功能
    5. 管理人脸功能

    我们将使用face_recognition库进行人脸识别,并使用PyQt5来构建图形用户界面(GUI)。以下是完整的代码实现。

    安装依赖

    首先,确保安装了必要的Python包:

    pip install opencv-python face-recognition numpy pandas PyQt5
    

    代码实现

    1. 初始化和辅助函数
    import cv2
    import face_recognition
    import os
    import numpy as np
    import pandas as pd
    from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
    from PyQt5.QtGui import QImage, QPixmap
    from PyQt5.QtCore import QTimer
    from FaceRecognition_Ui import Ui_MainWindow
    
    class FaceRecognitionSystem(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super().__init__()
            self.setupUi(self)
            self.known_face_encodings = []
            self.known_face_names = []
            self.load_known_faces()
            self.init_ui()
    
        def init_ui(self):
            self.pushButton_load.clicked.connect(self.load_image)
            self.pushButton_camera.clicked.connect(self.start_camera)
            self.pushButton_add.clicked.connect(self.add_face)
            self.pushButton_manage.clicked.connect(self.manage_faces)
    
        def load_known_faces(self):
            for filename in os.listdir('known_faces'):
                if filename.endswith('.jpg') or filename.endswith('.png'):
                    image = face_recognition.load_image_file(f'known_faces/{filename}')
                    encoding = face_recognition.face_encodings(image)[0]
                    self.known_face_encodings.append(encoding)
                    self.known_face_names.append(filename.split('.')[0])
    
        def load_image(self):
            options = QFileDialog.Options()
            file_name, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png)", options=options)
            if file_name:
                self.recognize_from_image(file_name)
    
        def recognize_from_image(self, image_path):
            image = face_recognition.load_image_file(image_path)
            face_locations = face_recognition.face_locations(image)
            face_encodings = face_recognition.face_encodings(image, 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)
                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(image, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.putText(image, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
    
            qimage = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888).rgbSwapped()
            pixmap = QPixmap.fromImage(qimage)
            self.label.setPixmap(pixmap)
    
        def start_camera(self):
            self.cap = cv2.VideoCapture(0)
            self.timer = QTimer()
            self.timer.timeout.connect(self.update_frame)
            self.timer.start(10)
    
        def update_frame(self):
            ret, frame = self.cap.read()
            small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
            rgb_small_frame = small_frame[:, :, ::-1]
    
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_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)
                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]
    
                top *= 4
                right *= 4
                bottom *= 4
                left *= 4
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
    
            qimage = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888).rgbSwapped()
            pixmap = QPixmap.fromImage(qimage)
            self.label.setPixmap(pixmap)
    
        def add_face(self):
            options = QFileDialog.Options()
            file_name, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png)", options=options)
            if file_name:
                image = face_recognition.load_image_file(file_name)
                encoding = face_recognition.face_encodings(image)[0]
                self.known_face_encodings.append(encoding)
                name = os.path.basename(file_name).split('.')[0]
                self.known_face_names.append(name)
                cv2.imwrite(f'known_faces/{name}.jpg', image)
                QMessageBox.information(self, "Success", f"Face {name} added successfully!")
    
        def manage_faces(self):
            # Implement management functionality here
            pass
    
    if __name__ == "__main__":
        app = QApplication([])
        window = FaceRecognitionSystem()
        window.show()
        app.exec_()
    

    解释

    1. 初始化和辅助函数

    2. load_known_faces:加载已知的人脸图像并提取特征编码。
    3. recognize_from_image:从图片中识别已知人脸。
    4. start_cameraupdate_frame:从摄像头实时捕获帧并识别已知人脸。
    5. add_face:添加新的人脸到数据库。
    6. UI部分

    7. 使用PyQt5构建了一个简单的GUI,包括按钮和标签。
    8. 按钮分别用于加载图片、启动摄像头、添加新的人脸和管理人脸。
    9. 运行

    10. 运行脚本后,会显示一个窗口,可以通过点击按钮执行相应的功能。

    注意事项

  • 确保在known_faces目录下有已知的人脸图像。
  • 根据需要调整路径和文件名。
  • 可以进一步扩展管理功能,例如删除人脸、更新人脸等。

    这个项目使用了PyQt5来构建图形用户界面(GUI),并且集成了人脸识别功能。为了帮助你更好地理解代码结构和实现细节,我们可以基于截图中的目录结构和功能需求来编写相应的Python代码。
  • 目录结构

    根据截图中的目录结构,我们可以看到以下文件和目录:

  • FaceRecognition
  • data
  • images
  • test_img
  • platech.txt
  • FaceRecognition_Ui.py
  • FaceRecognition.py
  • runMain.py
  • 功能需求

    1. 选择人脸照片识别
    2. 选择人脸视频识别
    3. 摄像头检测人脸识别
    4. 录入人脸功能
    5. 管理人脸功能

    代码实现

    我们将分步骤实现这些功能,并确保代码结构清晰、易于维护。

    1. 初始化和辅助函数
    import cv2
    import face_recognition
    import os
    import numpy as np
    import pandas as pd
    from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
    from PyQt5.QtGui import QImage, QPixmap
    from PyQt5.QtCore import QTimer
    from FaceRecognition_Ui import Ui_MainWindow
    
    class FaceRecognitionSystem(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super().__init__()
            self.setupUi(self)
            self.known_face_encodings = []
            self.known_face_names = []
            self.load_known_faces()
            self.init_ui()
    
        def init_ui(self):
            self.pushButton_load.clicked.connect(self.load_image)
            self.pushButton_camera.clicked.connect(self.start_camera)
            self.pushButton_add.clicked.connect(self.add_face)
            self.pushButton_manage.clicked.connect(self.manage_faces)
    
        def load_known_faces(self):
            for filename in os.listdir('known_faces'):
                if filename.endswith('.jpg') or filename.endswith('.png'):
                    image = face_recognition.load_image_file(f'known_faces/{filename}')
                    encoding = face_recognition.face_encodings(image)[0]
                    self.known_face_encodings.append(encoding)
                    self.known_face_names.append(filename.split('.')[0])
    
        def load_image(self):
            options = QFileDialog.Options()
            file_name, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png)", options=options)
            if file_name:
                self.recognize_from_image(file_name)
    
        def recognize_from_image(self, image_path):
            image = face_recognition.load_image_file(image_path)
            face_locations = face_recognition.face_locations(image)
            face_encodings = face_recognition.face_encodings(image, 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)
                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(image, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.putText(image, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
    
            qimage = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888).rgbSwapped()
            pixmap = QPixmap.fromImage(qimage)
            self.label.setPixmap(pixmap)
    
        def start_camera(self):
            self.cap = cv2.VideoCapture(0)
            self.timer = QTimer()
            self.timer.timeout.connect(self.update_frame)
            self.timer.start(10)
    
        def update_frame(self):
            ret, frame = self.cap.read()
            small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
            rgb_small_frame = small_frame[:, :, ::-1]
    
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_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)
                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]
    
                top *= 4
                right *= 4
                bottom *= 4
                left *= 4
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
    
            qimage = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888).rgbSwapped()
            pixmap = QPixmap.fromImage(qimage)
            self.label.setPixmap(pixmap)
    
        def add_face(self):
            options = QFileDialog.Options()
            file_name, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png)", options=options)
            if file_name:
                image = face_recognition.load_image_file(file_name)
                encoding = face_recognition.face_encodings(image)[0]
                self.known_face_encodings.append(encoding)
                name = os.path.basename(file_name).split('.')[0]
                self.known_face_names.append(name)
                cv2.imwrite(f'known_faces/{name}.jpg', image)
                QMessageBox.information(self, "Success", f"Face {name} added successfully!")
    
        def manage_faces(self):
            # Implement management functionality here
            pass
    
    if __name__ == "__main__":
        app = QApplication([])
        window = FaceRecognitionSystem()
        window.show()
        app.exec_()
    

    解释

    1. 初始化和辅助函数

    2. load_known_faces:加载已知的人脸图像并提取特征编码。
    3. recognize_from_image:从图片中识别已知人脸。
    4. start_cameraupdate_frame:从摄像头实时捕获帧并识别已知人脸。
    5. add_face:添加新的人脸到数据库。
    6. UI部分

    7. 使用PyQt5构建了一个简单的GUI,包括按钮和标签。
    8. 按钮分别用于加载图片、启动摄像头、添加新的人脸和管理人脸。
    9. 运行

    10. 运行脚本后,会显示一个窗口,可以通过点击按钮执行相应的功能。

    注意事项

  • 确保在known_faces目录下有已知的人脸图像。
  • 根据需要调整路径和文件名。
  • 可以进一步扩展管理功能,例如删除人脸、更新人脸等。
  • 希望这能帮助你构建一个人脸识别与管理系统!

    作者:资深码侬

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python深度学习实现人脸识别与管理系统详解

    发表回复