这段代码是一个用于处理视频文件的 Python 脚本。它接受两个参数 dir_pathdst_dir_path,分别表示输入目录和输出目录。

代码的主要功能是将输入目录中的视频文件(以 .webm 结尾)转换为一系列的图片文件,并将这些图片文件保存到输出目录中。具体的处理过程如下:

  1. 遍历输入目录中的每个子目录(即每个类别),对于每个子目录执行以下操作:
  2. 检查当前子目录是否存在,如果不存在则创建它。
  3. 遍历当前子目录中的每个视频文件,对于每个视频文件执行以下操作:
    • 检查文件名是否以 .webm 结尾,如果不是则跳过。
    • 提取文件名的名称部分和扩展名部分。
    • 构建输出目录中的子目录路径,以文件名的名称部分命名。
    • 检查输出目录中的子目录是否存在,如果存在且不包含 '000001.jpg' 文件,则删除该子目录并重新创建。
    • 如果输出目录中的子目录不存在,则创建它。
    • 使用 ffmpeg 命令将视频文件转换为一系列的图片文件,并保存到输出目录中的子目录中。

总体来说,这段代码的作用是将输入目录中的视频文件转换为一系列的图片文件,并按照类别的子目录结构保存到输出目录中。

def class_process(dir_path, dst_dir_path):
    class_path = dir_path
    if not os.path.isdir(class_path):
        return

    dst_class_path = dst_dir_path
    if not os.path.exists(dst_class_path):
        os.mkdir(dst_class_path)

    for file_name in os.listdir(class_path):
        if '.webm' not in file_name:
            continue
        name, ext = os.path.splitext(file_name)
        dst_directory_path = os.path.join(dst_class_path, name)

        video_file_path = os.path.join(class_path, file_name)
        try:
            if os.path.exists(dst_directory_path):
                if not os.path.exists(os.path.join(dst_directory_path, '000001.jpg')):
                    subprocess.call('rm -r ' + dst_directory_path, shell=True)
                    print('remove ' + dst_directory_path)
                    os.mkdir(dst_directory_path)
                else:
                    continue
            else:
                os.mkdir(dst_directory_path)
        except:
            print(dst_directory_path)
            continue
        cmd = 'ffmpeg -i ' + video_file_path + ' -vf scale=-1:240 ' + dst_directory_path + '/%06d.jpg'
        print(cmd)
        subprocess.call(cmd, shell=True)
        print('\n')


if __name__ == "__main__":
    print("HELLO")
    dir_path = sys.argv[1]
    dst_dir_path = sys.argv[2]

    count = 0
    for class_name in os.listdir(dir_path):
        print(count)
        count = count + 1
        class_process(dir_path, dst_dir_path)
Python 脚本:将视频文件转换为图片序列并按类别存储

原文地址: https://www.cveoy.top/t/topic/wqq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录