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()

总结

大功告成

你可能感兴趣的:(python,python,opencv,计算机视觉)