一、引言
OpenCV 是计算机视觉库,可以处理图像和视频!非常强大!
💡 先安装 opencv-python,导入用 import cv2
二、安装
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
三、摄像头预览
import cv2
# 打开摄像头,0 是默认摄像头
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("无法打开摄像头!")
exit()
while True:
# 读取一帧
ret, frame = cap.read()
if not ret:
print("无法接收帧!")
break
# 显示
cv2.imshow('Camera Preview', frame)
# 按 q 退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
四、简单图像操作
import cv2
# 读取图片
img = cv2.imread('test.jpg')
if img is None:
print("图片不存在!")
else:
# 转灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 显示
cv2.imshow('Color', img)
cv2.imshow('Gray', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 保存
cv2.imwrite('gray.jpg', gray)
总结
通过本章学习,你应该已经掌握了「使用 OpenCV 实现摄像头预览」的相关知识。
下一章是模块8的最后一篇!