1 在pychram中搭配好opencv环境
2 到opencv官网下载,因为需要用到其中E:\Edgedownload\opencv\sources\data\haarcascades路径的下训练好的分类器(注意路径要求全英文)
1 首先在项目所在文件夹下新建data文件,在data文件下新建jm文件夹用来放置训练所用图片,在data文件下新建trainer文件下,会保存训练得到的文件。
2 训练数据
import os
import cv2
import sys
from PIL import Image
import numpy as np
def getImageAndLabels(path):
#存储人脸数据
facesSamples=[]
#存储姓名数据
ids=[]
#储存图片信息
path_list = os.listdir(path)
path_list.sort(key=lambda x: int(x.split('.')[0]))
imagePaths=[os.path.join(path,f) for f in path_list]
#加载分类器
face_detector = cv2.CascadeClassifier('E:/Edgedownload/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
#打印数组imagePaths
print('数据排列:',imagePaths)
#遍历列表中的图片
for imagePath in imagePaths:
#打开图片,黑白化
PIL_img=Image.open(imagePath).convert('L')
#将图像转换为数组,以黑白深浅
# PIL_img = cv2.resize(PIL_img, dsize=(400, 400))
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:
ids.append(id)
facesSamples.append(img_numpy[y:y+h,x:x+w])
#打印脸部特征和id
print('fs:', facesSamples)
print('id:', id)
return facesSamples,ids
if __name__ == '__main__':
#图片路径
path='./data/jm/'
#获取图像数组和id标签数组和姓名
faces,ids=getImageAndLabels(path)
#获取训练对象
recognizer=cv2.face.LBPHFaceRecognizer_create()
#recognizer.train(faces,names)#np.array(ids)
recognizer.train(faces,np.array(ids))
#保存文件
recognizer.write('trainer/trainer.yml')
#save_to_file('names.txt',names)
#print(ids)
3 识别测试
import cv2
import numpy as np
import os
# coding=utf-8
import urllib
import urllib.request
import hashlib
#加载训练数据集文件
recogizer=cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer.yml')
names = []
#准备识别的图片
def face_detect_demo(img):
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#转换为灰度
face_detector=cv2.CascadeClassifier('E:/Edgedownload/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
face=face_detector.detectMultiScale(gray)
for x,y,w,h in face:
cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
# cv2.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
# 人脸识别
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
print('标签id:',ids,'置信评分:', confidence)
if confidence > 80:
cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
else:
cv2.putText(img,str(names[ids]), (x + 45, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
cv2.imshow('result',img)
#print('bug:',ids)
def name():
path = './data/jm/'
path_list = os.listdir(path)
path_list.sort(key=lambda x: int(x.split('.')[0]))
imagePaths=[os.path.join(path,f) for f in path_list]
for imagePath in imagePaths:
name = str(os.path.split(imagePath)[1].split('.',2)[1])
names.append(name)
print(names)
if __name__ == '__main__':
#输出训练样本图片的名称
name()
#打开电脑默认摄像头实时检测
#cap = cv2.VideoCapture(0)
# while True:
# flag,frame = cap.read()
# if not flag:
# break
# face_detect_demo(frame)
# if ord('q') == cv2.waitKey(1):
# break
#打开一张图片实现检测
cap = cv2.imread('test1.jpg')
face_detect_demo(cap)
while True:
if ord('q') == cv2.waitKey(0):
break
#释放内存
cv2.destroyAllWindows()
#释放摄像头
cap.release()
4 结果