视频抽帧保存为视频
"""
@Author:yebin
@file_name:视频扩充.py
@Time:2020/8/21 上午11:10
@function:
"""
import cv2
import os
import glob
def getPath(rootPath):
video_paths = glob.glob(rootPath + '/*.mp4')
return video_paths
def readVideo(video_path):
imgs = []
if not os.path.isfile(video_path):
return imgs
cap = cv2.VideoCapture(video_path)
fps = int(cap.get(cv2.CAP_PROP_FPS)) #获取帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frames_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) #得到视频的总帧数
frames = -1
while(cap.isOpened()):
ret, frame = cap.read() #其中ret是布尔值,如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False。frame就是每一帧的图像,是个三维矩阵。
frames += 1
if frames == frames_num:
break
imgs.append(frame.copy())
cap.release() #释放摄像头
cv2.destroyAllWindows() #关闭所有图像窗口
return imgs, fps
def saveVideo(video_path, imgs, fps, width=224, height=224):
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(video_path,fourcc, fps, (width,height))
for m in imgs:
m = cv2.resize(m, (width,height))
out.write(m)
out.release()
def expandVideo(video_path,save_path_root, scala=3): #scala是扩充的倍数,不能太大
saveVideoName = video_path.split('/')[-1] # *.mp4
imgs, fps = readVideo(video_path)
l = len(imgs)
startFrameId = 0
endFrameId = l-1
total_Imgs = []
tempImgs1 = []
tempImgs2 = []
tempImgs3 = []
tempImgs4 = []
for i in range(scala): #隔scala帧保存
s = i
while s<l:
if i == 0:
tempImgs1.append(imgs[s])
elif i == 1:
tempImgs2.append(imgs[s])
elif i == 2:
tempImgs3.append(imgs[s])
else:
tempImgs4.append(imgs[s])
s = s + scala
total_Imgs.append(tempImgs1)
total_Imgs.append(tempImgs2)
total_Imgs.append(tempImgs3)
# total_Imgs.append(tempImgs4)
for i in range(scala):
save_path = save_path_root + '/' + str(i) + '_' + saveVideoName
saveVideo(save_path, total_Imgs[i], fps)
if __name__ == "__main__":
rootPath = "/media/em/data_1/project/slowFastProject/data_src/test/1"
video_paths = getPath(rootPath)
save_path_root = "/media/em/data_1/project/slowFastProject/data_src/test/1e" # 待定
for video_path in video_paths:
expandVideo(video_path, save_path_root)