OpenCV 读取视频
想捕获视频,首先创建 cv.VideoCapture() 对象
cv.VideoCapture() 参数决定了视频来源
- 0 一般是电脑自带的摄像头
- 1、2、3 电脑的外接摄像头
- 视频文件的路径
- rtsp源
笔记本电脑用自带的摄像头取视频
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0) # 打开自带相机
if not cap.isOpened(): # 判断相机是否打开
print("Cannot open camera")
exit()
while True:
# 逐帧捕获
ret, frame = cap.read() # 取视频帧
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
cv.imshow('frame', frame) # 显示结果帧e
if cv.waitKey(1) == ord('q'): # q退出程序
break
cap.release() # 完成所有操作后,释放捕获器
cv.destroyAllWindows()
对视频帧的操作
- cap.get(cv.CAP_PROP_FRAME_WIDTH) # 获取视频的宽度
- cap.get(cv.CAP_PROP_FRAME_HEIGHT) # 获取视频的高度
- cap.set(propId,value) # 设置视频的宽高 propId 为cv.CAP_PROP_FRAME_WIDTH或cv.CAP_PROP_FRAME_HEIGHT value 为设置的值int
默认分辨率为640x480
播放文件视频
import numpy as np
import cv2 as cv
cap = cv.VideoCapture('Video_20211211152247.wmv')
while cap.isOpened():
ret, frame = cap.read()
# 如果正确读取帧,ret为True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
OpenCV 保存视频
-
在Fedora中:DIVX,XVID,MJPG,X264,WMV1,WMV2。(最好使用XVID。MJPG会生成大尺寸的视频。X264会生成非常小的尺寸的视频)
-
在Windows中:DIVX(尚待测试和添加)
-
在OSX中:MJPG(.mp4),DIVX(.avi),X264(.mkv)
-
cv.VideoWriter_fourcc(‘M’,‘J’,‘P’,‘G’)或 cv.VideoWriter_fourcc(*‘MJPG’) # 定义编码器
-
cv.VideoWriter(‘video.avi’, fourcc, 20.0, (640, 480)) # 创建写入视频对象
-
out.write(frame) # 写入视频帧
-
cv.flip(frame, 0) # 视频帧旋转
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# 定义编解码器并创建VideoWriter对象
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('video.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# frame = cv.flip(frame, 0)
# 写翻转的框架
out.write(frame)
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
# 完成工作后释放所有内容
cap.release()
out.release()
cv.destroyAllWindows()