opencv学习笔记02-视频读取与写入
opencv 简易笔记 2
2.视频读取和截取
import cv2
# 窗口命名
cv2.namedWindow("video", cv2.WINDOW_NORMAL)
cv2.resizeWindow("video", 500, 500)
# 读取视频
video = cv2.VideoCapture("mdPNG/3-11 OpenCV中的TrackBar控件.mp4", cv2.CAP_FFMPEG)
# 循环读取视频,延时设置为100ms
videowriter = cv2.VideoWriter(
"mdPNG/3-11 OpenCV中的TrackBar控件_copy.mp4",
cv2.VideoWriter_fourcc(*"MJPG"),
30.0,
(1920, 1080),
isColor=False,
)
ret = True
while ret:
ret, frame = video.read()
cv2.imshow("video", frame)
videowriter.write(frame)
key = cv2.waitKey(1)
if key & 0xFF == ord("q"):
break
print(ret)
# 释放videoCapture
video.release()
videowriter.release()
cv2.destroyAllWindows()
2.1 VideoCapture(filename,api)
该方法能够读取到视频,api 无需特别指定,除非有特殊需求:
(1) filename: 文件名,0 为摄像头
(2) api: 通过 cv2.CAP 进行查看
2.2 read()->bool,mat
该方法能够读取视频帧,并有两个返回值,即状态值与当前帧
(1) bool: 状态值,正常状态为 True
(2) mat: 当前帧 mat
Tips: 当进行视频播放时,如果 waitKey 中值过小,导致视频播放速度异常,其实这是因为正常视频一般为每秒 20-25 帧左右,以 24 帧为例,正确的设置应当为 1000/24。关于如何查询原视频的帧数,可以通过 ffplay 来查看:
ffplay yourvideoname.mp4
![](https://img2023.cnblogs.com/blog/2549937/202306/2549937-20230601010226489-945867943.png)
2.2 release()->bool,mat
该方法能够释放 VideoCapture,无返回值
2.3 videoWriter(filename,fourcc,fps,framesize,iscolor)->videoWriter
该方法能够将数据写入视频,有多个参数,返回一个 videoWriter 对象,使用 write 写入 frame,最后需要释放资源。代码示例:
def create_video(filename, width, height, fps=30):
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
video = cv2.VideoWriter(filename, fourcc, float(fps), (width, height))
video = cv2.VideoWriter(filename, fourcc, float(fps), (width, height),True)
return video
(1) filename: 保存的文件名
(2) fourcc: 编码格式,int
(3) fps: 帧率,double
(4) framesize: 宽高,格式为 size
(5) iscolor: 是否为彩色,默认为 True,最好不要操作,容易出错