用OpenCV-python写一段能实时检测人脸数据且能和mysql数据库进行比对且标注的代码
时间: 2024-05-24 08:12:45 浏览: 184
OpenCV和Python实现实时人脸检测
抱歉,因为我是AI语言模型,无法在本地运行代码,以下是一份伪代码,仅供参考:
import cv2
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
# 创建游标
mycursor = mydb.cursor()
# 加载人脸识别分类器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头
ret, frame = cap.read()
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 遍历每个人脸
for (x, y, w, h) in faces:
# 在人脸周围绘制矩形框
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
# 检查数据库中是否有匹配的人脸
sql = "SELECT name FROM people WHERE face_id = %s"
val = (str(x) + "," + str(y) + "," + str(w) + "," + str(h), )
mycursor.execute(sql, val)
result = mycursor.fetchone()
# 如果有匹配的人脸,标注姓名
if result is not None:
name = result[0]
cv2.putText(frame, name, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示图像
cv2.imshow('frame', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和窗口
cap.release()
cv2.destroyAllWindows()
阅读全文