opencv调用摄像头
时间: 2023-09-19 19:10:19 浏览: 11
使用OpenCV调用摄像头需要以下步骤:
1. 导入OpenCV库
```python
import cv2
```
2. 创建VideoCapture对象并打开摄像头
```python
cap = cv2.VideoCapture(0) # 0表示打开默认摄像头,也可以使用视频文件路径
```
3. 循环读取每一帧图像
```python
while True:
ret, frame = cap.read() # ret表示是否成功读取,frame为读取到的帧图像
if ret:
# 在这里对图像进行处理
cv2.imshow('frame', frame) # 显示图像
if cv2.waitKey(1) & 0xFF == ord('q'): # 按q键退出
break
else:
break
```
4. 释放资源
```python
cap.release() # 释放摄像头
cv2.destroyAllWindows() # 关闭窗口
```
完整代码如下:
```python
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
```
相关推荐













