Python在人脸识别方面功能很强大,程序语言简单高效,下面小编来编程实现一下如何实现人脸识别。如有错点,还望斧正
识别图片中的人脸位置
#人脸识别分类器路径
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)
根据训练集训练数据并保存(dataTraining.py)
import os
import cv2 as cvimport numpyfrom 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:
# print(i)
img = Image.open(i).convert("L")
# Image._show(img) #将图片转换为数组 img_np = numpy.array(img,'uint8')
# print(img_np)
# 获取图像的人脸信息和对应id 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")
人脸识别(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:
# print(x,y,w,h)
cv.rectangle(gray, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
#检测出识别后的图片和id 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()