软硬件环境
- macOS
- opencv 3.3.1
- anaconda3 & python 3.6.4
OpenCV简介
OpenCV
(Open Source Computer Vision Library)是开源的计算机视觉和机器学习库,提供了C/C++
、Python
等接口,并支持Windows
、Linux
、Mac
及Android
等平台。
OpenCV的安装
使用anaconda
来安装,anaconda
的基本使用可以参考我的另一篇博文 https://xugaoxiang.com/2019/12/08/anaconda/
conda install opencv
图片显示及保存
import cv2
image = cv2.imread('test.jpg', cv2.IMREAD_ANYCOLOR)
# 开窗口显示
cv2.imshow('show image', image)
# 保存成文件
cv2.imwrite('copy.jpg', image)
# 接收键盘输入,相当于是一个loop循环
cv2.waitKey(0)
# 删除创建的所有窗口,删除特定窗口cv2.destroyWindow(winname=**)
cv2.destroyAllWindows()
读取摄像头数据并实时显示
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
# 接收到q键,退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
IP Camera的RTSP视频播放
读取IP摄像头的数据跟读取本地摄像头类似
import cv2
cap = cv2.VideoCapture("rtsp://admin:123456@192.168.1.100:554/Streaming/Channels/101?transportmode=unicast")
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
# 接收到q键,退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
视频的存储
import cv2
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
# 设置编码类型XVID, 如果有其它的解码器,可以设置,如'X264'、'DIVX'等,各个平台支持的也不尽相同,此处以windows为例
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('test.avi', fourcc, 20.0, (640, 480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
frame = cv2.flip(frame, 0)
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()