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

cv2.imshow无法显示摄像头画面且不弹出窗口问题求助(macOS环境)

问题解决方法

这个问题是macOS Big Sur系统与旧版OpenCV的GUI接口兼容问题,以及代码窗口初始化逻辑缺失共同导致的,按以下步骤修复即可:

    1. 显式初始化GUI窗口
      在调用cv2.VideoCapture()之前添加窗口初始化代码,macOS下imshow方法需要预先创建窗口才能正常渲染:
cv2.namedWindow('Video', cv2.WINDOW_GUI_NORMAL)
    1. 修正摄像头检测逻辑
      原代码中摄像头未打开时的pass会导致逻辑继续向下执行读取空帧,改为continue跳过后续逻辑:
if not video_capture.isOpened():
    print('Unable to load camera.')
    sleep(5)
    continue # 替换原有的pass
    1. 删除重复的cv2.imshow调用
      原代码循环中两次调用imshow会导致窗口渲染队列异常,删除循环末尾重复的cv2.imshow('Video', frame)即可。
    1. 升级OpenCV版本
      OpenCV 4.2.0对Big Sur系统的GUI适配存在已知bug,执行以下命令升级到最新稳定版:
      pip install --upgrade opencv-python
    1. 检查系统权限
      打开系统偏好设置→安全与隐私→隐私→摄像头,确认你运行脚本的IDE/终端已经勾选摄像头访问权限。

修正后可运行的完整代码

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

# 预先初始化窗口,解决macOS下渲染异常问题
cv2.namedWindow('Video', cv2.WINDOW_GUI_NORMAL)

faceCascade = cv2.CascadeClassifier('/Users/***/Documents/GitHub/FaceAuth/haarcascade_frontalface_default.xml')
log.basicConfig(filename='webcam.log', level=log.INFO)

video_capture = cv2.VideoCapture(0)  # 0 for phone cam, 1 for pc cam
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        continue

    # Capture frame-by-frame
    ret, frame = video_capture.read()
    # 新增帧读取校验,避免读空帧崩溃
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(gray, 1.1, 4)

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: " + str(len(faces)) + " at " + str(dt.datetime.now()))

    # Display the resulting frame
    cv2.imshow('Video', frame)

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

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:15:04