面部识别

 

面部识别

elder1先采集人脸数据


import cv2
import os 
import time
cap = cv2.VideoCapture(0)

time.sleep(1)
FaceDetector = cv2.CascadeClassifier(r'./haarcascade_frontalface_default.xml')

Faceid = input('\n input your id:')

count = 0
flag = True
while flag:
	flag ,img = cap.read()

	Gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	Faces = FaceDetector.detectMultiScale(Gray, 1.3 ,5)

	for (x,y,w,h) in Faces:
		cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),3)
		count+=1

		cv2.imwrite(r'.\Facedata\User.'+str(Faceid)+'.'+str(count)+'.jpg', Gray[y:y+h,x:x+w])

		cv2.imshow('233', img)
	k=cv2.waitKey(1)
	if(k==27):
		break
	elif count >= 1000:
		break

cap.release()
cv2.destroyAllWindows()
'''
这个程序大体就是在检测到了面部的时候,不停的拍下照片,编号并且保存到facedata这个文件夹里
'''

然后通过python-opencv自带的人脸识别进行分析

import numpy as np 
from PIL import Image
import os
import cv2

path = r'.\Facedata'

recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(r'.\haarcascade_frontalface_default.xml')

def GetImagesAndLabels(path):
	ImagePaths = [os.path.join(path,i) for i in os.listdir(path)]
	FaceSamples = []
	ids = []

	for imagePath in ImagePaths:
		PIL_img = Image.open(imagePath).convert('L')
		img_numpy = np.array(PIL_img,'uint8')
		id = int(os.path.split(imagePath)[-1].split('.')[1])
		Faces = detector.detectMultiScale(img_numpy)

		for (x,y,w,h) in Faces:
			FaceSamples.append(img_numpy[y:y+h,x:x+w])
			ids.append(id)
	
	return FaceSamples,ids
print('ok')
Faces, ids = GetImagesAndLabels(path)
recognizer.train(Faces,np.array(ids))

recognizer.write(r'.\trainer.yml')

print('{0} faces trained.'.format(len(np.unique(ids))))

首先,对脸的样本和id分析,读取,建立一个面部图像和人物id的样本和列表

然后利用recoginzer.train来训练,以及写出相关yml文件

import cv2

Recognizer = cv2.face.LBPHFaceRecognizer_create()
Recognizer.read(r'.\trainer.yml')
CascadePath = r'.\haarcascade_frontalface_default.xml'
FaceCasecade = cv2.CascadeClassifier(CascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX

idnum = 0

names = ['A','B']

cap = cv2.VideoCapture(0)
minW = 0.1*cap.get(3)
minH = 0.1*cap.get(4)

while True:
	ret , img = cap.read()
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	Faces = FaceCasecade.detectMultiScale(gray,1.2,5,minSize=(int(minW),int(minH)))

	for (x,y,w,h) in Faces:
		cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
		idnum, confidence = Recognizer.predict(gray[y:y+h,x:x+w])

		if confidence < 100:
			idnum = names[idnum]
			confidence = "{0}%".format(round(100-confidence))
		else:
			idnum = "unknown"
			confidence = "{0}%".format(round(100-confidence))
		cv2.putText(img, str(idnum),(x+5,y-5),font,1,(0,0,255),2)
		cv2.putText(img, str(confidence),(x+5,y+h-5),font,1,(0,0,0),2)

	cv2.imshow('233',img)
	k = cv2.waitKey(10)
	if k==27:
		break

cap.release()
cv2.destroyAllWindows()

大致就是实现在人脸识别出的框旁边显示一个匹配率数值,以及是谁,不再赘述