简介:opencv的人脸检测的xml文件,这些文件可用于检测静止图像,视频和摄像头所得到图像中的人脸。业余AI相关学习人员,错误的地方请指正,轻喷。
案例的前提:Python环境、Opencv库,笔记本摄像头
实现步骤:
1、调用开启摄像头,进行人脸录入。(单人场景可以考虑通过sanic编写一个接口实现远程访问进行截图保存) 2、对采集的人脸进行数据训练。 3、调用数据训练的模型算法结果,开启摄像头,编写识别逻辑。
案例源码:
input_face.py
import cv2.cv2 as cv2
cap = cv2.VideoCapture(0)
num = 1
name = "tom"
while True:
ret_flag, v_show = cap.read()
cv2.imshow("Capture", v_show)
k = cv2.waitKey(1)
if k == ord("s"):
face_num = str(num) + "." + name
cv2.imwrite(fr"D:\xxxxx\person_face\{face_num}.jpg", v_show)
print("成功保存", str(num) + ".jpg")
print("*" * 80)
num += 1
elif k == ord(" "):
break
cap.release()
cv2.destroyAllWindows()
单人sanic远程截图:参考sanic:通过API接口进行电脑截图或录像
data_training.py
import os
import cv2.cv2 as cv2
import numpy as np
from PIL import Image
def get_img_labels(path):
faces_samples = []
ids = []
img_paths = [os.path.join(path, f) for f in os.listdir(path)]
face_detector = cv2.CascadeClassifier(
r"D:\xxxxxx\venv\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml")
for img_path in img_paths:
pil_img = Image.open(img_path).convert("L")
img_numpy = np.array(pil_img, "uint8")
faces = face_detector.detectMultiScale(img_numpy)
id = int(os.path.split(img_path)[1].split(".")[0])
for x, y, w, h in faces:
ids.append(id)
faces_samples.append(img_numpy[y:y + h, x:x + w])
print(f"id:{id}")
print(f"faces_samples:{faces_samples}")
return faces_samples, ids
if __name__ == '__main__':
path = r"D:\codes\ai2022\person_face"
faces, ids = get_img_labels(path)
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces, np.array(ids))
recognizer.write("TrainingDataSet.yml")
main.py
import cv2.cv2 as cv2
import os
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('TrainingDataSet.yml')
names = []
def face_detect_demo(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_detector = cv2.CascadeClassifier(
r'D:\xxxxx\venv\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
face = face_detector.detectMultiScale(gray, 1.1, 3, cv2.CASCADE_SCALE_IMAGE, (50, 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)
print(f"names:{names}")
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
print(f"confidence:{confidence}")
if confidence > 70:
cv2.putText(img, 'unKnow', (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)
def name():
path = r'D:\xxxxx\person_face'
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:
flag, frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if ord(' ') == cv2.waitKey(10):
break
cv2.destroyAllWindows()
cap.release()
print(names)
人脸录入保存的结果:保存的图像特征labels越多,执行的时间就越长,效果越好。一般建议多角度,多条件录入,例如侧脸,正脸,远近高低,光照,衣服颜色,背景,角度,俯视平视仰视。
最终运行效果:
截取1
截取2
针对识别视频类型的类例的执行效果:
微信公众号:玩转测试开发 欢迎关注,共同进步,谢谢!
|