1.读取视频
def readtest():
videoname = 'videoname.avi'
capture = cv2.VideoCapture(videoname )
if capture.isOpened():
while True:
ret,img=capture.read() # img 就是一帧图片
# 可以用 cv2.imshow() 查看这一帧,也可以逐帧保存
if not ret:break # 当获取完最后一帧就结束
else:
print('视频打开失败!')
2.保存视频
主要用这个类
cv2.VideoWriter(videooutpath,fourcc, 20.0, (1280,960),True)
videooutpath 输出文件名
fourcc = cv2.VideoWriter_fourcc(*‘XVID’) 是指定编码器
20.0 是帧率
(1280,960) 是视频尺寸
True 指的是彩色
编码器一般: “DIVX"、”MJPG"、“XVID”、“X264"
注意: 如果是MacBook打开看的话要用.mp4格式 这里就填 *'mp4v'
,不然只改文件后缀名为.mp4还是打不开
更多的参考:https://www.fourcc.org/codecs.php
def writetest():
videoname = 'videoname_out.avi'
fourcc = cv2.VideoWriter_fourcc(*'XVID')
writer = cv2.VideoWriter(videoname, fourcc, 1.0, (1280,960),True)
imgpaths = glob.glob('*.jpg')
for path in imgpaths:
print(path)
img = cv.imread(path)
writer.write(img) # 读取图片后一帧帧写入到视频中
writer.release()
3.逐帧处理
有了前两个基础就很简单了
def makevideo():
videoinpath = 'videoname.avi'
videooutpath = 'videoname_out.avi'
capture = cv2.VideoCapture(videoinpath )
fourcc = cv2.VideoWriter_fourcc(*'XVID')
writer = cv2.VideoWriter(videooutpath ,fourcc, 20.0, (1280,960), True)
if capture.isOpened():
while True:
ret,img_src=capture.read()
if not ret:break
img_out = op_one_img(img_src) # 自己写函数op_one_img()逐帧处理
writer.write(img_out)
else:
print('视频打开失败!')
writer.release()