【问题标题】:Python OpenCv can open external webcam but can't show imagePython OpenCv 可以打开外部网络摄像头但无法显示图像
【发布时间】:2021-07-02 07:05:51
【问题描述】:

我正在尝试从 Mac 上的外部网络摄像头读取 VideoCapture 并拍摄图像,但我无法显示图像。这是我正在使用的:

  • Python:3.9.1
  • opencv-contrib-python: 4.5.1.48
  • MacOS Big Sur 11.2.3
  • 外置网络摄像头:罗技 C905

我正在从命令行运行脚本,我很确定我提供了所有需要的权限。在我朋友的使用 Linux 的笔记本电脑上一切正常。当我使用 FaceTime 或 Photo Booth 时,我能够看到网络摄像头图像。

代码如下:

class Camera:
    def __init__(self, camera_index: int):
        self._camera_index = camera_index
        self._capture = None
        self._open_capture()

    def take_world_image(self):
        return self._get_camera_frame()

    def _get_camera_frame(self):
        print(self._capture.read)
        opened_successfully, current_frame = self._capture.read()
        if not opened_successfully:
            raise InvalidCameraConfigException
        return current_frame

    def _open_capture(self):
        self._capture = cv2.VideoCapture(self._camera_index)
        
    def _close_capture(self):
        self._capture.release()


if __name__ == "__main__":
    camera = Camera(1)
    while True:
        image = camera.take_world_image()
        cv2.imshow("image", image)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    cv2.destroyAllWindows()

open_successfully 返回 True,但这是我得到的图像: image

感谢您的帮助!

【问题讨论】:

    标签: python macos opencv


    【解决方案1】:

    如果您的代码适用于主网络摄像头和 linux,则问题出在 Mac 权限上,而不是 python。

    尝试不要在 iDE 上运行脚本,而是在 Mac 上打开终端到包含 .py 文件的文件夹中并运行它。

    【讨论】:

    • 感谢您的回答,当我从终端或 Pycharm 运行代码时,我得到了相同的结果。在 System Preferences -> Security & Privacy -> Privacy -> Camera 中,Terminal 和 Pycharm 都有访问摄像头的权限。我正在尝试查看外部摄像头的权限是否不同,但我现在没有很多成功。如果可以的话,你知道怎么做吗?
    • 尝试 cv2.VideoCapture(self._camera_index) 与此值 cv2.VideoCapture(0) 或 cv2.VideoCapture(1) 或 cv2.VideoCapture(2) 并检查!
    • 嗨弗雷迪,谢谢你的建议。我试过了,内置摄像头可以正常工作,索引 2 超出范围(如预期)但我仍然遇到索引 1 相同的问题(外置摄像头)。
    • 尝试卸载相机驱动并重新安装。
    猜你喜欢
    • 2017-09-25
    • 2020-09-10
    • 2017-05-28
    • 2012-08-08
    • 2020-03-06
    • 2017-01-29
    • 2017-02-09
    • 2019-06-29
    • 2011-02-05
    相关资源
    最近更新 更多