人脸识别python
时间: 2023-06-22 08:23:27 浏览: 81
在Python中,可以使用多种开源的人脸识别库来实现人脸识别,其中比较常用的有OpenCV和Dlib等。
使用OpenCV进行人脸识别的步骤如下:
1. 安装OpenCV库
```
pip install opencv-python
```
2. 加载人脸检测器和人脸识别器模型
```
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer.yml')
```
3. 打开摄像头,读取视频流
```
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
4. 进行人脸检测
```
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
```
5. 对每张检测到的人脸进行识别
```
for (x,y,w,h) in faces:
roi_gray = gray[y:y+h, x:x+w]
id_, conf = recognizer.predict(roi_gray)
if conf>=45 and conf<=85:
# 在图像中绘制人脸和对应的识别结果
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(img, labels[id_], (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2, cv2.LINE_AA)
```
完整代码示例:
```
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer.yml')
labels = {"person_name": 1}
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
for (x,y,w,h) in faces:
roi_gray = gray[y:y+h, x:x+w]
id_, conf = recognizer.predict(roi_gray)
if conf>=45 and conf<=85:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(img, labels[id_], (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2, cv2.LINE_AA)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
```
阅读全文