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

按下q键无法关闭OpenCV摄像头窗口,需终止程序才能关闭的问题

问题解决:按Q键无法关闭OpenCV摄像头窗口

问题原因

你的代码仅监听了ESC键(ASCII码27)的按键事件,未加入Q键(ASCII码113)的判断逻辑,导致按下Q键无法触发摄像头窗口关闭流程,只能通过终止整个程序结束运行。

修复方案

修改循环内的按键判断逻辑,同时监听ESC键和Q键。注意先缓存cv2.waitKey(1)的返回值,避免多次调用导致按键事件丢失:

#### This function will run when we click on Take Attendance Button
@app.route('/start',methods=['GET'])
def start():
    if 'face_recognition_model.pkl' not in os.listdir('static'):
        return render_template('home.html',totalreg=totalreg(),datetoday2=datetoday2,mess='There is no trained model in the static folder. Please add a new face to continue.') 

    cap = cv2.VideoCapture(0)
    ret = True
    while ret:
        ret,frame = cap.read()
        if extract_faces(frame)!=():
            (x,y,w,h) = extract_faces(frame)[0]
            cv2.rectangle(frame,(x, y), (x+w, y+h), (255, 0, 20), 2)
            face = cv2.resize(frame[y:y+h,x:x+w], (50, 50))
            identified_person = identify_face(face.reshape(1,-1))[0]
            add_attendance(identified_person)
            cv2.putText(frame,f'{identified_person}',(30,30),cv2.FONT_HERSHEY_SIMPLEX,1,(255, 0, 20),2,cv2.LINE_AA)
        cv2.imshow('Attendance',frame)
        # 缓存按键值,同时监听ESC(27)和Q(113)键
        key = cv2.waitKey(1)
        if key == 27 or key == 113:
            break
    cap.release()
    cv2.destroyAllWindows()
    names,rolls,times,l = extract_attendance()    
    return render_template('home.html',names=names,rolls=rolls,times=times,l=l,totalreg=totalreg(),datetoday2=datetoday2) 

说明

修改后,程序会同时响应ESC键和Q键的按下操作,触发循环终止后,会执行cap.release()释放摄像头资源,再通过cv2.destroyAllWindows()关闭摄像头窗口,无需终止整个程序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:28:25