1.识别图片中的人脸位置
tool_url = r'C:\Users\86188\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml'
def face_detect(img):
gray = cv.cvtColor(img,cv.COLOR_BGRA2BGR)
face = cv.CascadeClassifier(tool_url)
faces = face.detectMultiScale(gray)
for x,y,w,h in faces:
reg = cv.rectangle(img, (x, y),( x + w, y + h), color=(0, 255, 0), thickness=2)
cv.imshow("reg",reg)
2.根据训练集训练数据并保存(dataTraining.py)
import os
import cv2 as cv
import numpy
from PIL import Image
'''
训练数据来自s2和s9
'''
def getImageAndIds(path):
facesSimples = []
ids = []
img_paths = [os.path.join(path,f) for f in os.listdir(path)]
tool_url = r'C:\Users\86188\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml'
face = cv.CascadeClassifier(tool_url)
for i in img_paths:
img = Image.open(i).convert("L")
img_np = numpy.array(img,'uint8')
faces = face.detectMultiScale(img_np)
id = int(i.split(path)[1].split('.')[0])
for x, y, w, h in faces:
facesSimples.append(img_np[y:y+h,x:x+w])
ids.append(id)
return facesSimples,ids
if __name__ == "__main__":
path = "./data/"
faces,ids = getImageAndIds(path)
reg = cv.face.LBPHFaceRecognizer_create()
reg.train(faces,numpy.array(ids))
reg.write("trainer/trainer.yml")
3.人脸识别(faceChecking.py)
import cv2 as cv
import os,numpy
tool_url = r'C:\Users\86188\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml'
path = './data/'
face = cv.CascadeClassifier(tool_url)
reg = cv.face.LBPHFaceRecognizer_create()
reg.read("trainer/trainer.yml")
img= cv.imread("3.jpg")
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
faces = face.detectMultiScale(gray)
for x, y, w, h in faces:
cv.rectangle(gray, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
id,configence = reg.predict(gray[y:y+h,x:x+w])
print("编号:{},置信度:{}".format(id,configence))
aim_img = cv.imread(os.path.join(path,str(id)+'.jpg'))
cv.imshow("aim_img",aim_img)
cv.imshow("result",gray)
cv.waitKey(0)
cv.destroyAllWindows()