Sebastian Cavada commited on
Commit
81001e6
·
1 Parent(s): 7738311

adding prepare data

Browse files
Files changed (1) hide show
  1. prepare_data.py +441 -0
prepare_data.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import itertools
3
+ import subprocess
4
+
5
+ def list_images_in_folder_multi(folder_path, scene_name, output_file=None):
6
+ """
7
+ Recursively list all image files in a specified folder and its subdirectories.
8
+ :param folder_path: Path to the root folder containing images
9
+ :param scene_name: Name of the current scene
10
+ :param output_file: Optional path to save the list of images (if None, prints to console)
11
+ :return: List of image filenames with full relative paths
12
+ """
13
+ # List of common image file extensions
14
+ image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
15
+
16
+ # List to store image paths
17
+ image_files = []
18
+
19
+ # Walk through all directories and subdirectories
20
+ for root, dirs, files in os.walk(folder_path):
21
+ # Find image files in current directory
22
+ current_images = [
23
+ os.path.relpath(os.path.join(root, file), folder_path)
24
+ for file in files
25
+ if os.path.splitext(file)[1].lower() in image_extensions
26
+ ]
27
+
28
+ # Add current directory's images to the list
29
+ image_files.extend(current_images)
30
+
31
+ # Sort the image files
32
+ image_files.sort()
33
+
34
+ # If output file is specified, write to file
35
+ if output_file:
36
+ with open(output_file, 'w') as f:
37
+ for image in image_files:
38
+ f.write(f"{scene_name}/{image}\n")
39
+ print(f"Image list saved to {output_file}")
40
+
41
+ # Print some basic information
42
+ print(f"Total images found: {len(image_files)}")
43
+ return image_files
44
+
45
+
46
+ def get_list_images(base_path):
47
+ """
48
+ Retrieve images from all camera subdirectories.
49
+ :param base_path: Base directory containing camera subdirectories
50
+ :return: Dictionary of camera names to sorted image lists
51
+ """
52
+ camera_images = {}
53
+ # Find all camera subdirectories
54
+ for camera_dir in os.listdir(base_path):
55
+ camera_path = os.path.join(base_path, camera_dir)
56
+
57
+ # Check if it's a directory and starts with 'cam'
58
+ if os.path.isdir(camera_path) and camera_dir.startswith('cam'):
59
+ # Get jpg files for this camera
60
+ image_files = [f for f in os.listdir(camera_path) if f.endswith('.jpg')]
61
+ camera_images[camera_dir] = sorted(image_files)
62
+
63
+ return camera_images
64
+
65
+ def generate_image_pairs(camera_images):
66
+ """
67
+ Generate image pairs within and across cameras, avoiding pairing an image with itself.
68
+ :param camera_images: Dictionary of camera names to image lists
69
+ :return: List of image pair tuples with camera names
70
+ """
71
+ image_pairs = []
72
+ camera_names = list(camera_images.keys())
73
+
74
+ # Generate pairs within each camera
75
+ for camera, images in camera_images.items():
76
+ # Pairs within the same camera using combinations
77
+ camera_pairs = list(itertools.combinations(images, 2))
78
+ camera_formatted_pairs = [(f"{camera}/{pair[0]}", f"{camera}/{pair[1]}") for pair in camera_pairs]
79
+ image_pairs.extend(camera_formatted_pairs)
80
+
81
+ # Generate pairs across different cameras
82
+ for i in range(len(camera_names)):
83
+ for j in range(i+1, len(camera_names)):
84
+ cam1, cam2 = camera_names[i], camera_names[j]
85
+ for img1 in camera_images[cam1]:
86
+ for img2 in camera_images[cam2]:
87
+ image_pairs.append((f"{cam1}/{img1}", f"{cam2}/{img2}"))
88
+
89
+ return image_pairs
90
+
91
+ def save_pairs_to_file(pairs, output_file, scene_name):
92
+ """
93
+ Save image pairs to a text file.
94
+ :param pairs: List of image pair tuples
95
+ :param output_file: Path to the output text file
96
+ :param scene_name: Name of the current scene
97
+ """
98
+ with open(output_file, 'w') as f:
99
+ for pair in pairs:
100
+ f.write(f"{scene_name}/{pair[0]} {scene_name}/{pair[1]}\n")
101
+
102
+ # ------------------------------------------------
103
+ # Helper functions for processing individual scenes
104
+ # CROSS PAIRS EXHAUSTIVE
105
+ # ------------------------------------------------
106
+
107
+ def get_image_range(path, start, end):
108
+ """
109
+ Get list of images within a specific range.
110
+
111
+ :param path: Directory path
112
+ :param start: Start of image range
113
+ :param end: End of image range
114
+ :return: Sorted list of images in the specified range
115
+ """
116
+ files = []
117
+ for file in os.listdir(path):
118
+ if file.endswith('.jpg'):
119
+ # Extract number from filename
120
+ try:
121
+ num = int(''.join(filter(str.isdigit, file)))
122
+ if start <= num <= end:
123
+ files.append(file)
124
+ except ValueError:
125
+ continue
126
+ return sorted(files)
127
+
128
+ def generate_cross_camera_pairs(images_list1, images_list2):
129
+ """
130
+ Generate image pairs between two specific ranges of images.
131
+
132
+ :param images_list1: List of images from first camera range
133
+ :param images_list2: List of images from second camera range
134
+ :return: List of image pair tuples
135
+ """
136
+ image_pairs = []
137
+ for img1 in images_list1:
138
+ for img2 in images_list2:
139
+ image_pairs.append((img1, img2))
140
+
141
+ return image_pairs
142
+
143
+ # ------------------------------------------------
144
+ # Helper functions for processing individual scenes
145
+ # PAIRS SEQUENTIALLY
146
+ # ------------------------------------------------
147
+
148
+ def generate_multi_camera_pairs(camera_images, window_size=20):
149
+ """
150
+ Generate image pairs across multiple cameras sequentially.
151
+ :param camera_images: Dictionary of camera names to image lists
152
+ :param window_size: Number of images to match before and after each image
153
+ :return: List of image pair tuples with camera names
154
+ """
155
+ # Ensure all cameras have the same number of images
156
+ max_images = max(len(images) for images in camera_images.values())
157
+
158
+ # Pad shorter camera lists with None to match the longest list
159
+ for camera, images in camera_images.items():
160
+ if len(images) < max_images:
161
+ camera_images[camera] = images + [None] * (max_images - len(images))
162
+
163
+ image_pairs = []
164
+
165
+ # Iterate through image indices
166
+ for current_index in range(max_images):
167
+ # Generate pairs for each camera with other cameras
168
+ for base_camera, base_images in camera_images.items():
169
+ # Skip if base image is None
170
+ if base_images[current_index] is None:
171
+ continue
172
+
173
+ # Generate pairs with images from other cameras in the same time step
174
+ for target_camera, target_images in camera_images.items():
175
+ if base_camera == target_camera:
176
+ continue
177
+
178
+ # Skip if target image is None
179
+ if target_images[current_index] is None:
180
+ continue
181
+
182
+ # Add current image pair
183
+ image_pairs.append((f"{base_camera}/{base_images[current_index]}",
184
+ f"{target_camera}/{target_images[current_index]}"))
185
+
186
+ # Generate pairs within window size for forward and backward directions
187
+ for i in range(1, window_size + 1):
188
+ # Forward window
189
+ if current_index + i < max_images:
190
+ if base_images[current_index + i] is not None and target_images[current_index + i] is not None:
191
+ image_pairs.append((
192
+ f"{base_camera}/{base_images[current_index]}",
193
+ f"{target_camera}/{target_images[current_index + i]}"
194
+ ))
195
+
196
+ # Backward window
197
+ if current_index - i >= 0:
198
+ if base_images[current_index - i] is not None and target_images[current_index - i] is not None:
199
+ image_pairs.append((
200
+ f"{base_camera}/{base_images[current_index]}",
201
+ f"{target_camera}/{target_images[current_index - i]}"
202
+ ))
203
+
204
+ return image_pairs
205
+
206
+
207
+ # Function to count image files in the directory
208
+ def count_images(output_directory):
209
+ image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff'}
210
+ return len([
211
+ f for f in os.listdir(output_directory)
212
+ if os.path.isfile(os.path.join(output_directory, f)) and os.path.splitext(f)[1].lower() in image_extensions
213
+ ])
214
+
215
+
216
+ def generate_images(out_dir, scene_name, config):
217
+
218
+ # Define the root folder for videos
219
+ root_video_dir = f"./videos/{scene_name}"
220
+
221
+ camera_correspondances = {
222
+ "00": "a",
223
+ "01": "b",
224
+ "02": "c",
225
+ "03": "d",
226
+ "04": "e",
227
+ "05": "f",
228
+ "core01": "core",
229
+ }
230
+
231
+ prev_max_id = 0
232
+
233
+ # Iterate through each folder in the root video directory
234
+ for folder_name in sorted(os.listdir(root_video_dir)):
235
+ folder_path = os.path.join(root_video_dir, folder_name)
236
+ print(f"Processing folder: {folder_name}")
237
+
238
+ # Check if it's a directory
239
+ if os.path.isdir(folder_path):
240
+ # Search for a video file in the folder
241
+ video_file = None
242
+ for file_name in os.listdir(folder_path):
243
+ if file_name.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')): # Add extensions as needed
244
+ video_file = os.path.join(folder_path, file_name)
245
+ break
246
+
247
+ if video_file is None:
248
+ print(f"No video file found in {folder_name}. Skipping...")
249
+ continue
250
+
251
+ # Create output images directory if it doesn't exist
252
+ output_images_dir = f"{out_dir}/{scene_name}/cam{folder_name}"
253
+ os.makedirs(output_images_dir, exist_ok=True)
254
+
255
+ skip_n_frames = config[scene_name]['skip_start_frames']
256
+
257
+ # Construct the ffmpeg command
258
+ ffmpeg_command = [
259
+ "ffmpeg",
260
+ "-hwaccel", "auto",
261
+ "-ss", f"{skip_n_frames/2}", # Skip n frames at 2fps (n/2 seconds)
262
+ "-i", video_file,
263
+ "-vf", "fps=2,scale=iw:ih",
264
+ "-q:v", "2",
265
+ "-start_number", f"{prev_max_id}",
266
+ f"{output_images_dir}/%06d_{camera_correspondances[folder_name]}.jpg"
267
+ ]
268
+
269
+ print(f"Running ffmpeg command for folder: {folder_name}")
270
+ # Run the command
271
+ try:
272
+ subprocess.run(ffmpeg_command,
273
+ stdout=subprocess.DEVNULL, # Suppress stdout
274
+ stderr=subprocess.DEVNULL, # Suppress stderr
275
+ check=True
276
+ )
277
+ print(f"Completed processing for folder: {folder_name}")
278
+
279
+ except subprocess.CalledProcessError as e:
280
+ print(f"Error processing folder {folder_name}: {e}")
281
+
282
+ total_images = count_images(output_images_dir)
283
+ print(f"Total images extracted: {total_images}")
284
+ prev_max_id += total_images + 1
285
+ print(f"Next start number: {prev_max_id}")
286
+
287
+ def generate_exhaustive_pairs(folder_path, output_file_pairs_exhaustive, scene_name):
288
+ # Get images from all cameras
289
+ camera_images = get_list_images(folder_path)
290
+
291
+ # Generate exhaustive list of pairs of images
292
+ print(f"Generating image pairs for scene: {scene_name}")
293
+ image_pairs = generate_image_pairs(camera_images)
294
+
295
+ # Save pairs to file
296
+ save_pairs_to_file(image_pairs, output_file_pairs_exhaustive, scene_name)
297
+ print(f"Processing completed for scene: {scene_name}")
298
+
299
+ def process_scene(scene_name, config, out_dir="./images"):
300
+ """
301
+ Process a single scene including video extraction and image pair generation
302
+ :param scene_name: Name of the scene to process
303
+ :param config: Configuration dictionary containing scene-specific settings
304
+ """
305
+ print(f"\n{'='*50}\nProcessing scene: {scene_name}\n{'='*50}")
306
+
307
+ print(f"Generating images for scene: {scene_name}")
308
+ generate_images(out_dir, scene_name, config)
309
+
310
+ # Generate output files
311
+ new_folder_path = f"{out_dir}/{scene_name}"
312
+ output_file_list = f"{out_dir}/{scene_name}/image_list.txt"
313
+ output_file_pairs_exhaustive = f"{out_dir}/{scene_name}/image_pairs_exhaustive.txt"
314
+ output_file_pairs_sequential = f"{out_dir}/{scene_name}/image_pairs_sequential.txt"
315
+
316
+ # Write the image list
317
+ print(f"Generating image list for scene: {scene_name}")
318
+ list_images_in_folder_multi(new_folder_path, scene_name, output_file_list)
319
+
320
+ print(f"Generating exhaustive image pairs for scene: {scene_name}")
321
+ generate_exhaustive_pairs(new_folder_path, output_file_pairs_exhaustive, scene_name)
322
+
323
+ # Get images from all cameras
324
+ camera_images = get_list_images(new_folder_path)
325
+
326
+ # # Generate exhaustive list of pairs of images
327
+ # print(f"Generating image pairs for scene: {scene_name}")
328
+ # image_pairs = generate_image_pairs(camera_images)
329
+
330
+ # # Save pairs to file
331
+ # save_pairs_to_file(image_pairs, output_file_pairs_exhaustive, scene_name)
332
+ # print(f"Processing completed for scene: {scene_name}")
333
+
334
+ if(config[scene_name].get('generate_correspondances', False)):
335
+ src_scene = config.get('src_scene', "campus_core")
336
+ src_cam = config.get('src_cam', "core01")
337
+ target_scene = config.get('target_scene', "mid_library")
338
+
339
+ # generate cross-camera pairs
340
+ cam1_path = f"{out_dir}/{src_scene}/{src_cam}"
341
+ cam2_path = f"{out_dir}/{target_scene}/cam01"
342
+ output_file = f"{out_dir}/{target_scene}/cross_camera_pairs.txt"
343
+
344
+ # Get images in specified ranges
345
+ cam1_start = config[scene_name]['cam1_start']
346
+ cam1_end = config[scene_name]['cam1_end']
347
+ cam2_start = config[scene_name]['cam2_start']
348
+ cam2_end = config[scene_name]['cam2_end']
349
+
350
+ cam1_images = get_image_range(cam1_path, cam1_start, cam1_end)
351
+ cam2_images = get_image_range(cam2_path, cam2_start, cam2_end)
352
+
353
+ # Generate cross-camera image pairs
354
+ image_pairs = generate_cross_camera_pairs(cam1_images, cam2_images)
355
+
356
+ # Save pairs to file
357
+ save_pairs_to_file(image_pairs, output_file, cam1_prefix=f'{src_scene}/{src_cam}/', cam2_prefix=f'{target_scene}/cam01/')
358
+
359
+ # Print statistics
360
+ print(f"Images from Camera 1 (range {cam1_start}-{cam1_end}): {len(cam1_images)}")
361
+ print(f"Images from Camera 2 (range {cam2_start}-{cam2_end}): {len(cam2_images)}")
362
+ print(f"Total cross-camera pairs generated: {len(image_pairs)}")
363
+ print(f"Pairs saved to: {output_file}")
364
+
365
+ # Scene configurations
366
+ config = {
367
+ "campus_core": {
368
+ 'skip_start_frames': 0,
369
+ 'src_scene': "campus_core",
370
+ 'src_cam': "core01",
371
+ 'target_scene': "mid_library",
372
+ 'cam1_start': 0,
373
+ 'cam1_end': 100,
374
+ 'cam2_start': 0,
375
+ 'cam2_end': 100,
376
+ 'generate_correspondances': False,
377
+ },
378
+ "campus_entrance": {
379
+ 'skip_start_frames': 0,
380
+ 'cam1_start': 0,
381
+ 'cam1_end': 100,
382
+ 'cam2_start': 0,
383
+ 'cam2_end': 100,
384
+ },
385
+ "campus_entrance_2": {
386
+ 'skip_start_frames': 0,
387
+ },
388
+ "campus_knowledge_center": {
389
+ 'skip_start_frames': 0,
390
+ },
391
+ "campus_nlpr": {
392
+ 'skip_start_frames': 0,
393
+ },
394
+ "garden_path": {
395
+ 'skip_start_frames': 0,
396
+ },
397
+ "hydro_NLP_connection":{
398
+ 'skip_start_frames': 0,
399
+ 'cam1_start': 1150,
400
+ 'cam1_end': 1170,
401
+ 'cam2_start': 158,
402
+ 'cam2_end': 171,
403
+ },
404
+ "knowledge_center_front": {
405
+ 'skip_start_frames': 0,
406
+ },
407
+ "library": {
408
+ 'skip_start_frames': 4,
409
+ },
410
+ "mid_library": {
411
+ 'skip_start_frames': 20,
412
+ 'cam1_start': 700,
413
+ 'cam1_end': 720,
414
+ 'cam2_start': 118,
415
+ 'cam2_end': 140,
416
+ },
417
+ "NLP_boulevard": {
418
+ 'skip_start_frames': 8,
419
+ 'cam1_start': 220,
420
+ 'cam1_end': 240,
421
+ 'cam2_start': 164,
422
+ 'cam2_end': 174,
423
+ },
424
+ }
425
+
426
+ # List of scenes to process
427
+ # Process all the scenes
428
+ # scenes_to_process = config.keys()
429
+
430
+ # or Process a subset of scenes
431
+ # scenes_to_process = ["library", "mid_library", "NLP_boulevard"]
432
+ scenes_to_process = ["campus_core"]
433
+
434
+ # Process each scene
435
+ for scene in scenes_to_process:
436
+ if scene in config:
437
+ process_scene(scene, config)
438
+ else:
439
+ print(f"Warning: Scene '{scene}' not found in configuration. Skipping.")
440
+
441
+ print("All scenes processed successfully!")