介绍
本文附录了通过LBPH实现简单人脸识别的源代码,分类效果并不是很好,供个人学习使用。
人脸录入.py
import cv2
cap = cv2.VideoCapture(0)
flag = 1
num = 0
while (cap.isOpened()):
ret_flag, Vshow = cap.read()
cv2.imshow("Capture_Test", Vshow)
k = cv2.waitKey(1) & 0xFF
if k == ord('s'):
cv2.imwrite("F:/pythonProject/test/Lao_Wang/" + "0.WangZhenHui" + str(num) + ".jpg", Vshow)
# 路径需要自己修改 名称里的id和名字也要自己修改,每个人一个id和一个名字 num表示的每个id所对应的图片的数量
print("success to save" + str(num) + ".jgp")
print("----------------------------------")
num += 1
elif k == ord(' '):
break
cap.release()
cv2.destroyAllWindows()
训练数据.py
import os
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('D:/Python_venv/tf/Lib/site-packages/cv2/data'
'/haarcascade_frontalface_alt2.xml '
)
# 打印数组imagePaths
print('数据排列:', imagePaths)
# 遍历列表中的图片
for imagePath in imagePaths:
# 打开图片,黑白化
PIL_img = Image.open(imagePath).convert('L')
# 将图像转换为数组,以黑白深浅
img_numpy = np.array(PIL_img, 'uint8')
# 获取图片人脸特征
faces = face_detector.detectMultiScale(img_numpy)
# 获取每张图片的id和姓名
id = int(os.path.split(imagePath)[1].split('.')[0])
# 预防无面容照片
for x, y, w, h in faces:
ids.append(id)
facesSamples.append(img_numpy[y:y + h, x:x + w])
print('id:', id)
print('fs:', facesSamples)
return facesSamples, ids
if __name__ == '__main__':
# 图片路径
path = 'F:/pythonProject/test/Lao_Wang/'
# 获取图像数组和id标签数组和姓名
faces, ids = getImageAndLabels(path)
# 创建LBPH实例对象
recognizer = cv2.face.LBPHFaceRecognizer_create()
# 训练模型
recognizer.train(faces, np.array(ids))
# 保存数据
recognizer.write('trainer/trainer.yml')
人脸识别.py
import cv2
import numpy as np
import os
# coding=utf-8
import urllib
import urllib.request
import hashlib
# 加载训练数据集文件
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer.yml')
names = []
warningtime = 0
# 准备识别的图片
def face_detect_demo(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度
face_detector = cv2.CascadeClassifier('D:/Python_venv/tf/Lib/site-packages/cv2/data'
'/haarcascade_frontalface_alt2.xml ')
face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300)) # 人脸检测
for x, y, w, h in face:
cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
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])
print('标签id:',ids,'置信评分:', confidence) # 这里的置信评分其实可以理解为差异值,超过80就代表着差异值过大
if confidence > 80:
global warningtime
warningtime += 1
if warningtime > 100:
warningtime = 0
cv2.putText(img, 'unknown', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
else:
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)
# name函数读取特定路径下的名字
def name():
path = 'F:/pythonProject/test/Lao_Wang/'
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('1.mp4')
cap = cv2.VideoCapture(0)
name()
while True:
flag, frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if ord(' ') == cv2.waitKey(10):
break
cv2.destroyAllWindows()
cap.release()
# print(names)
标签:人脸识别,img,Python,LBPH,cv2,face,path,import,id
From: https://www.cnblogs.com/index-12/p/17280693.html