python视频抽帧保存为视频

视频抽帧保存为视频

"""
@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)
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值