cv2.VideoCapture按照名称选择摄像头
时间: 2024-03-21 20:43:40 浏览: 15
你可以按照名称选择摄像头,使用方法是在调用`cv2.VideoCapture()`函数时,将摄像头的名称或者索引作为参数传入即可。下面是一个示例代码,假设你要选择名称为"Logitech HD Webcam C270"的摄像头:
```python
import cv2
cap = cv2.VideoCapture(0) # 选择索引为0的摄像头
if not cap.isOpened():
cap = cv2.VideoCapture("Logitech HD Webcam C270") # 如果打开失败,则尝试选择名称为"Logitech HD Webcam C270"的摄像头
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, frame = cap.read()
if not ret:
break
cv2.imshow("frame", frame)
if cv2.waitKey(1) == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
```
在代码中,我们首先尝试打开索引为0的摄像头,如果打开失败,则尝试选择名称为"Logitech HD Webcam C270"的摄像头。你可以根据实际情况修改代码中的摄像头名称或者索引。最后,我们使用`cv2.imshow`来显示图像,并使用`cv2.waitKey`等待按键事件。