人脸识别

训练数据:

import os
import cv2
import numpy as np
import sys
from PIL import Image
def getImageAndLabels(path):
    facesSamples=[]
    ids = []
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
    
    #检测人脸
    face_detector = cv2.CascadeClassifier('E:/opencv_package/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
  
    #遍历列表中的图片
    for imagePath in imagePaths:
        #打开图片
        PIL_img = Image.open(imagePath).convert('L')
        #将图像转换为数组
        img_numpy = np.array(PIL_img,'uint8')
        faces = face_detector.detectMultiScale(img_numpy)
        #获取每张图片的id
        id = int(os.path.split(imagePath)[1].split('.')[0])
        for x,y,w,h in faces:
            facesSamples.append(img_numpy[y:y+h,x:x+w])
            ids.append(id)
        
       
    return facesSamples,ids
if __name__ == '__main__':
    #图片路径
    path = './data/jm/'
    #获取图像数组和ID标签数组
    faces,ids=getImageAndLabels(path)
    #获取训练对象
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.train(faces,np.array(ids))
    
    #保存文件
    recognizer.write('trainer/trainer.yml')

实现人脸检测:

import cv2
import numpy as np
import os
#加载训练数据集文件
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
#准备识别的图片
img = cv2.imread('7.pgm')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_detector = cv2.CascadeClassifier('E:/opencv_package/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
faces = face_detector.detectMultiScale(gray)
for x,y,w,h in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
    #人脸识别
    id,confidence = recognizer.predict(gray[y:y+h,x:x+w])
    print('标签id:',id,'置信评分:',confidence)
cv2.imshow('dst',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

最后结果:
人脸识别_第1张图片

你可能感兴趣的:(Python,机器学习)