主要使用 haarcascade_frontalface_default.xml
摄像头录入人脸(可选)可以弄一个文件夹,里面放一堆图片
import cv2
face_name = 'xxxx'
face_cascade = cv2.CascadeClassifier("D:/BaiduNetdiskDownload/python/opencv/opencv-4.5.1/"
"data/haarcascades/haarcascade_frontalface_default.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()
camera = cv2.VideoCapture(0)
success, img = camera.read()
W_size = 0.1 * camera.get(3)
H_size = 0.1 * camera.get(4)
def get_face():
print("正在从摄像头录入新人脸信息 \n")
picture_num = 0
while True:
global success
global img
ret, frame = camera.read()
if ret is True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
break
face_detector = face_cascade
faces = face_detector.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + w), (255, 0, 0))
picture_num += 1
t = face_name
cv2.imwrite("./data/1." + str(t) + '.' + str(picture_num) + '.jpg', gray[y:y + h, x:x + w])
maximums_picture = 13
if picture_num > maximums_picture:
break
cv2.waitKey(1)
get_face()
用于训练的图片文件夹格式

用人脸开始训练
import os
import cv2
from PIL import Image
import numpy as np
def getImageAndLabel(path):
faceSamples = []
ids = []
dirs = os.listdir(path)
faceCascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_default.xml')
for dir in dirs:
dir_path = os.path.join(path, dir)
imagePaths = [os.path.join(dir_path, f) for f in os.listdir(dir_path)]
id = int(dir.split('.')[0])
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L')
img_numpy = np.array(PIL_img, 'uint8')
faces = faceCascade.detectMultiScale(img_numpy)
for (x, y, w, h) in faces:
faceSamples.append(img_numpy[y:y + h, x:x + w])
ids.append(id)
return faceSamples, ids
if __name__ == '__main__':
faces, ids = getImageAndLabel('./data/faces')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces, np.array(ids))
recognizer.save('./data/face_trainer.yml')
人脸识别
可以通过图片,视频,摄像头来进行人脸检测,识别成功后会返回id,根据id索引来对应人物名称
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import ffmpeg
import threading
import time
import subprocess
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('./data/face_trainer.yml')
names = ['未知', 'xxxx', '成龙', '胡歌', '刘亦菲']
warningtime = 0
font_path = './data/font/simfang.ttf'
def cv2ImgAddText(img, text, left, top, textColor=(0, 0, 255), textSize=20):
"""
文字转换为图片并添加到图片上
"""
if (isinstance(img, np.ndarray)):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontStyle = ImageFont.truetype(
font_path, textSize, encoding="utf-8")
draw.text((left, top), text, textColor, font=fontStyle)
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
def detect_face(src_img):
face_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_alt2.xml')
gray = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
for (x, y, w, h) in faces:
cv2.rectangle(src_img, (x, y), (x + w, y + h), (0, 0, 255), 2)
id, confidence = recognizer.predict(gray[y:y + h, x:x + w])
print(id)
if confidence < 70:
name = names[id]
confidence = "{0}%".format(round(100 - confidence))
else:
name = "unknown"
confidence = "{0}%".format(round(100 - confidence))
src_img = cv2ImgAddText(src_img, name, x + 5, y + 5, (255, 0, 0), 50)
print(name)
src_img = cv2ImgAddText(src_img, confidence, x + 5, y + h - 30, (255, 0, 0), 50)
if name == "unknown":
global warningtime
warningtime += 1
if warningtime > 3:
print("警报")
warningtime = 0
return src_img
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FPS, 30)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
while True:
ret, frame = cap.read()
if ret:
img = detect_face(frame)
cv2.imshow("img", img)
time.sleep(0.1)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~