• 人脸识别相关代码


    人脸识别相关代码

    这个是网上别人做的视频的学习地址:
    https://www.bilibili.com/video/BV1zc41197BA/?p=8&vd_source=e9167c654bb4523338a765358a8ac2af
    手敲了一遍:
    在这里插入图片描述

    总结

    我只能说自己训练的人脸效果实在是不好,还是没搞懂为啥别人的视频效果确实不错,或许是训练集问题

    人脸识别

    其中haarcascade_frontalface_default.xml,这个下载opencv以后就会有的文件,然后将其添加到项目中

    import cv2 as cv
    
    
    def detect():
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # 使用绝对路径加载级联分类器文件
        face_detector = cv.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
        faces = face_detector.detectMultiScale(gray)
    
        for (x, y, w, h) in faces:
            cv.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv.imshow('result', img)
        cv.waitKey(0)
    
    
    img = cv.imread('1.jpeg')
    if __name__ == '__main__':
        detect()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    检测视频中的人脸

    import cv2 as cv
    
    def detect(img):
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # 使用绝对路径加载级联分类器文件
        face_detector = cv.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
        faces = face_detector.detectMultiScale(gray)
    
        for (x, y, w, h) in faces:
            cv.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv.imshow('result', img)
        cv.waitKey(0)
    
    def main():
        cap = cv.VideoCapture('video.mp4')
        while True:
            flag, frame = cap.read()
            if not flag:
                break
            detect(frame)
            if ord('q') == cv.waitKey(10):
                break
        cv.destroyAllWindows()
        cap.release()
    if __name__ == '__main__':
        main()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    训练数据

    import os
    
    import cv2 as cv
    import numpy as np
    from PIL import Image
    
    
    def getImageAndLabels(path):
        # 使用绝对路径加载级联分类器文件
        face_detector = cv.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
        faceSamples = []
        ids = []
        imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
        for imagePaths in imagePaths:
            PIL_img = Image.open(imagePaths).convert('L')
            # 图像转为数组
            img_numpy = np.array(PIL_img, 'uint8')
            faces = face_detector.detectMultiScale(img_numpy)
            # 获取每张图像的id
            id = int(os.path.split(imagePaths)[1].split('.')[0])
            for x, y, w, h in faces:
                faceSamples.append(img_numpy[y:y + h, x:x + w])
                ids.append(id)
        return faceSamples, ids
    
    
    if __name__ == '__main__':
        path = './data/jm/'
        faces, ids = getImageAndLabels(path)
        recognizer = cv.face.LBPHFaceRecognizer_create()
        recognizer.train(faces, np.array(ids))
        # 保存文件
        recognizer.write('trainer.yml')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    置信区间

    import cv2 as cv
    
    def detect(img):
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # 使用绝对路径加载级联分类器文件
        face_detector = cv.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
        faces = face_detector.detectMultiScale(gray)
    
        recognizer = cv.face.LBPHFaceRecognizer_create()
        recognizer.read('trainer.yml')
    
        for (x, y, w, h) in faces:
            roi_gray = gray[y:y + h, x:x + w]
            label, confidence = recognizer.predict(roi_gray)
    
            # 打印预测标签和置信度
            print(f"Predicted Label: {label}, Confidence: {confidence}")
    
            # 绘制矩形框
            cv.rectangle(img, (x, y), (x + w, y + h), (100, 255, 0), 2)
    
            # 计算文本位置
            text_x = x + int(w / 2) - 50
            text_y = y - 20
    
            # 绘制标签和置信度信息
            label_text = f"Label: {label}, Confidence: {confidence:.2f}"
            cv.putText(img, label_text, (text_x, text_y), cv.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    
        cv.imshow('result', img)
        cv.waitKey(0)
        cv.destroyAllWindows()
    
    if __name__ == '__main__':
        path = './data/test/'
        detect(cv.imread(path + '9.jpg'))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
  • 相关阅读:
    SpringBoot-38-Dubbo概述
    我使用延迟队列实现商品的竞拍成交功能
    基础算法(排序、二分、精度运算)
    pytorch代码迁移到mindspore时,API的替换问题
    GBase8s数据库在组合查询中的集合运算符
    嵌入式软件架构设计-程序分层
    windows的批量解锁
    【Rust日报】2022-08-07 专注于开发人员生产力的 R3BL TUI 库和应用程序
    c# .NET 高级编程 高并发必备技巧(二) - 分布式锁
    相机内参数矩阵推导
  • 原文地址:https://blog.csdn.net/weixin_43914278/article/details/134511742