训练模型
import cv2
import os
import numpy as np
from PIL import Image
FACEIDEN = "F:/Program Files/openCV/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml"
PATH = './trains/'
def get_image_path_id(path):
facesSample = []
ids = []
imagePath = [os.path.join(path, f) for f in os.listdir(path)]
faceDetector = cv2.CascadeClassifier(FACEIDEN)
for itemPath in imagePath:
PLI_img = Image.open(itemPath).convert('L')
ima_numpy = np.array(PLI_img)
faces = faceDetector.detectMultiScale(ima_numpy)
id = int(os.path.split(itemPath)[1].split('.')[0])
for x, y, w, h in faces:
facesSample.append(ima_numpy[y:y + h, x:x + w])
ids.append(id)
return facesSample, ids
if __name__ == '__main__':
path = PATH
faces, ids = get_image_path_id(path)
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces, np.array(ids))
recognizer.write("./yml/train.yml")
print("训练完成")
识别模型
import cv2
FACEIDEN = "" # 填写opencv的面部识别 yml文件
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('yml/train.yml')
img = cv2.imread('1.jpg') #20200721134535.jpg IMG_20200721_134537
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faceDetector = cv2.CascadeClassifier(FACEIDEN)
faces = faceDetector.detectMultiScale(gray)
for x, y, w, h in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
id, confidence = recogizer.predict(gray[y:y + h, x:x + w])
print(id, confidence, "评分")
resize = cv2.resize(img, (300, 400))
cv2.imshow('result', resize)
cv2.waitKey(0)
cv2.destroyAllWindows()
Comments | NOTHING