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

Python人脸识别系统实现数据已存在错误弹窗提示的方法问询

修改思路

你需要在插入数据、启动人脸拍摄之前,先校验待插入的数据是否已经在数据库中存在,如果存在就直接弹出错误提示,终止后续流程。具体修改如下:

  1. 替换原有的全表查询逻辑,改为按重复判断字段做条件查询,避免全表扫描性能损耗
  2. 新增重复判断分支,匹配到重复数据时弹出错误提示,直接终止后续操作

完整修改后代码

if (t1.get()==""  or t2.get()=="" or t3.get()=="" or t4.get()==""):
        messagebox.showinfo("Result","Please Complete the Provided Details!")
else:
    databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
    )
    cursors = databases.cursor()
    # 新增重复校验查询:这里以姓名+原始ID作为重复判断依据,可根据业务调整WHERE条件
    check_sql = "SELECT 1 FROM record WHERE names = %s AND ids = %s"
    check_params = (t1.get(), t4.get())
    cursors.execute(check_sql, check_params)
    exist_data = cursors.fetchone()

    # 校验到重复数据
    if exist_data:
        messagebox.showerror("错误", "数据已存在")
        cursors.close()
        databases.close()
        # 直接退出,不执行后续插入、拍摄逻辑
        return
    
    # 以下是原有正常流程的代码
    id = t4.get()
    id = int(id)+1
    sql = "INSERT INTO record(ids, names,course_year,positions) values(%s ,%s ,%s , %s)"
    val = (id, t1.get(), t2.get(), t3.get())
    cursors.execute(sql,val)
    databases.commit()

    # 后面是原有拍摄人脸的代码,无需修改
    face_classifier = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    def face_cropped(img):
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
        faces = face_classifier.detectMultiScale(gray, 1.3, 5)
        # scaling factor = 1.3
        # minimum neighbor = 5
        if faces is ():
            return None
        for (x,y,w,h) in faces:
                cropped_face = img[y:y+h, x:x+w]
        return cropped_face

    cap = cv2.VideoCapture(0)
    img_id = 0

    while True:
        ret, frame = cap.read()
        if face_cropped(frame) is not None:
            img_id+=1
            face = cv2.resize(face_cropped(frame), (200,200))
            face = cv2.cvtColor(face,cv2.COLOR_BGR2GRAY)
            file_name_path = "img/"+str (t1.get())+"." +str(id)+"."+str(img_id)+".jpg"
            cv2.imwrite(file_name_path, face)
            cv2.putText(face, str(img_id), (50,50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
            cv2.imshow("Cropped face", face)
        if cv2.waitKey(1)==1 or int(img_id)==50:
            break
    cap.release()
    cv2.destroyAllWindows()
    messagebox.showinfo("Result","Saved Completed!")

可选优化

  • 可以按需调整重复判断规则,比如只需要判断姓名重复,就把查询条件改成WHERE names = %s,参数只传t1.get()即可
  • 建议给数据库record表的重复校验字段加唯一索引,双重保障避免脏数据写入

内容的提问来源于stack exchange,提问作者So_LoW

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:06:05