You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python人脸识别项目:MongoDB插入时间显示异常的问题求助

人脸识别考勤系统MongoDB时间插入错误修复

问题现象

控制台可正确输出考勤时间(如{'13:10:34'}),但向MongoDB插入数据时,时间字段被插入<module 'time' (built-in)>,而非正确的时间值。

错误原因分析

  1. 变量命名冲突:代码中导入了标准库time,又用time作为存储时间的变量名,导致后续引用的是time模块而非存储时间的变量。
  2. 遍历逻辑错误:原循环仅保留最后一次迭代的name和time值,且str(List_Name.values())[i]的取值方式完全错误,无法正确获取每个用户的时间集合。
  3. 全局集合复用问题:所有用户的考勤时间都存入同一个全局timeset,会导致不同用户的时间互相覆盖。

修改后的完整代码

import face_recognition
import cv2
import numpy as np
from datetime import datetime
from datetime import date
from pymongo import MongoClient
import time 


video_capture = cv2.VideoCapture(0)


Siddharth_image = face_recognition.load_image_file("Siddharth.png")
Siddharth_face_encoding = face_recognition.face_encodings(Siddharth_image)[0]


known_face_encodings = [
    # 需补充其他人员的face_encoding定义,原代码缺失该部分
    Siddharth_face_encoding
]
known_face_names = [
    "Siddharth"
    # 对应上面的编码,补充其他人员姓名
]
List_Name={}
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
unknownCount = 0  # 移到循环外,避免每次重置计数

while True:
    ret, frame = video_capture.read()

    if process_this_frame:
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
        face_names = []
        
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding,tolerance=0.5)
            name = "Unknown"
                
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            
            if matches[best_match_index]:
                now = datetime.now()
                current_time = now.strftime("%H:%M:%S")
                name = known_face_names[best_match_index]
                if name not in List_Name.keys():
                    # 为每个用户创建独立的时间集合,避免全局复用
                    user_times = set()
                    user_times.add(current_time)
                    List_Name[name] = user_times
                else:
                    # 直接向该用户的集合添加时间
                    List_Name[name].add(current_time)
            else:
                unknownCount +=1
            face_names.append(name)
            
    process_this_frame = not process_this_frame


    for (top, right, bottom, left), name in zip(face_locations, face_names):
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()
myclient = MongoClient("mongodb://localhost:27017/")
mydb = myclient["OpenCV"]
mycol = mydb["OpenCVData"]

# 遍历每个用户,插入对应的考勤记录
for name, time_set in List_Name.items():
    # 将集合转为列表,适配MongoDB存储习惯
    time_list = list(time_set)
    x = mycol.insert_one({
        "name": name,
        "time": time_list,
        "date": str(date.today())  # 补充日期字段,便于后续查询
    })
    print(f"插入用户:{name},考勤时间:{time_list}")

today = date.today()
print(f"login details for date : {today}, Login is {List_Name}")
print(f"Known count is : {len(List_Name)}")
print(f"Unknown count is : {unknownCount}")
print(f"Total count is : {unknownCount + len(List_Name)}")

关键修改点说明

  1. 解决变量冲突:删除全局timeset,为每个用户创建独立的时间集合,避免与导入的time模块命名冲突。
  2. 修正遍历逻辑:使用for name, time_set in List_Name.items()直接遍历字典键值对,确保每个用户的记录都能正确插入MongoDB。
  3. 优化数据存储:将时间集合转为列表存入MongoDB,更符合MongoDB的数据存储习惯,便于后续查询统计。
  4. 修复未知计数:将unknownCount移到循环外,避免每次处理帧时重置计数,保证统计准确。

内容的提问来源于stack exchange,提问作者Pushpraj Singh Panwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:30:59