百木园-与人分享,
就是让自己快乐。

视频处理---Python对视频抽帧得到图片

引:

    近期做CV方面算法,分享几个简单的视频、图片处理脚本

    脚本中均有print调试代码,,方便更改

 

Python对视频抽帧得到图片:

# -*- coding:utf8 -*-
import cv2
import os
import shutil


def get_frame_from_video(video_name, prefix_path):
    \"\"\"
    Args:
        video_name:输入视频名字
        interval: 保存图片的帧率间隔
    Returns:
    \"\"\"

    # 保存图片的路径
    save_path = video_name.split(\'.mp4\')[0] + \"\\\\\"
    print(f\'aaaaaa_+++video_name: {video_name} \')
    # 开始读视频
    video_capture = cv2.VideoCapture(video_name)
    # 读取视频的 FPS ,便于确定抽帧频次
    fps = int(video_capture.get(cv2.CAP_PROP_FPS))
    # fps = 15
    print(f\'fps_____: {fps}\')
    i = 0
    j = 0

    while True:
        success, frame = video_capture.read()
        print(f\'success: {success};;\')
        i += 1
        # 用 i 直接对帧率取余, 此脚本为每秒抽一张图片, 可灵活更改此处改变抽帧频度
        if i % fps == 0:
            # 保存图片
            j += 1
            # save_name = save_path + str(j) + \'_\' + str(i) + \'.jpg\'
            save_name = \'./\' + prefix_path + str(j) + \'_\' + str(i) + \'.jpg\'
            print(f\'nbnbbbbb_save_path: {save_path}\')
            print(f\'nbnbbbbb_savename: {save_name}\')
            cv2.imwrite(save_name, frame)
            print(\'image of %s is saved\' % save_name)
        if not success:
            print(\'video is all read\')
            break


# 获取文件夹下所有文件名
def get_filename(path: str, file_list: list):
    for file_name in os.listdir(path):
        file_path = os.path.join(path, file_name)
        if os.path.isdir(file_path):
            print(\"文件夹, 跳过\")
            continue
        file_list.append(file_name)
    file_list.sort()


if __name__ == \'__main__\':
    # 视频文件名字
    # video_name = \'./sss.mp4\'
    interval = 60
    data_path = \"E:\\\\PersonShape\\\\\"
    files = list()
    get_filename(data_path, files)
    total = len(files)
    print(f\'total: {total}\')
    for i in range(len(files)):
        try:
            video_name = data_path + files[i]
            prefix_path = files[i].split(\'.mp4\')[0] + \"\\\\\"
            if not os.path.exists(\'./\' + files[i].split(\'.mp4\')[0]):
                os.mkdir(\'./\' + files[i].split(\'.mp4\')[0])
            print(f\'video_name: {video_name}, prefix_path:{prefix_path}\')
            get_frame_from_video(video_name, prefix_path)
        except Exception as e:
            print(f\'e______________: {e}\')

  


来源:https://www.cnblogs.com/zhangxingcomeon/p/15993161.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » 视频处理---Python对视频抽帧得到图片

相关推荐

  • 暂无文章