欢迎光临散文网 会员登陆 & 注册

Python将视频分成帧,将图片帧合成视频

2021-06-19 00:44 作者:泉来啦  | 我要投稿

1.将视频切成图片


import os
import CV2

"""
功能:将视频转成图片(提取视频的每一帧图片)
     1.能够设置多少帧提取一帧图片
     2.可以设置输出图片的大小及灰度图
     3.手动设置输出图片的命名格式
"""
def ExtractVideoFrame(video_input,output_path):
    # 输出文件夹不存在,则创建输出文件夹
    if not os.path.exists(output_path):
        os.mkdir(output_path)

    times = 0               # 用来记录帧
    frame_frequency = 10    # 提取视频的频率,每frameFrequency帧提取一张图片,提取完整视频帧设置为1
    count = 0               # 计数用,分割的图片按照count来命名
    cap = CV2.VideoCapture(video_input)  # 读取视频文件

    print('开始提取', video_input, '视频的图片')
    while True:
        times += 1
        res, image = cap.read()          # 读出图片。res表示是否读取到图片,image表示读取到的每一帧图片
        if not res:
            print('图片提取结束')
            break
        if times % frame_frequency == 0:
            # picture_gray = CV2.cvtColor(image, CV2.COLOR_BGR2GRAY)  # 将图片转成灰度图
            # image_resize = CV2.resize(image, (368, 640))            # 修改图片的大小
            img_name = str(count).zfill(6)+'.jpg'
            CV2.imwrite(output_path + os.sep + img_name, image)
            count += 1

            print(output_path + os.sep + img_name)  # 输出提示
    cap.release()

"""
功能:获取视频的指定帧并进行显示
"""
def ShowSpecialFrame(file_path,frame_index):
    cap = CV2.VideoCapture(file_path)  # 读取视频文件
    cap.set(CV2.CAP_PROP_POS_FRAMES, float(frame_index))
    if cap.isOpened():  # 判断是否正常打开
        rval, frame = cap.read()
        CV2.imshow("image:"+frame_index,frame)
        CV2.waitKey()
    cap.release()

"""
功能:切割视频的指定帧。比如切割视频从100帧到第200帧的图片
     1.能够设置多少帧提取一帧图片
     2.可以设置输出图片的大小及灰度图
     3.手动设置输出图片的命名格式
"""
def ExtractVideoBySpecialFrame(video_input,output_path,start_frame_index,end_frame_index = -1):
    # 输出文件夹不存在,则创建输出文件夹
    if not os.path.exists(output_path):
        os.mkdir(output_path)

    cap = CV2.VideoCapture(video_input) # 读取视频文件
    cap.set(CV2.CAP_PROP_POS_FRAMES, float(start_frame_index))    # 从指定帧开始读取文件
    times = 0                           # 用来记录帧
    frame_frequency = 10                # 提取视频的频率,每frameFrequency帧提取一张图片,提取完整视频帧设置为1
    count = 0                           # 计数用,分割的图片按照count来命名

    # 未给定结束帧就从start_frame_index帧切割到最后一帧
    if end_frame_index == -1:
        print('开始提取', video_input, '视频从第',start_frame_index,'帧到最后一帧的图片!!')
        while True:
            times += 1
            res, image = cap.read()  # 读出图片
            if not res:
                print('图片提取结束!!')
                break
            if times % frame_frequency == 0:
                # picture_gray = CV2.cvtColor(image, CV2.COLOR_BGR2GRAY)  # 将图片转成灰度图
                # image_resize = CV2.resize(image, (368, 640))            # 修改图片的大小
                img_name = str(count).zfill(6) + '.jpg'
                CV2.imwrite(output_path + os.sep + img_name, image)
                count += 1
                print(output_path + os.sep + img_name)  # 输出提示
    else:
        print('开始提取', video_input, '视频从第', start_frame_index, '帧到第',end_frame_index,'帧的图片!!')
        k = end_frame_index - start_frame_index + 1
        while(k >= 0):
            times += 1
            k -= 1
            res, image = cap.read()  # 读出图片
            if not res:
                print('图片提取结束!!')
                break
            if times % frame_frequency == 0:
                # picture_gray = CV2.cvtColor(image, CV2.COLOR_BGR2GRAY)  # 将图片转成灰度图
                # image_resize = CV2.resize(image, (368, 640))            # 修改图片的大小
                img_name = str(count).zfill(6) + '.jpg'
                CV2.imwrite(output_path + os.sep + img_name, image)
                count += 1
                print(output_path + os.sep + img_name)  # 输出提示
        print('图片提取结束!!')
    cap.release()


if __name__ == "__main__":
    # 视频路径
    video_input = 'E://bilibili录屏//皮断腿.mp4'
    # 图片输出路径
    output_path = r'E:\ps\test'

    # 提取视频图片
    ExtractVideoFrame(video_input, output_path)

    # 显示视频第100帧的图片
    # ShowSpecialFrame(video_input, 1500)

    # 获取视频第100帧到第200帧的图片
    #ExtractVideoBySpecialFrame(video_input, output_path, 100, 200)

2.将图片帧合成视屏


# @description:把照片合成视频。

import os
import CV2
import uuid


def read_picture():
    path = 'E://ps//test' #input('请输入视频的路径[eg:D:\Image\BaiDuImgDownLoad\liuhai]: ')
    file_list = os.listdir(path)

    fps = 3  # 视频每秒多少帧
    height = 1280
    weight = 720
    size = (int(height), int(weight))  # 需要转为视频的图片的尺寸
    return [path, fps, size, file_list]


def write_video():
    path, fps, size, file_list = read_picture()
    # AVI格式编码输出 XVID
    four_cc = CV2.VideoWriter_fourcc(*'XVID')
    save_path = path + '\\' + '%s.avi' % str(uuid.uuid1())
    video_writer = CV2.VideoWriter(save_path, four_cc, float(fps), size)
    # 视频保存在当前目录下
    for item in file_list:
        if item.endswith('.jpg') or item.endswith('.png'):
            # 找到路径中所有后缀名为.png的文件,可以更换为.jpg或其它
            item = path + '\\' + item
            img = CV2.imread(item)
            re_pics = CV2.resize(img, size, interpolation=CV2.INTER_CUBIC)  # 定尺寸
            if len(re_pics):
                video_writer.write(re_pics)

    video_writer.release()
    CV2.destroyAllWindows()


if __name__ == '__main__':
    write_video()

Python将视频分成帧,将图片帧合成视频的评论 (共 条)

分享到微博请遵守国家法律