溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

opencv實(shí)現(xiàn)簡單人臉識(shí)別

發(fā)布時(shí)間:2020-09-05 12:58:51 來源:腳本之家 閱讀:231 作者:Lin_QC 欄目:開發(fā)技術(shù)

對于opencv 它提供了許多已經(jīng)練習(xí)好的模型可供使用,我們需要通過他們來進(jìn)行人臉識(shí)別

參考了網(wǎng)上許多資料 

假設(shè)你已經(jīng)配好了開發(fā)環(huán)境 ,在我之前的博客中由開發(fā)環(huán)境的配置。

項(xiàng)目代碼結(jié)構(gòu):

opencv實(shí)現(xiàn)簡單人臉識(shí)別

dataSet : 存儲(chǔ)訓(xùn)練用的圖片,他由data_gen生成,當(dāng)然也可以修改代碼由其他方式生成

haarcascade_frontalface_alt.xml  、 haarcascade_frontalface_default.xml: 用于人臉檢測的haar分類器,網(wǎng)上普遍說第一個(gè)效果更好,第二個(gè)運(yùn)行速度更快

data_gen.py:生成我們所需的數(shù)據(jù)

trainer.py: 訓(xùn)練數(shù)據(jù)集

train.yml: 由train.py生成的人臉識(shí)別模型,供后面的人臉識(shí)別使用

recognize.py:視頻中的人臉識(shí)別

data_gen.py

連續(xù)拍20張照片當(dāng)作訓(xùn)練數(shù)據(jù),每個(gè)人建立一組數(shù)據(jù)

import cv2
 
detector = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
sampleNum = 0
Id = input('enter your id: ')
 
while True:
 ret, img = cap.read()
 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 faces = detector.detectMultiScale(gray, 1.3, 5)
 for (x, y, w, h) in faces:
 cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
 
 # incrementing sample number
 sampleNum = sampleNum + 1
 # saving the captured face in the dataset folder
 cv2.imwrite("dataSet/User." + str(Id) + '.' + str(sampleNum) + ".jpg", gray[y:y + h, x:x + w]) #
 
 cv2.imshow('frame', img)
 # wait for 100 miliseconds
 if cv2.waitKey(100) & 0xFF == ord('q'):
 break
 # break if the sample number is morethan 20
 elif sampleNum > 20:
 break
 
cap.release()
cv2.destroyAllWindows()

train.py

訓(xùn)練數(shù)據(jù)

import cv2
import os
import numpy as np
from PIL import Image
 
# recognizer = cv2.createLBPHFaceRecognizer()
detector = cv2.CascadeClassifier("/Users/qiuchenglin/PycharmProjects/face_recognize/haarcascade_frontalface_alt.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()
 
 
def get_images_and_labels(path):
 image_paths = [os.path.join(path, f) for f in os.listdir(path)]
 face_samples = []
 ids = []
 
 for image_path in image_paths:
 image = Image.open(image_path).convert('L')
 image_np = np.array(image, 'uint8')
 if os.path.split(image_path)[-1].split(".")[-1] != 'jpg':
  continue
 image_id = int(os.path.split(image_path)[-1].split(".")[1])
 faces = detector.detectMultiScale(image_np)
 for (x, y, w, h) in faces:
  face_samples.append(image_np[y:y + h, x:x + w])
  ids.append(image_id)
 
 return face_samples, ids
 
 
Faces, Ids = get_images_and_labels('dataSet')
recognizer.train(Faces, np.array(Ids))
recognizer.save('trainner.yml')

recognize.py

下面就是根據(jù)訓(xùn)練好的模型進(jìn)行人臉識(shí)別,根據(jù)之前生成數(shù)據(jù)的編號(hào),可以填入相對應(yīng)的人名,例如以下示例我訓(xùn)練了三組人的數(shù)據(jù)

import cv2
import numpy as np
 
recognizer = cv2.face.LBPHFaceRecognizer_create()
# recognizer = cv2.createLBPHFaceRecognizer() # in OpenCV 2
recognizer.read('/Users/qiuchenglin/PycharmProjects/face_recognize/trainner.yml')
# recognizer.load('trainner/trainner.yml') # in OpenCV 2
 
cascade_path = "/Users/qiuchenglin/PycharmProjects/face_recognize/haarcascade_frontalface_alt.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 = 'liuzb'
  elif img_id == 2:
  img_id = 'linqc'
  elif img_id == 3:
  img_id = 'keaibao'
 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), font, 1, (0, 255, 0), 1)
 cv2.imshow('im', im)
 if cv2.waitKey(10) & 0xFF == ord('q'):
 break
 
cam.release()
cv2.destroyAllWindows() 

簡單的一個(gè)人臉識(shí)別就完成了,只能說準(zhǔn)確率沒有非常高。

之后想辦法進(jìn)行提高。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI