• Python+OpenCV人脸识别,训练模型



    1.引入库

    代码如下(示例):

    import cv2 as cv
    import os
    import numpy as np
    from PIL import Image

    2.读入数据

    代码如下(示例):

    import cv2 as cv
    import os
    import numpy as np
    from PIL import Image
    
    def train_img(path):
        #调用训练集
        face = cv.CascadeClassifier('haarcascade_frontalface_alt2.xml')
        #图片集
        picture = []
        #标签集
        ids = []
        #图片集合
        Imagepaths = [os.path.join(path, f) for f in os.listdir(path)]
        #循环每一张图片
        for Imagepath in Imagepaths:
            #提取这张图片的id号
            id = int(os.path.split(Imagepath)[1].split('.')[0])
            #将图片转灰
            PIL_img = Image.open(Imagepath).convert('L')
            #将图片转化为uint8
            img_numpy = np.array(PIL_img, 'uint8')
            #提取人脸
            faces = face.detectMultiScale(img_numpy)
    
            for x, y, w, h in faces:
                picture.append(img_numpy[y:y+h, x:x+w])
                ids.append(id)
        return picture, ids
    
    path = 'D://ll//'
    faces, ids = train_img(path)
    recognizer = cv.face.LBPHFaceRecognizer_create()
    recognizer.train(faces, np.array(ids))
    recognizer.write('d:\\train.xml')
    

    3.识别图片

    import cv2 as cv
    recognizer = cv.face.LBPHFaceRecognizer_create()
    recognizer.read('d:\\train.xml')
    def compare_img(img):
        face = cv.CascadeClassifier('haarcascade_frontalface_alt2.xml')
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        faces = face.detectMultiScale(gray)
        for x, y, w, h in faces:
            cv.rectangle(img,(x, y), (x+w, y+h), (0,255,0),2)
            id, picture = recognizer.predict(gray[y:y+h, x:x+w])
            print('图片-->',id,'相似度评分:',picture)
    
        cv.imshow('out', img)
    img = cv.imread('D:\\33.jpg')
    compare_img(img)
    cv.waitKey(0)
    cv.destroyAllWindows()

    总结

    大功告成

  • 相关阅读:
    基于 outline 实现头像剪裁以及预览
    提问:为什么整数乘于0.01小数会变成很多小数?java+js
    ASP.NET Core - 缓存之分布式缓存
    链表-哈希表 详解
    MySQL 流程控制 的详细讲解
    系列三、双亲委派机制
    Flutter入门-Dart端和Native端的页面跳转
    低代码平台的分类及选择参考
    52. N皇后 II(难度:困难)
    一种加权变异的粒子群算法-附代码
  • 原文地址:https://blog.csdn.net/airyearth/article/details/126409582