-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_frames.py
More file actions
149 lines (116 loc) · 4.29 KB
/
process_frames.py
File metadata and controls
149 lines (116 loc) · 4.29 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
from pathlib import Path
from datetime import datetime
import pandas as pd
import subprocess
# -------------------------------------------------------
# Create FFmpeg filelist
# -------------------------------------------------------
def write_filelist(filelist_path, image_paths):
with open(filelist_path, "w", encoding="utf-8") as f:
for p in image_paths:
f.write(f"file '{p.as_posix()}'\n")
# -------------------------------------------------------
# Run FFmpeg
# -------------------------------------------------------
def run_ffmpeg(cmd):
print("Running FFmpeg:")
print(" ".join(cmd))
subprocess.run(cmd, check=True)
# -------------------------------------------------------
# MAIN PROCESS
# -------------------------------------------------------
def process(input_folder=Path("C:/sync"), fps=15):
output_folder = input_folder / "output_videos"
output_folder.mkdir(exist_ok=True)
# ---------------------------------------------------
# Step 1 — Collect ALL frames and parse timestamps
# ---------------------------------------------------
print("Scanning JPG files...")
jpg_files = list(input_folder.rglob("*.jpg"))
records = []
for file in jpg_files:
ip = file.parent.parent.parent.parent.name # "<ip>"
ts_str = file.stem.replace("~T", "")
try:
ts = datetime.strptime(ts_str, "%Y_%m_%dT%H_%M_%S_%f")
except:
continue
records.append((ip, ts, file))
df = pd.DataFrame(records, columns=["ip", "timestamp", "path"])
df = df.sort_values(["timestamp", "ip"])
# ---------------------------------------------------
# Step 2 — Build synchronized groups
# ---------------------------------------------------
print("Grouping timestamps...")
counts = df["timestamp"].value_counts()
shared_ts = counts[counts == df["ip"].nunique()].index # only timestamps present in all cameras
df_sync = df[df["timestamp"].isin(shared_ts)]
df_sync = df_sync.sort_values(["timestamp", "ip"])
print(f"Total synchronized frames: {len(df_sync)}")
# ---------------------------------------------------
# Step 3 — Create per-camera filelists
# ---------------------------------------------------
ips = sorted(df_sync["ip"].unique())
filelists = {}
for ip in ips:
cam_frames = df_sync[df_sync["ip"] == ip]["path"].tolist()
filelist_path = output_folder / f"{ip}_filelist.txt"
write_filelist(filelist_path, cam_frames)
filelists[ip] = filelist_path
# ---------------------------------------------------
# Step 4 — Encode each camera video
# ---------------------------------------------------
print("Encoding camera videos...")
cam_videos = {}
for ip, filelist in filelists.items():
out = output_folder / f"{ip}.mp4"
cam_videos[ip] = out
cmd = [
"ffmpeg", "-y",
"-f", "concat",
"-safe", "0",
"-r", str(fps),
"-i", str(filelist),
"-vf", "hflip",
"-vcodec", "libx264",
"-preset", "fast",
"-crf", "18",
"-pix_fmt", "yuv420p",
str(out)
]
run_ffmpeg(cmd)
# ---------------------------------------------------
# Step 5 — Build synchronized grid montage
# ---------------------------------------------------
print("Building grid video...")
# expected cameras in layout
cam27 = str(cam_videos.get("27"))
cam25 = str(cam_videos.get("25"))
cam26 = str(cam_videos.get("26"))
cam24 = str(cam_videos.get("24"))
grid_out = output_folder / "sync_grid.mp4"
cmd = [
"ffmpeg", "-y",
"-i", cam27,
"-i", cam25,
"-i", cam26,
"-i", cam24,
"-filter_complex",
# Build the 2x2 grid layout:
# Row1: cam27 | cam25
# Row2: cam26 | cam24
"[0:v][1:v]hstack=inputs=2[top];"
"[2:v][3:v]hstack=inputs=2[bottom];"
"[top][bottom]vstack=inputs=2[grid]",
"-map", "[grid]",
"-vcodec", "libx264",
"-preset", "fast",
"-crf", "18",
"-pix_fmt", "yuv420p",
str(grid_out)
]
run_ffmpeg(cmd)
print("\nALL DONE!")
print(f"Grid video: {grid_out}")
if __name__ == "__main__":
process()