import os
import dotenv
import etool
dotenv.load_dotenv()
import os
import cv2
import numpy as np
from PIL import Image
# 摄像头被分配到的设备ID,window通常为0,linux通常为1,AIBox通常为9~13
CID = "http://192.168.20.233:8080/video"
if os.path.exists("dataSet"):
os.makedirs("dataSet")
# 输入人脸,id为人脸对应的id,同个id的人脸会被识别为同一个人
def get_face(id="1"):
faceDetect = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
cam = cv2.VideoCapture(CID)
sampleNum = 0
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceDetect.detectMultiScale(gray, 1.3, 5)
for x, y, w, h in faces:
cv2.imwrite(
"dataSet/User." + str(id) + "." + str(sampleNum) + ".png",
gray[y : y + h, x : x + w],
)
sampleNum = sampleNum + 1
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.waitKey(100)
cv2.imshow("Face", img)
cv2.waitKey(1)
if sampleNum > 20:
break
cam.release()
cv2.destroyAllWindows()
# 训练数据
def trainer_face(path="dataSet"):
recognizer = cv2.face.LBPHFaceRecognizer_create()
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
faces = []
IDs = []
for imagePath in imagePaths:
faceImg = Image.open(imagePath).convert("L")
faceNp = np.array(faceImg, "uint8")
ID = int(os.path.split(imagePath)[-1].split(".")[1])
faces.append(faceNp)
IDs.append(ID)
cv2.imshow("training", faceNp)
cv2.waitKey(10)
recognizer.train(faces, np.array(IDs))
recognizer.save("trainningData.yml")
cv2.destroyAllWindows()
# 识别人脸
def recognizer(labels={"p1": 1, "p2": 2}):
# 加载人脸识别器
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# 加载已训练的人脸识别模型
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainningData.yml")
# 初始化摄像头
cap = cv2.VideoCapture(CID)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
)
rgb_color = (0, 0, 0)
for x, y, w, h in faces:
# 识别人脸
id, confidence = recognizer.predict(gray[y : y + h, x : x + w])
person = ""
if confidence < 100:
for name, label in labels.items():
if label == id:
person = name
break
confidence = int(100 - confidence)
if int(confidence) > 40:
rgb_color = (0, 255, 0) # 绿色
person = str(person) + str(confidence) + "%"
elif 0 < int(confidence) < 40:
rgb_color = (255, 0, 0) # 红色
person = "unkonw"
cv2.putText(
frame,
str(person),
(x, y + h),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 0, 255),
2,
) # 更新为cv2.putText()
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Face Recognition", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
get_face(id="1")
trainer_face(path="dataSet")
recognizer()
import time
time.sleep(0.5)
etool.ManagerEmail.send_email(
sender = "example@example.com", # 填你自己的邮箱
password = os.getenv("EMAIL_PASSWORD"), # env 填你自己的邮箱密码
message = "<h1>快来看,有人!</h1>",
recipient = "example@example.com", # 填你同桌的邮箱
subject = "有人来了",
image_path = "output/20250721_1.jpg",
)
最新发布