opencv的拍摄相片代码
时间: 2024-03-18 19:37:08 浏览: 24
当使用OpenCV进行拍摄相片时,你可以使用以下代码示例:
```python
import cv2
# 打开摄像头
cap = cv2.VideoCapture(0)
# 检查摄像头是否成功打开
if not cap.isOpened():
print("无法打开摄像头")
exit()
# 循环读取帧,直到按下 'q' 键停止
while True:
# 读取当前帧
ret, frame = cap.read()
# 检查帧是否成功读取
if not ret:
print("无法获取帧")
break
# 显示当前帧
cv2.imshow("Camera", frame)
# 按下 's' 键保存当前帧为图片
if cv2.waitKey(1) & 0xFF == ord('s'):
cv2.imwrite("photo.jpg", frame)
print("已保存照片")
break
# 按下 'q' 键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和关闭窗口
cap.release()
cv2.destroyAllWindows()
```
这段代码使用`cv2.VideoCapture()`函数打开摄像头,然后循环读取每一帧图像,并显示在窗口中。当按下's'键时,会将当前帧保存为名为"photo.jpg"的图片文件。按下'q'键时,循环会退出并关闭窗口。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)