Python多摄像头实时人脸识别如何确定识别到人员的对应摄像头
人脸识别程序新增摄像头名称写入功能实现方案
前置操作:修改MySQL表结构
首先在你存储识别记录的表中新增camera_name字段,用于存储摄像头位置名称,参考SQL语句:
ALTER TABLE 你的识别记录表名 ADD COLUMN camera_name VARCHAR(50) NOT NULL COMMENT '摄像头对应位置名称';
实现步骤
1. 绑定摄像头与对应名称
为每个VideoCapture实例绑定自定义的摄像头名称,方便后续插入数据时直接引用,比如你现有代码里的本地默认摄像头和RTSP摄像头可以这样定义:
# 单摄像头场景配置 cap = cv2.VideoCapture(0) current_camera = "正门大堂摄像头" # 自定义当前摄像头的位置名称 # 如果你要启用第二个RTSP摄像头,按如下配置即可 # cap1 = cv2.VideoCapture('rtsp://admin:umerkhan261@192.168.226.201') # current_camera1 = "后门通道摄像头"
2. 调整识别逻辑,关联摄像头名称
在识别到人员、拼接插入数据时,把当前摄像头的名称加入待写入参数,修改后的代码参考如下(补全了数据库插入逻辑):
import cv2 import pickle import datetime import mysql.connector # 确保你已经安装mysql-connector-python库 # 初始化人脸识别模型 face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read("trainner.yml") # 加载人员标签 labels = {"person_name": 1} with open("labels.pickle", 'rb') as f: og_labels = pickle.load(f) labels = {v: k for k, v in og_labels.items()} # 初始化数据库连接 db_conn = mysql.connector.connect( host="你的数据库地址", user="你的数据库用户名", password="你的数据库密码", database="你的数据库名" ) cursor = db_conn.cursor() # 初始化摄像头+绑定名称 cap = cv2.VideoCapture(0) current_camera = "正门大堂摄像头" # 去重缓存:记录1分钟内已经插入过的(人员ID,摄像头)组合,避免重复写入 inserted_cache = set() last_clear_time = datetime.datetime.now() while True: # 每分钟清空一次去重缓存 if (datetime.datetime.now() - last_clear_time).seconds >= 60: inserted_cache.clear() last_clear_time = datetime.datetime.now() ret, frame = cap.read() if not ret: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) now = datetime.datetime.now() for (x, y, w, h) in faces: roi_gray = gray[y:y + h, x:x + w] id_, conf = recognizer.predict(roi_gray) if 45 <= conf <= 85: name = labels[id_] tString = now.strftime('%H:%M:%S') dtString = now.strftime('%Y-%m-%d') # 建议修改为标准日期格式,避免原%D:%m的格式歧义 # 生成唯一键去重 unique_key = (id_, current_camera) if unique_key not in inserted_cache: # 插入数据库,新增camera_name字段 insert_sql = "INSERT INTO 你的识别记录表名 (date, time, person_name, person_id, camera_name) VALUES (%s, %s, %s, %s, %s)" cursor.execute(insert_sql, (dtString, tString, name, id_, current_camera)) db_conn.commit() inserted_cache.add(unique_key)
3. 多摄像头场景适配
如果需要同时接入多个摄像头,可把摄像头实例和对应名称放在列表里循环处理即可,也可以开启多线程分别处理每个摄像头的流避免卡顿。
注意事项
- 建议把原代码里的日期格式
%D:%m替换为%Y-%m-%d这类标准格式,避免后续统计时出现格式歧义 - 加去重逻辑是为了避免同一个人在同一个摄像头下被连续识别时重复写入大量冗余数据,可根据自己的需求调整缓存清空的时间间隔
内容的提问来源于stack exchange,提问作者Umer Khan
相关产品推荐
相关产品推荐

