python - 为什么网络摄像头不出现在 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
解决方案
您应该首先列出可用的相机 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。因为它可能不起作用。如果结果没有列出可用端口,您可能需要外接摄像头。
推荐阅读
- performance - Can this function be refactored to be O(1)
- java - Java 避免使用过多的 if 语句或过多的验证器类
- c# - 在 Python 和 C# 之间发送数据的最佳解决方案是什么?
- excel - 等待 OPEN/SAVE/CANCEL 迷你窗口出现在 IE 浏览器中。FindWindowEx() 在 VBA 中循环浏览 IE 失败
- console - 停用 setinterval 功能?
- sql - 如何优化查询以计算与行相关的日期时间关系?
- node.js - 抽头测试超时
- c# - Winform 图表 - 固定 X 轴
- reactjs - 如何使用axios调用GET api在BODY中发送数据?
- python - 迭代for循环时如何将多个系列(熊猫)添加在一起?