如何使用 OpenCV 和 python 访问我的 USB 摄像头? [英] How do I access my USB camera using OpenCV with python?
问题描述
我在使用 OpenCV 和 python 访问我的 USB 摄像头时遇到问题.
I am having trouble accessing my USB camera using OpenCV with python.
我收到以下错误消息,我理解这意味着没有捕获帧?
I get the following error message which I understand means no frame was captured?
error: OpenCV(3.4.1) C:\Miniconda3\conda-bld\opencv-suite_1533128839831\work\modules\highgui\src\window.cpp:356: error: (-215) size.width>0 && size.height>0 in function cv::imshow
简单代码如下.有什么想法吗?一些帮助我会很感激
Simple code as below. Any thoughts? Some help I'll appreciate
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
推荐答案
camera index
大多数时候默认为 0
,但如果您插入的是 USB 摄像头,其camera index
可能是 1
或 2
,您可以同时尝试使用它们.
The camera index
most of the time is 0
as default with computers which come with an integrated camera, but if you're plugging a USB camera, its camera index
could be 1
or 2
, you can try with both of them.
但是如果你想获得所有camera index
可用,你可以使用以下简单的脚本来找出:
But if you wanna get all camera index
available, you can use the following simple script to find out:
import cv2
import numpy as np
all_camera_idx_available = []
for camera_idx in range(10):
cap = cv2.VideoCapture(camera_idx)
if cap.isOpened():
print(f'Camera index available: {camera_idx}')
all_camera_idx_available.append(camera_idx)
cap.release()
结果将是一个 list
,例如:[0,1,2,...]
,其中包含所有可用的相机索引.
The result would be a list
like: [0,1,2,...]
with all camera index available.
但如果您使用的是 USB 摄像头,则必须记住某些 OpenCV
功能将不起作用,请查看 这个.
But if you're using a USB camera you have to keep in mind that some OpenCV
functions won't work, take a look at this.
这篇关于如何使用 OpenCV 和 python 访问我的 USB 摄像头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!