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

基于OpenCV的人脸检测程序每帧弹出独立窗口,无法播放连续视频

问题:人脸检测程序每帧弹出独立窗口,无法显示连续视频

正在学习人脸检测课程,近期完成了摄像头功能的集成,但程序运行时每帧都会弹出独立窗口,无法将画面合成为连续视频。以下是我的代码:

# -*- coding: utf-8 -*-

import cv2
import face_recognition

webcam_video = cv2.VideoCapture(1)

all_face_locations = []

while True:
    ret,current_frame = webcam_video.read()
    current_frame_small = cv2.resize(current_frame, (0, 0),fx=0.25,fy=0.25)
    all_face_locations = face_recognition.face_locations(current_frame_small,model='hog')
    for index,current_face_location in enumerate(all_face_locations):
        top_pos,right_pos,bottom_pos,left_pos = current_face_location
        top_pos = top_pos * 4
        right_pos = right_pos * 4
        bottom_pos = bottom_pos * 4
        left_pos = left_pos * 4
        print('found face {} at top:{},right:{},bottom:{},left:{}'.format(index+1,top_pos,right_pos,bottom_pos,left_pos))
        cv2.rectangle(current_frame,(left_pos,top_pos),(right_pos,bottom_pos),(0,255,0),2)
    cv2.imshow("Test",current_frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
        
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

webcam_video.release()
cv2.destroyAllWindows()

我认为问题出在cv2.waitKey(0)和cv2.destroyAllWindows()语句上,但删除这两句后程序又无法打开窗口,希望得到解决办法。


解决办法

你的判断完全正确,问题根源就是这两行代码:

  • cv2.waitKey(0):参数为0时会无限等待用户按键,每处理一帧就暂停,必须按任意键才会继续;
  • cv2.destroyAllWindows():在循环内调用会每帧关闭窗口,导致下一帧重新创建新窗口,这就是每帧弹出独立窗口的原因。

修改后的正确代码如下:

# -*- coding: utf-8 -*-

import cv2
import face_recognition

webcam_video = cv2.VideoCapture(1)

all_face_locations = []

while True:
    ret,current_frame = webcam_video.read()
    # 检查摄像头是否成功读取帧
    if not ret:
        break
    current_frame_small = cv2.resize(current_frame, (0, 0),fx=0.25,fy=0.25)
    all_face_locations = face_recognition.face_locations(current_frame_small,model='hog')
    for index,current_face_location in enumerate(all_face_locations):
        top_pos,right_pos,bottom_pos,left_pos = current_face_location
        top_pos = top_pos * 4
        right_pos = right_pos * 4
        bottom_pos = bottom_pos * 4
        left_pos = left_pos * 4
        print('found face {} at top:{},right:{},bottom:{},left:{}'.format(index+1,top_pos,right_pos,bottom_pos,left_pos))
        cv2.rectangle(current_frame,(left_pos,top_pos),(right_pos,bottom_pos),(0,255,0),2)
    cv2.imshow("Test",current_frame)
    # 等待1毫秒,同时监听q键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

webcam_video.release()
cv2.destroyAllWindows()

关键修改点:

  1. 删除循环内的cv2.waitKey(0)和cv2.destroyAllWindows();
  2. 将退出判断的cv2.waitKey(1)移到cv2.imshow之后,确保每帧显示后等待1毫秒,同时监听退出按键;
  3. 增加if not ret:判断,防止摄像头读取失败导致程序报错。

修改后,程序会持续显示摄像头的连续画面,检测到人脸时实时绘制框,按下q键即可正常退出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:25:31