1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
| import subprocess
| import os
|
| import re
|
|
| def cut_video_by_frames(video_path, frame_segments, total_frames, output_dir):
| """
| 将视频按照指定的帧切片进行切割。
|
| 参数:
| - video_path: 输入视频的路径
| - frame_segments: 切片的帧序号数组,例如:[0, M1, M2, ..., Mlast]
| - output_dir: 输出视频文件的目录
| """
| fps = 30 # default fps
|
| # 获取视频的帧率 (fps)
| command = [
| "ffmpeg", "-i", video_path, "-vf", "fps=1", "-f", "null", "-"
| ]
| result = subprocess.run(command, stdout=subprocess.PIPE,
| stderr=subprocess.PIPE, text=True)
| output = result.stderr
| # 解析 fps,查找信息
| fps_line = next(line for line in output.splitlines() if 'fps' in line)
| # 使用正则表达式提取帧率值(假设fps值总是出现在"fps"前面)
| match = re.search(r'(\d+(\.\d+)?)\s*fps', fps_line)
| if match:
| fps = float(match.group(1)) # 提取并转换为 float
| print(f"FPS: {fps}")
|
| print(f"视频的总帧数: {total_frames}, 帧率: {fps}")
|
| # 遍历切片区间
| for i in range(len(frame_segments) - 1):
| start_frame = frame_segments[i]
| end_frame = frame_segments[i + 1]
|
|
| start_time = float(start_frame) / fps
| end_time = float(end_frame) / fps
|
| output_file = os.path.join(output_dir, f"segment_{i + 1}.mp4")
|
|
| # 使用 FFmpeg 命令来切割视频
| command = [
| "ffmpeg", "-i", video_path, "-ss", f"{start_time:.10f}", "-to", f"{end_time:.10f}",
| "-c:v", "libx264", "-c:a", "copy","-crf", "18","-preset", "veryslow", output_file
| ]
| print(" ".join(command))
|
| subprocess.run(command)
|
| # 最后一段处理(从最后一个切片到视频结束)
| last_start_frame = frame_segments[-1]
| last_start_time = last_start_frame / fps
| output_file = os.path.join(
| output_dir, f"segment_{len(frame_segments)}.mp4")
|
| #print(f"正在切割最后一段:从 {last_start_time:.10f}s 到视频结束,保存为 {output_file}")
| command = [
| "ffmpeg", "-i", video_path, "-ss", f"{last_start_time:.10f}",
| "-c:v", "libx264", "-c:a", "copy","-crf", "18","-preset", "veryslow", output_file
| ]
| print(" ".join(command))
| subprocess.run(command)
|
|
| target_file = "E:/抖音-AI风景/新建文件夹\_demoold.mp4"
| selected_labels = [0, 60, 79, 98, 116, 135,
| 153, 172, 190, 209, 228, 246, 264, 283]
| frame_count = 305
| output_dir = "E:/抖音-AI风景/新建文件夹\ProcessResults"
|
| cut_video_by_frames(target_file, selected_labels, frame_count, output_dir)
|
|