python+opencv+haarcascade实现实时⼈脸识别
⼀:准备阶段
需要准备的库和python解释器
⼆:测试cv能否运⾏
# 导⼊cv
import cv2 as cv
# 读取图⽚,这⾥最好⽤⽂件的绝对路径,否则容易报错。注意⽤‘/’或者‘\\’代替‘\'
img = cv.imread('*:\\****\\****\\****\\****.jpg')
cv.imshow('read_img',img)
cv.waitKey(0)
cv.destroyAllWindos()
三:⼈脸识别的基本原理
调⽤“detectFaceInImage”函数。 指定OpenCV使⽤的⼈脸分类器(Face Classifier)。⽐如,OpenCV⾃带了⼀些⽤于正⾯脸的分类器,也有⼀些⽤于侧⾯脸的,还有眼睛检测,⿐检测,嘴检测,全⾝检测等等。你实际上可以任意把其它的分类检测器⽤于此函数,甚⾄创造你⾃⼰定制的分类检测器对于正
⾯⼈脸检测,选取这些OpenCV⾃带的haar级联分类器,在实现之前需要将⼈脸进⾏灰度转化 gary = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
“haarcascade_l”
“haarcascade_l”
“haarcascade_l”
“haarcascade_frontalface_l”
实现源码如下:
# 导⼊cv
import cv2 as cv
def face_detect_demo():
gary = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 这⾥插⼊haarcascade_l的绝对路径,你的opencv下载到哪就在哪
face_detect = cv.CascadeClassifier('C:/Users/Administrator/Downloads/opencv/sources/data/haarcascades/haarcascade_l')    face = face_detect.detectMultiScale(gary)
for x,y,w,h in face:
cv.imshow('result',img)
img = cv.imread('C:\\****\\******\\*****\\****.jpg')
face_detect_demo()
while True:
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindos()
四:调⽤摄像头实现实时⼈脸检测
我们只需要把上述代码稍加修改即可,调⽤摄像头、
# 导⼊cv
import cv2 as cv
def face_detect_demo(img):
gary = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('C:/Users/Administrator/Downloads/opencv/sources/data/haarcascades/haarcascade_l')    face = face_detect.detectMultiScale(gary)
for x,y,w,h in face:
cv.imshow('result',img)
#读取摄像头,0是默认的笔记本电脑摄像头
cap = cv.VideoCapture(0)
while True:
f,frame = ad()
if not f:
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(10):
break
五:采集⼈脸数据
import cv2
import sys
from PIL import Image
import numpy as np
def getImageAndLabels(path):
facesSamples=[]
ids=[]
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
face_detector = cv2.CascadeClassifier('C:/Users/Administrator/Downloads/opencv/sources/data/haarcascades/haarcascade_l')    print('矩阵:',imagePaths)
for imagePath in imagePaths:
PIL_img=Image.open(imagePath).convert('L')
# PIL_img = size(PIL_img, dsize=(600, 600))
img_numpy=np.array(PIL_img,'uint8')
faces = face_detector.detectMultiScale(img_numpy)
id = int(os.path.split(imagePath)[1].split('.')[0])
#print('fs:', facesSamples)
print('id:', id)
#print('fs:', facesSamples[id])
print('fs:', facesSamples)
#print('脸:',facesSamples[0])
#print('名字:',ids[0])
return facesSamples,ids
if __name__ == '__main__':
#图⽚路径,把需要计算的⼈脸照⽚放在⽂件夹内
path='G:/******/******/******'
faces,ids=getImageAndLabels(''G:/******/******/******'')
recognizer=cv2.face.LBPHFaceRecognizer_create()
#ain(faces,names)#np.array(ids)
recognizer.write('***.yml ')
# ⽣成的yml⽂件,下⼀步要⽤到
#save_to_file('',names)
六:实时⼈脸识别
这是本⽂的最后⼀个步骤,也就是实现实时⼈脸识别。
import numpy as np
import os
import urllib
quest
import hashlib
recogizer=cv2.face.LBPHFaceRecognizer_create()
names=[]
warningtime = 0
def md5(str):
import hashlib
m = hashlib.md5()
m.de("utf8"))
return m.hexdigest()
def face_detect_demo(img):
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_detector=cv2.CascadeClassifier('C:/Users/Administrator/Downloads/opencv/sources/data/haarcascades/haarcascade_l')    face=face_detector.detectMultiScale(gray,1.1,5,cv2.CASCADE_SCALE_IMAGE,(200,220),(400,400))
for x,y,w,h in face:
cv2.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
cv2.putText(img, 's', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
cv2.putText(img,str(names[ids-1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
cv2.imshow('result',img)
def name():
path = '*****************/'
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
for imagePath in imagePaths:
name = str(os.path.split(imagePath)[1].split('.',2)[1])
names.append(name)
cap=cv2.VideoCapture(0)
name()
while True:
f,ad()
if not f:
break
face_detect_demo(frame)
if ord(' ') == cv2.waitKey(1):
break
rectangle函数opencv
cv2.destroyAllWindows()
如有问题私信联系我

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。