OpenCV內部自帶有三種人臉檢測方式:LBPH人臉識和其他兩種方法(Eigen人臉識別,FisherFace人臉識別)本次主要說明第一種方式LBPH檢測。
1.素材創(chuàng)建
1.創(chuàng)建需要訓練的圖片的集文件夾,和識別功能測試圖片集的文件夾。
圖(1)訓練圖集文件夾?
?圖(1.1)taylorswift照片(盡量選用背景沒其他人和尺寸小的照片,不然不好打開,也可以用resize函數進行縮?。?/p>
?圖(2)識別文件夾,一樣放入需要識別的照片
2.識別過程
1.使用Haar-cascade進行訓練,針對與Haar-cascade的識別原理,大家可以自行Google查詢,主要說明如何使用Haar-cascade進行訓練。首先創(chuàng)建haar_cascade實例,
haar_cascade = cv2.CascadeClassifier('haar_face.xml') # .xml文件可從opencv官網下載
2.導入文件內容(目標圖片和對應標簽)
def create_train():
# loop every folder
for person in people:
path = os.path.join(DIR, person)
label = people.index(person)
# loop every image in the folder
for img in os.listdir(path):
img_path = os.path.join(path, img)
# read the image from the path
img_array = cv2.imread(img_path)
gary = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
faces_rect = haar_cascade.detectMultiScale(gary, scaleFactor=1.1, minNeighbors=7)
for (x, y, w, h) in faces_rect:
faces_roi = gary[y:y + h, x:x + w]
features.append(faces_roi)
labels.append(label)
文件路徑名根據自己創(chuàng)建的文件所在路徑更改
3.用函數cv2.face.LBPHFaceRecognizer_ create ( ) 生成LBPH識別器實例模型
首先創(chuàng)建訓練實例對象
cv2.face.LBPHFaceRecognizer_ create ( radius,neighbors,grid_ x,grid_ y, threshold)四個參數均可選,通常默認不設置
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
4.訓練模型
face_recognizer.train(features,labels)
通常傳入兩個參數scr和label
scr:訓練圖像,用來識別的人臉圖像
label:人臉圖像對于的標簽,名字
5.通常需要將訓練好的模型進行保存
face_recognizer.save('face_trained.yml')
6.函數face_recognizer.predict( ) 對一個待測人臉圖像進行判斷,尋找與當前圖像距離最近的人臉圖像。與哪個人臉圖像最近,就將當前待測圖像標注為其對應的標簽。該函數有兩個返回值,label和confidence。
label:返回的識別結果標簽。
confidence:置信度,衡量識別結果與原有模型之間的距離。在LBPH識別方式中,0表示完全匹配。通常情況下,認為小于50的值是可以接受的,如果該值大于85則認為差別較大。
以下為代碼,分為訓練代碼和識別代碼兩個部分
訓練代碼
# face_train.py
# by liangyu 2020.7.19
# use opencv's built in face recognizer
import os
import cv2
import numpy as np
people = ['Avril Lavigne', 'Chris Martin', 'Emma Watson', 'Taylor Swift']
# p = []
# for i in os.listdir(r'E:\opencv_source'):
# p.append(i)
# print(p)
DIR = r'E:\opencv_source'
haar_cascade = cv2.CascadeClassifier('haar_face.xml') # .xml文件可從opencv官網下載
features = []
labels = []
def create_train():
# loop every folder
for person in people:
path = os.path.join(DIR, person)
label = people.index(person)
# loop every image in the folder
for img in os.listdir(path):
img_path = os.path.join(path, img)
# read the image from the path
img_array = cv2.imread(img_path)
gary = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
faces_rect = haar_cascade.detectMultiScale(gary, scaleFactor=1.1, minNeighbors=7)
for (x, y, w, h) in faces_rect:
faces_roi = gary[y:y + h, x:x + w]
features.append(faces_roi)
labels.append(label)
create_train()
# print(f'Length of the features = {len(features)}')
# print(f'Length of the features = {len(labels)}')
print('Training Done ------------------')
features = np.array(features,dtype='object')
labels = np.array(labels)
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
# Train the Recognizer on the features list and the labels list
face_recognizer.train(features,labels)
# Pass two parameters: 1.scr--->the target image 2.label---->the corresponding label of the image
face_recognizer.save('face_trained.yml')
np.save('features.npy',features)
np.save('labels.npy',labels)
識別代碼
# faces_recognition.py
import numpy as np
import cv2
haar_cascade = cv2.CascadeClassifier('haar_face.xml')
people = ['Avril Lavigne', 'Chris Martin', 'Emma Watson', 'Taylor Swift']
features = np.load('features.npy', allow_pickle=True)
labels = np.load('labels.npy', allow_pickle=True)
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.read('face_trained.yml')
img = cv2.imread(r'E:\image\verify\Chris Martin\cm3.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Person', gray)
# Detect the face in the image
face_rect = haar_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in face_rect:
face_roi = gray[y:y + h, x:x + w]
label, confidence = face_recognizer.predict(face_roi)
# Return two values: label and confidence
print(f'label = {people[label]} with a confidence of {confidence}')
# confidence :'0' indicates an exact match,value less than 50 is considered acceptable
# value greater than 85 means the difference is huge
cv2.putText(img, str(people[label]), (10, 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 255, 0), thickness=1)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)
cv2.imshow('Detected Face', img)
cv2.waitKey(0)
3.識別結果展示
?對Coldplay主唱 Chris Martin進行識別可以看到與其相匹配且置信度為0表示完全匹配。
對霉霉進行識別,結果識別出來為艾瑪沃特森??!置信度72表示和實際有較大的誤差
4.結束語:
對于opencv內部自帶的人臉檢測(LBPH人臉識別)和其他兩種方法(Eigen人臉識別,FisherFace人臉識別)方法大致相同,通常情況下這三種方法識別精度較低,且對噪聲較為敏感,識別效果并不是十分精準,和預期還是有一定出入的。其他兩種識別方法可參考這篇文章https://blog.csdn.net/weixin_43810267/article/details/106650055文章來源:http://www.zghlxwxcb.cn/news/detail-470824.html
Haar特征分類器介紹可以參考?(55條消息) opencv人臉檢測--detectMultiScale函數_walker lee的博客-CSDN博客_detectmultiscale文章來源地址http://www.zghlxwxcb.cn/news/detail-470824.html
到了這里,關于OpenCV人臉識別,訓練模型為cv2.face.LBPHFaceRecognizer_create()的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!