File size: 8,415 Bytes
c9e1b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import glob
import os
import pandas as pd
import numpy as np
import shutil
import os.path as osp
import cv2
import subprocess
import re
from calibration_syncvideos import calibration_syncvideos

ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.npy', '.png', '.pcd']


def visual_sync_output(output_dirs, devices_name):
    cam_txts = ["CAM " + devicen + " {}" for devicen in devices_name]
    size = (1920, 1080)  # (1920, 1080)
    video_size = (size[0] * 2, size[1] * 2)  # (size[0] * 3 + 1080, size[1] * 2)
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    all_imgs = []

    def extract_number(filename):
        base = os.path.basename(filename)
        number = int(os.path.splitext(base)[0])
        return number

    for outputdir in output_dirs:
        all_imgs.append(sorted(glob.glob(outputdir + "/*"), key=extract_number))
    out = cv2.VideoWriter("visual.avi", fourcc, 28, video_size)
    for frame in range(len(all_imgs[0])):
        # if frame < 600:
        #     continue
        # if frame > 900:
        #     break
        frame0 = cv2.imread(all_imgs[0][frame])
        frame1 = cv2.imread(all_imgs[1][frame])
        frame2 = cv2.imread(all_imgs[2][frame])
        frame3 = cv2.imread(all_imgs[3][frame])

        cv2.putText(frame0, cam_txts[0].format(frame), org=(100, 100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2,
                    color=(0, 0, 255), thickness=3)
        cv2.putText(frame1, cam_txts[1].format(frame), org=(100, 100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2,
                    color=(0, 0, 255), thickness=3)
        cv2.putText(frame2, cam_txts[2].format(frame), org=(100, 100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2,
                    color=(0, 0, 255), thickness=3)
        cv2.putText(frame3, cam_txts[3].format(frame), org=(100, 100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2,
                    color=(0, 0, 255), thickness=3)
        row0 = np.column_stack((frame0, frame1))
        row1 = np.column_stack((frame2, frame3))
        imshow = np.row_stack((row0, row1))
        scale_percent = 0.5
        dim = (int(imshow.shape[1] * scale_percent), int(imshow.shape[0] * scale_percent))
        resized = cv2.resize(imshow, dim, interpolation=cv2.INTER_AREA)  # resize image
        cv2.imshow('Image', resized)
        cv2.waitKey(10)
        out.write(imshow)
    out.release()


def sync_all_frames(input_dirs, output_dirs):
    # Create a dictionary to hold image timestamps for each directory
    timestamps_dict = {}

    # Define a function to check if the basename contains only digits
    def is_numeric_filename(filename):
        basename = os.path.splitext(os.path.basename(filename))[0]
        return basename.isdigit()

    for vid in input_dirs:
        out_images = sorted(glob.glob(vid + "/*"))
        # Filter the out_images to include only numeric filenames
        numeric_images = filter(is_numeric_filename, out_images)
        image_timestamps = list(map(lambda x: int(os.path.splitext(os.path.basename(x))[0]), numeric_images))
        timestamps_dict[vid] = image_timestamps

    # Threshold for matching timestamps
    THRESHOLD_NS = 25

    # Create a DataFrame for each directory's timestamps
    data_frames = {}
    for vid, timestamps in timestamps_dict.items():
        if 'frame' in timestamps:
            continue
        df = pd.DataFrame({'t': timestamps, vid: list(map(str, timestamps))})
        data_frames[vid] = df

    # Start with the first DataFrame
    merged_df = list(data_frames.values())[0]

    # Merge each subsequent DataFrame
    for vid, df in list(data_frames.items())[1:]:
        merged_df = pd.merge_asof(merged_df, df, on='t', tolerance=THRESHOLD_NS, allow_exact_matches=True,
                                  direction='nearest')

    # Drop any rows with NaN values resulting from the merge
    merged_df = merged_df.dropna()

    # Drop the 't' column if it's no longer needed
    merged_df = merged_df.drop('t', axis='columns')

    # Reset the index for a clean DataFrame
    merged_df = merged_df.reset_index(drop=True)

    print(merged_df.head())
    print(merged_df.dtypes)

    # Save the matched DataFrame to CSV
    parent_folder = os.path.abspath(os.path.join(output_dirs[0], os.pardir))
    output_filename = os.path.join(parent_folder, 'match_all.csv')
    merged_df.to_csv(output_filename)

    # Copy matched images to the new directory and rename them
    for cam_idx, sync_output in enumerate(output_dirs):
        if not osp.exists(sync_output):
            os.makedirs(sync_output)
        else:
            shutil.rmtree(sync_output)
            os.makedirs(sync_output)
    for idx, row in merged_df.iterrows():
        for cam_idx, vid in enumerate(input_dirs):
            src_file = f"{vid}/{row[vid]}.png"
            dst_file = os.path.join(output_dirs[cam_idx], f"{idx}.png")
            shutil.copy(src_file, dst_file)


def rename2timestamp(target_dir, video_path):
    # load frame timestamps csv, rename frames according to it
    video_root, video_filename = os.path.split(video_path)
    video_name, _ = os.path.splitext(video_filename)
    video_date = re.sub(r"VID_((\d|_)*)", r"\1", video_name)

    video_parent_dir = os.path.abspath(os.path.join(video_root, os.pardir))

    with open(os.path.join(video_parent_dir, video_date + ".csv")) \
            as frame_timestamps_file:
        filename_timestamps = list(map(
            lambda x: (x.strip('\n'), int(x)), frame_timestamps_file.readlines()
        ))
        length = len(list(filter(
            lambda x: os.path.splitext(x)[1] in ALLOWED_EXTENSIONS,
            os.listdir(target_dir)
        )))
        length = min(length, len(filename_timestamps))
        # frame number assertion
        # assert len(filename_timestamps) == len(list(filter(
        #     lambda x: os.path.splitext(x)[1] in ALLOWED_EXTENSIONS,
        #     os.listdir(target_dir)
        # ))), "Frame number in video %d and timestamp files %d did not match" % (l, len(filename_timestamps))
        print(video_path, "=========================================================")
        _, extension = os.path.splitext(os.listdir(target_dir)[0])
        for i in range(length):
            timestamp = filename_timestamps[i]
            os.rename(
                os.path.join(target_dir, "frame-%d.png" % (i + 1)),
                os.path.join(target_dir, timestamp[0] + extension)
            )


def extract_frames_from_videos(input_videos, extract_video_dirs):
    for video_path, output_dir in zip(input_videos, extract_video_dirs):
        if not osp.exists(output_dir):
            os.makedirs(output_dir)
        else:
            shutil.rmtree(output_dir)
            os.makedirs(output_dir)
        # Construct and call the FFmpeg command
        command = [
            'ffmpeg', '-i', video_path, '-vsync', '0',
            os.path.join(output_dir, 'frame-%d.png')
        ]
        subprocess.run(command, check=True)

        rename2timestamp(output_dir, video_path)


def sync_videos():
    recsync_videos_root = "./capturesync/"
    # input_videos = ["20240716/S22/VID/VID_20240716_141453.mp4", "20240716/Fold3/VID/VID_20240716_141453.mp4",
    #                 "20240716/S20/VID/VID_20240716_141453.mp4", "20240716/TabS7/VID/VID_20240716_141453.mp4"]
    input_videos = ["20240715/S22/VID/VID_20240715_170336.mp4", "20240715/Note9/VID/VID_20240715_170334.mp4",
                    "20240715/S20/VID/VID_20240715_170336.mp4", "20240715/TabS7/VID/VID_20240715_170336.mp4"]
    input_videos = [os.path.join(recsync_videos_root, video) for video in input_videos]
    output_dir = "./GMC0715"
    extract_dir_temp = "./GMC0715/extract_frames/"

    devices_name = [os.path.normpath(video).split(os.sep)[-3] for video in input_videos]
    extract_video_dirs = [os.path.join(extract_dir_temp, devicen) for devicen in devices_name]
    extract_frames_from_videos(input_videos, extract_video_dirs)
    sync_dirs = [os.path.join(output_dir, devicen) for devicen in devices_name]
    sync_all_frames(extract_video_dirs, sync_dirs)
    # shutil.rmtree(extract_dir_temp)
    visual_sync_output(sync_dirs, devices_name)


if __name__ == '__main__':
    sync_videos()
    calibration_syncvideos()