import os
import cv2
from PIL import Image
import numpy
as
np
def getImageAndLabels(path):
facesSamples = []
ids = []
imagePaths = [os.path.join(path, f)
for
f in os.listdir(path)]
# 检测人脸
# 加载特征数据
face_detector = cv2.CascadeClassifier(
'D:/Python/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml'
)
# 参数: scaleFactor(比例因子):图片缩放多少,minNeighbors:至少检测多少次,minSize maxSize:当前检测区域的最小面积
# scaleFactor=1.01, minNeighbors=3, maxSize=(33, 33), minSize=(28, 28)
# 遍历列表中的图片
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:
# 进行切片处理,获取图像数组和id
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'
)