- 我们在任意一个硬盘的根目录下创建一个Code-project文件夹

- 在该文件夹下分别创建C-project和Python-project文件夹

- 在Python-project文件夹下创建face recognition文件夹



- 在根目录下创建main.py,如果已经有了就无需创建




复制链接到仓库URL后点击应用:https://pypi.tuna.tsinghua.edu.cn/simple/

import os
import cv2 as cv
from PIL import Image
import numpy as np
import smtplib
from email.mime.text import MIMEText
def SlowSnail(s):
up = 0
low = 0
for c in s:
if c.isupper():
up += 1
elif c.islower():
low += 1
if up + low == len(s):
return 1
else:
return 0
def savePhoto():
cap = cv.VideoCapture(0)
num = 1
while (cap.isOpened()):
ret_flag, Vshow = cap.read()
cv.imshow('Capture_Test', Vshow)
k = cv.waitKey(1) & 0xFF
if k == ord(' '):
name = input("待识别人员姓名(英文或拼音):")
if SlowSnail(name) == 0:
continue
cv.imwrite('face_photo/' + str(num) + "." + name + ".jpg", Vshow)
print('success to save' + str(num) + '.jpg')
print('-------------------------------')
num += 1
elif k == ord('s'):
break
cv.destroyAllWindows()
cap.release()
def getImageAndLabels(path):
facesSamples = []
ids = []
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
face_detector = cv.CascadeClassifier(
'venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
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 = 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
def warning():
mail_host = 'smtp.qq.com'
mail_user = '2**********5'
mail_pass = 'i**********f'
sender = '2*********@qq.com'
receivers = ['26*********@qq.com']
message = MIMEText('有未知人员在镜头前', 'plain', 'utf-8')
message['Subject'] = 'warning!!!'
message['From'] = sender
message['To'] = receivers[0]
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(
sender, receivers, message.as_string())
smtpObj.quit()
print('The message was sent successfully\n')
def face_detect_demo(img):
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_detector = cv.CascadeClassifier(
'venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
face = face_detector.detectMultiScale(gray, 1.1, 5, cv.CASCADE_SCALE_IMAGE, (50, 50), (300, 300))
for x, y, w, h in face:
cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
print('标签id:', ids, '置信系数:', confidence)
if confidence > 80:
global warningtime
warningtime += 1
if warningtime > 100:
warning()
warningtime = 0
cv.putText(img, 'unkonw', (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
else:
cv.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (255, 0, 0), 1)
cv.imshow('result', img)
def name():
path = 'face_photo/'
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
for imagePath in imagePaths:
name1 = str(os.path.split(imagePath)[1].split('.', 2)[1])
names.append(name1)
savePhoto()
path = 'face_photo/'
face, ids = getImageAndLabels(path)
recognizer = cv.face.LBPHFaceRecognizer_create()
recognizer.train(face, np.array(ids))
recognizer.write('trainer.yml')
recogizer = cv.face.LBPHFaceRecognizer_create()
recogizer.read('trainer.yml')
names = []
warningtime = 0
cap = cv.VideoCapture(0)
name()
while True:
flag, frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if cv.waitKey(1) == 27:
break
cv.destroyAllWindows()
cap.release()
- 代码中的报警模块,此处用的是QQ邮箱,需要提前登录球球邮箱网页版点击设置-账户,滑到最下面开启SMTP,并且生成授权码

- 运行无错误后,1、空格拍照,2、输入英文名字或者拼音,3、 循环1和2直到按下s退出,4、按esc退出识别
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了