首页 > 解决方案 > 无法通过 OpenCV python 打开 Mac 网络摄像头

问题描述

我是 opencv 的新手,并试图通过 OpenCV python 访问我的 Macbook 的内置摄像头,但它给出了一个错误。

import cv2

frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)

while True:
   success, img = cap.read()
   cv2.imshow("Result", img)
   if cv2.waitKey(1) & 0xFF == ord('q'):
       break

Traceback (most recent call last):
  File "/Users/hasanaktas/PycharmProjects/OpencvPython/project3.py", line 12, in <module>
    cv2.imshow("Result", img)
cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

已经尝试将 VideoCapture(0) 更改为 VideoCapture(1) 并添加以下代码,但仍然没有帮助。顺便说一句,使用 PyCharm

cap.release()
cv2.destroyAllWindows()

标签: pythonopencvcomputer-visionpycharmopencv-python

解决方案


我想提两个建议。

#1:使您的终端或 PyCharm 能够访问相机。


  • 转到System Preferences-> Security and Privacy->Camera并将 PyCharm 添加到列表中。

    • 在此处输入图像描述

#2而不是while Trueuse while cap.isOpened(),因此您可以知道PyCharmterminal可以访问您的相机。

  • import cv2
    
    frameWidth = 640
    frameHeight = 480
    cap = cv2.VideoCapture(0)
    cap.set(3, frameWidth)
    cap.set(4, frameHeight)
    cap.set(10,150)
    
    while cap.isOpened():
        success, img = cap.read()
        if success:
            cv2.imshow("Result", img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    

推荐阅读