在以前的文章中,咱们学习了使用数据集训练出一个识别器。本文中,咱们将载入这个识别器,而后来看见怎么识别人脸。python
若是看过以前的文章,你就已经准备好了一个识别器,它就在trainner文件夹和trainner.yml文件里面。ide
如今,咱们将使用这个训练好的文件去识别人脸了。函数
import cv2 import numpy as np
接下来,咱们用OpenCV库以及咱们训练好的数据(yml文件)建立一个识别器对象:学习
recognizer = cv2.face.LBPHFaceRecognizer_create() # recognizer = cv2.createLBPHFaceRecognizer() # in OpenCV 2 recognizer.read('trainner/trainner.yml') # recognizer.load('trainner/trainner.yml') # in OpenCV 2
而后用以前准备好的xml建立一个分类器:测试
cascade_path = "haarcascade_frontalface_default.xml" face_cascade = cv2.CascadeClassifier(cascade_path)
获取到摄像头的控制对象:字体
cam = cv2.VideoCapture(0)
加载一个字体,用于在识别后,在图片上标注出识别对象的名字:spa
# font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) font = cv2.FONT_HERSHEY_SIMPLEX
在程序的主循环中,咱们须要作的是:code
while True: ret, im = cam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.2, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x - 50, y - 50), (x + w + 50, y + h + 50), (225, 0, 0), 2) img_id, conf = recognizer.predict(gray[y:y + h, x:x + w]) # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255) cv2.putText(im, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1) cv2.imshow('im', im) if cv2.waitKey(10) & 0xFF == ord('q'): break
recognizer.predict
为预测函数,putText
则是在图片上添加文字xml
因为可能识别不出来,或者存在未知的人脸。并且,若是只用id1,id2就会大大地下降了程序的体验。所以,咱们能够把id换成名字,把未知的脸标为未知。对象
咱们把程序改为:
img_id, conf = recognizer.predict(gray[y:y + h, x:x + w]) if conf > 50: if img_id == 1: img_id = 'jianyujianyu' elif img_id == 2: img_id = 'ghost' else: img_id = "Unknown" # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255) cv2.putText(im, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1)
记得释放资源
cam.release() cv2.destroyAllWindows()
而后在测试阶段,这我的工智障完美地识别不出我。
我以为是素材不够丰富,我回头改改。。。
如今的目录:
import cv2 import numpy as np recognizer = cv2.face.LBPHFaceRecognizer_create() # recognizer = cv2.createLBPHFaceRecognizer() # in OpenCV 2 recognizer.read('trainner/trainner.yml') # recognizer.load('trainner/trainner.yml') # in OpenCV 2 cascade_path = "haarcascade_frontalface_default.xml" face_cascade = cv2.CascadeClassifier(cascade_path) cam = cv2.VideoCapture(0) # font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) # in OpenCV 2 font = cv2.FONT_HERSHEY_SIMPLEX while True: ret, im = cam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.2, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x - 50, y - 50), (x + w + 50, y + h + 50), (225, 0, 0), 2) img_id, conf = recognizer.predict(gray[y:y + h, x:x + w]) if conf > 50: if img_id == 1: img_id = 'jianyujianyu' elif img_id == 2: img_id = 'ghost' else: img_id = "Unknown" # cv2.cv.PutText(cv2.cv.fromarray(im), str(Id), (x, y + h), font, 255) cv2.putText(im, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1) cv2.imshow('im', im) if cv2.waitKey(10) & 0xFF == ord('q'): break cam.release() cv2.destroyAllWindows()
先这样吧