首页 > 解决方案 > 为什么网络摄像头不出现在 python-opencv 中

问题描述

当我使用 macbook air 在 python 上运行我的 nooby opencv 程序时,它没有显示任何内容。程序也会在 0.5-1 秒后退出。

这是代码,它真的很简单

import cv2



cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)

while True:
     success, img = cap.read()
     cv2.imshow("Video", img)

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

标签: pythonopencv

解决方案


您应该首先列出可用的相机 ID

在这里您可以使用G M 的答案

def list_ports():
    is_working = True
    dev_port = 0
    working_ports = []
    available_ports = []
    while is_working:
        camera = cv2.VideoCapture(dev_port)
        if not camera.isOpened():
            is_working = False
            print("Port %s is not working." % dev_port)
        else:
            is_reading, img = camera.read()
            w = camera.get(3)
            h = camera.get(4)
            if is_reading:
                print("Port %s is working and reads images (%s x %s)" % (dev_port, h, w))
                working_ports.append(dev_port)
            else:
                print("Port %s for camera ( %s x %s) is present but does not reads." % (dev_port, h, w))
                available_ports.append(dev_port)
        dev_port += 1
    return available_ports, working_ports

结果将是:

Port 0 is working and reads images (720.0 x 1280.0)
OpenCV: out device of bound (0-0): 1
OpenCV: camera failed to properly initialize!
Port 1 is not working.

例如,对于我的 mac,camera id ( cid) 0 可用,但不可用 1。

cid因此我用0初始化了代码。

cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
while cap.isOpened():
    success, img = cap.read()

    if success:
        cv2.imshow("Video", img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

默认情况下,您不应该初始化VideoCapture对象 0。因为它可能不起作用。如果结果没有列出可用端口,您可能需要外接摄像头。


推荐阅读