Skip to content

Instantly share code, notes, and snippets.

@htlin222
Last active March 28, 2024 05:26
Show Gist options
  • Save htlin222/df1f78a387c178f969e6895dc3d89f26 to your computer and use it in GitHub Desktop.
Save htlin222/df1f78a387c178f969e6895dc3d89f26 to your computer and use it in GitHub Desktop.
此 Python 指令碼可從視訊檔案中根據指定的時間段列表提取多個片段。它接受命令列參數以指定時間段檔案、視訊源和輸出目錄。若輸出目錄不存在,則自動建立。指令碼使用 moviepy 庫處理視訊,並生成以開始時間命名的片段檔案。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# title: trim
# date: "2024-01-29"
# description: 此 Python 指令碼可從視訊檔案中根據指定的時間段列表提取多個片段。它接受命令列參數以指定時間段檔案、視訊源和輸出目錄。若輸出目錄不存在,則自動建立。指令碼使用 moviepy 庫處理視訊,並生成以開始時間命名的片段檔案。
# `python trim.py -i clips.csv -v input.mp4`
import argparse
import os
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
def parse_time(time_str):
"""將時間字符串轉換為秒數"""
h, m, s = map(int, time_str.split(":"))
return h * 3600 + m * 60 + s
def format_time(seconds):
"""將秒數轉換為 HHMMSS 格式"""
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h:02d}{m:02d}{s:02d}"
def extract_clips(clips_file, video_file, output_dir):
"""從指定的視頻檔案中提取多個片段"""
# 檢查 output 目錄是否存在,不存在則創建
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(clips_file, "r") as file:
for line in file:
start, end = line.strip().split(",")
start_sec = parse_time(start)
end_sec = parse_time(end)
start_time_str = format_time(start_sec)
video_file_name = video_file.split(".")[0]
output_filename = (
f"{output_dir}/{video_file_name}_clip_{start_time_str}.mp4"
)
ffmpeg_extract_subclip(
video_file, start_sec, end_sec, targetname=output_filename
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="從視頻中提取片段")
parser.add_argument("-i", "--input", required=True, help="片段時間的文件")
# 00:01:01,00:01:30
parser.add_argument("-v", "--video", required=True, help="要處理的視頻文件")
parser.add_argument("-o", "--output", default="output", help="輸出目錄")
args = parser.parse_args()
extract_clips(args.input, args.video, args.output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment