在以前的文章中,咱們學習了使用數據集訓練出一個識別器。本文中,咱們將載入這個識別器,而後來看見怎麼識別人臉。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()
先這樣吧