File size: 20,252 Bytes
81001e6 7de9793 81001e6 2ffcc4f 81001e6 7de9793 81001e6 2ffcc4f 81001e6 2ffcc4f 81001e6 2ffcc4f 81001e6 7de9793 81001e6 7de9793 81001e6 7de9793 81001e6 7de9793 81001e6 7de9793 81001e6 7de9793 81001e6 fe964fe 34f6878 2ffcc4f 34f6878 fe964fe 34f6878 81001e6 5f7a053 81001e6 34f6878 81001e6 5f7a053 fe964fe 81001e6 5f7a053 81001e6 7de9793 81001e6 fe964fe 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee 81001e6 9a0dbee |
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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
import os
import json
import itertools
import subprocess
def list_images_in_folder_multi(folder_path, scene_name, output_file=None):
"""
Recursively list all image files in a specified folder and its subdirectories.
:param folder_path: Path to the root folder containing images
:param scene_name: Name of the current scene
:param output_file: Optional path to save the list of images (if None, prints to console)
:return: List of image filenames with full relative paths
"""
# List of common image file extensions
image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
# List to store image paths
image_files = []
# Walk through all directories and subdirectories
for root, dirs, files in os.walk(folder_path):
# Find image files in current directory
current_images = [
os.path.relpath(os.path.join(root, file), folder_path)
for file in files
if os.path.splitext(file)[1].lower() in image_extensions
]
# Add current directory's images to the list
image_files.extend(current_images)
# Sort the image files
image_files.sort()
# If output file is specified, write to file
if output_file:
with open(output_file, 'w') as f:
for image in image_files:
f.write(f"{scene_name}/{image}\n")
print(f"Image list saved to {output_file}")
# Print some basic information
print(f"Total images found: {len(image_files)}")
return image_files
def get_list_images(base_path):
"""
Retrieve images from all camera subdirectories.
:param base_path: Base directory containing camera subdirectories
:return: Dictionary of camera names to sorted image lists
"""
camera_images = {}
# Find all camera subdirectories
for camera_dir in os.listdir(base_path):
camera_path = os.path.join(base_path, camera_dir)
# Check if it's a directory and starts with 'cam'
if os.path.isdir(camera_path) and camera_dir.startswith('cam'):
# Get jpg files for this camera
image_files = [f for f in os.listdir(camera_path) if f.endswith('.jpg')]
camera_images[camera_dir] = sorted(image_files)
return camera_images
def generate_image_pairs(camera_images):
"""
Generate image pairs within and across cameras, avoiding pairing an image with itself.
:param camera_images: Dictionary of camera names to image lists
:return: List of image pair tuples with camera names
"""
image_pairs = []
camera_names = list(camera_images.keys())
# Generate pairs within each camera
for camera, images in camera_images.items():
# Pairs within the same camera using combinations
camera_pairs = list(itertools.combinations(images, 2))
camera_formatted_pairs = [(f"{camera}/{pair[0]}", f"{camera}/{pair[1]}") for pair in camera_pairs]
image_pairs.extend(camera_formatted_pairs)
# Generate pairs across different cameras
for i in range(len(camera_names)):
for j in range(i+1, len(camera_names)):
cam1, cam2 = camera_names[i], camera_names[j]
for img1 in camera_images[cam1]:
for img2 in camera_images[cam2]:
image_pairs.append((f"{cam1}/{img1}", f"{cam2}/{img2}"))
return image_pairs
def save_pairs_to_file(pairs, output_file, scene_name):
"""
Save image pairs to a text file.
:param pairs: List of image pair tuples
:param output_file: Path to the output text file
:param scene_name: Name of the current scene
"""
with open(output_file, 'w') as f:
for pair in pairs:
f.write(f"{scene_name}/{pair[0]} {scene_name}/{pair[1]}\n")
# ------------------------------------------------
# Helper functions for processing individual scenes
# CROSS PAIRS EXHAUSTIVE
# ------------------------------------------------
def get_image_range(path, start, end):
"""
Get list of images within a specific range.
:param path: Directory path
:param start: Start of image range
:param end: End of image range
:return: Sorted list of images in the specified range
"""
files = []
for file in os.listdir(path):
if file.endswith('.jpg'):
# Extract number from filename
try:
num = int(''.join(filter(str.isdigit, file)))
if start <= num <= end:
files.append(file)
except ValueError:
continue
return sorted(files)
def generate_cross_camera_pairs(images_list1, images_list2):
"""
Generate image pairs between two specific ranges of images.
:param images_list1: List of images from first camera range
:param images_list2: List of images from second camera range
:return: List of image pair tuples
"""
image_pairs = []
for img1 in images_list1:
for img2 in images_list2:
image_pairs.append((img1, img2))
return image_pairs
# ------------------------------------------------
# Helper functions for processing individual scenes
# PAIRS SEQUENTIALLY
# ------------------------------------------------
def generate_multi_camera_pairs(camera_images, window_size=20):
"""
Generate image pairs across multiple cameras sequentially.
Also generates pairs within the same camera if only one camera is present.
:param camera_images: Dictionary of camera names to image lists
:param window_size: Number of images to match before and after each image
:return: List of image pair tuples with camera names
"""
# Ensure all cameras have the same number of images
max_images = max(len(images) for images in camera_images.values())
# Pad shorter camera lists with None to match the longest list
for camera, images in camera_images.items():
if len(images) < max_images:
camera_images[camera] = images + [None] * (max_images - len(images))
image_pairs = []
# Iterate through image indices
for current_index in range(max_images):
# Generate pairs for each camera with other cameras
for base_camera, base_images in camera_images.items():
# Skip if base image is None
if base_images[current_index] is None:
continue
# Generate pairs with other cameras
for target_camera, target_images in camera_images.items():
# Skip self-pairing at the same index (would create identical pairs)
if base_camera == target_camera and current_index == current_index:
# But still generate pairs for same camera at different timestamps
# if there's only one camera
if len(camera_images) == 1:
# Generate pairs within window size for forward and backward directions
for i in range(1, window_size + 1):
# Forward window
if current_index + i < max_images and base_images[current_index + i] is not None:
image_pairs.append((
f"{base_camera}/{base_images[current_index]}",
f"{base_camera}/{base_images[current_index + i]}"
))
# Backward window
if current_index - i >= 0 and base_images[current_index - i] is not None:
image_pairs.append((
f"{base_camera}/{base_images[current_index]}",
f"{base_camera}/{base_images[current_index - i]}"
))
continue
# Skip if target image is None
if target_images[current_index] is None:
continue
# Add current image pair (from different cameras)
image_pairs.append((f"{base_camera}/{base_images[current_index]}",
f"{target_camera}/{target_images[current_index]}"))
# Generate pairs within window size for forward and backward directions
for i in range(1, window_size + 1):
# Forward window
if current_index + i < max_images:
if base_images[current_index + i] is not None and target_images[current_index + i] is not None:
image_pairs.append((
f"{base_camera}/{base_images[current_index]}",
f"{target_camera}/{target_images[current_index + i]}"
))
# Backward window
if current_index - i >= 0:
if base_images[current_index - i] is not None and target_images[current_index - i] is not None:
image_pairs.append((
f"{base_camera}/{base_images[current_index]}",
f"{target_camera}/{target_images[current_index - i]}"
))
return image_pairs
# Function to count image files in the directory
def count_images(output_directory):
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff'}
return len([
f for f in os.listdir(output_directory)
if os.path.isfile(os.path.join(output_directory, f)) and os.path.splitext(f)[1].lower() in image_extensions
])
def get_video_duration(video_path):
result = subprocess.run([
"ffprobe", "-v", "error",
"-show_entries", "format=duration",
"-of", "json", video_path
], stdout=subprocess.PIPE)
duration = float(json.loads(result.stdout)["format"]["duration"])
return duration
def generate_images(out_dir, scene_name, config):
# Define the root folder for videos
root_video_dir = f"./videos/{scene_name}"
camera_correspondances = {
"00": "a",
"01": "b",
"02": "c",
"03": "d",
"04": "e",
"05": "f",
"core01": "core",
}
prev_max_id = 0
# Iterate through each folder in the root video directory
for folder_name in sorted(os.listdir(root_video_dir)):
folder_path = os.path.join(root_video_dir, folder_name)
print(f"Processing folder: {folder_name}")
# Check if it's a directory
if os.path.isdir(folder_path):
# Search for a video file in the folder
video_file = None
for file_name in os.listdir(folder_path):
if file_name.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')): # Add extensions as needed
video_file = os.path.join(folder_path, file_name)
break
if video_file is None:
print(f"No video file found in {folder_name}. Skipping...")
continue
# Create output images directory if it doesn't exist
output_images_dir = f"{out_dir}/{scene_name}/cam{folder_name}"
os.makedirs(output_images_dir, exist_ok=True)
duration = get_video_duration(video_file)
skip_start = config[scene_name].get('skip_start_seconds', 0)
skip_end = config[scene_name].get('skip_end_seconds', 0)
duration_to_keep = duration - skip_start - skip_end
# Construct the ffmpeg command
# ffmpeg_command = [
# "ffmpeg",
# "-hwaccel", "auto",
# "-ss", f"{skip_start_seconds}", # Skip n frames at 2fps (n/2 seconds)
# "-i", video_file,
# "-vf", "fps=2,scale=iw:ih",
# "-q:v", "2",
# "-start_number", f"{prev_max_id}",
# f"{output_images_dir}/%06d_{camera_correspondances[folder_name]}.jpg"
# ]
# Build ffmpeg command
ffmpeg_command = [
"ffmpeg",
"-hwaccel", "auto",
"-ss", f"{skip_start}",
"-i", video_file,
"-t", f"{duration_to_keep}",
"-vf", "fps=2,scale=iw:ih",
"-q:v", "2",
"-start_number", f"{prev_max_id}",
f"{output_images_dir}/%06d{camera_correspondances[folder_name]}.jpg"
]
print(f"Running ffmpeg command for folder: {folder_name}")
# Run the command
try:
subprocess.run(ffmpeg_command,
stdout=subprocess.DEVNULL, # Suppress stdout
stderr=subprocess.DEVNULL, # Suppress stderr
check=True
)
print(f"Completed processing for folder: {folder_name}")
except subprocess.CalledProcessError as e:
print(f"Error processing folder {folder_name}: {e}")
total_images = count_images(output_images_dir)
print(f"Total images extracted: {total_images}")
prev_max_id += total_images + 1
print(f"Next start number: {prev_max_id}")
def generate_exhaustive_pairs(folder_path, output_file_pairs_exhaustive, scene_name):
# Get images from all cameras
camera_images = get_list_images(folder_path)
# Generate exhaustive list of pairs of images
print(f"Generating image pairs for scene: {scene_name}")
image_pairs = generate_image_pairs(camera_images)
# Save pairs to file
save_pairs_to_file(image_pairs, output_file_pairs_exhaustive, scene_name)
print(f"Processing completed for scene: {scene_name}")
def generate_sequential_pairs(folder_path, output_file_pairs_sequential, scene_name, window_size=20):
# Get images from all cameras
camera_images = get_list_images(folder_path)
print(camera_images)
# Generate exhaustive list of pairs of images
print(f"Generating image pairs for scene: {scene_name}")
images_pairs_sequential = generate_multi_camera_pairs(camera_images, window_size)
# Save pairs to file
save_pairs_to_file(images_pairs_sequential, output_file_pairs_sequential, scene)
def process_scene(scene_name, config, out_dir="./images"):
"""
Process a single scene including video extraction and image pair generation
:param scene_name: Name of the scene to process
:param config: Configuration dictionary containing scene-specific settings
"""
print(f"\n{'='*50}\nProcessing scene: {scene_name}\n{'='*50}")
print(f"Generating images for scene: {scene_name}")
if(os.path.exists(f"{out_dir}/{scene_name}")):
print(f"Images already generated for scene: {scene_name}")
else:
generate_images(out_dir, scene_name, config)
# Generate output files
new_folder_path = f"{out_dir}/{scene_name}"
output_file_list = f"{out_dir}/{scene_name}/image_list.txt"
output_file_pairs_exhaustive = f"{out_dir}/{scene_name}/image_pairs_exhaustive.txt"
output_file_pairs_sequential = f"{out_dir}/{scene_name}/image_pairs_sequential.txt"
# Write the image list
print(f"Generating image list for scene: {scene_name}")
list_images_in_folder_multi(new_folder_path, scene_name, output_file_list)
print(f"Generating exhaustive image pairs for scene: {scene_name}")
generate_exhaustive_pairs(new_folder_path, output_file_pairs_exhaustive, scene_name)
print(f"Generating sequential image pairs for scene: {scene_name}")
generate_sequential_pairs(new_folder_path, output_file_pairs_sequential, \
scene_name, config[scene_name].get('window_size', 20))
# Get images from all cameras
# camera_images = get_list_images(new_folder_path)
# # Generate exhaustive list of pairs of images
# print(f"Generating image pairs for scene: {scene_name}")
# image_pairs = generate_image_pairs(camera_images)
# # Save pairs to file
# save_pairs_to_file(image_pairs, output_file_pairs_exhaustive, scene_name)
# print(f"Processing completed for scene: {scene_name}")
if(config[scene_name].get('generate_correspondances', False)):
src_scene = config.get('src_scene', "campus_core")
src_cam = config.get('src_cam', "core01")
target_scene = config.get('target_scene', "mid_library")
# generate cross-camera pairs
cam1_path = f"{out_dir}/{src_scene}/{src_cam}"
cam2_path = f"{out_dir}/{target_scene}/cam01"
output_file = f"{out_dir}/{target_scene}/cross_camera_pairs.txt"
# Get images in specified ranges
cam1_start = config[scene_name]['cam1_start']
cam1_end = config[scene_name]['cam1_end']
cam2_start = config[scene_name]['cam2_start']
cam2_end = config[scene_name]['cam2_end']
cam1_images = get_image_range(cam1_path, cam1_start, cam1_end)
cam2_images = get_image_range(cam2_path, cam2_start, cam2_end)
# Generate cross-camera image pairs
image_pairs = generate_cross_camera_pairs(cam1_images, cam2_images)
# Save pairs to file
save_pairs_to_file(image_pairs, output_file, cam1_prefix=f'{src_scene}/{src_cam}/', cam2_prefix=f'{target_scene}/cam01/')
# Print statistics
print(f"Images from Camera 1 (range {cam1_start}-{cam1_end}): {len(cam1_images)}")
print(f"Images from Camera 2 (range {cam2_start}-{cam2_end}): {len(cam2_images)}")
print(f"Total cross-camera pairs generated: {len(image_pairs)}")
print(f"Pairs saved to: {output_file}")
# Scene configurations
config = {
"campus_core": {
'skip_start_seconds': 5,
'skip_end_seconds': 20,
'src_scene': "campus_core",
'src_cam': "core01",
'target_scene': "mid_library",
'cam1_start': 0,
'cam1_end': 100,
'cam2_start': 0,
'cam2_end': 100,
'generate_correspondances': False,
'window_size': 10,
},
"campus_entrance": {
'skip_start_seconds': 0,
'cam1_start': 0,
'cam1_end': 100,
'cam2_start': 0,
'cam2_end': 100,
},
"campus_entrance_2": {
'skip_start_seconds': 3,
'skip_end_seconds': 0,
},
"campus_knowledge_center": {
'skip_start_seconds': 0,
'skip_end_seconds': 0,
},
"campus_nlp": {
'skip_start_seconds': 0,
'skip_end_seconds': 0,
},
"garden_path": {
'skip_start_seconds': 5,
'skip_end_seconds': 0,
},
"hydro_NLP_connection":{
'skip_start_seconds': 6,
'skip_end_seconds': 7,
'cam1_start': 1150,
'cam1_end': 1170,
'cam2_start': 158,
'cam2_end': 171,
},
"knowledge_center_front": {
'skip_start_seconds': 8,
'skip_end_seconds': 0,
},
"library": {
'skip_start_seconds': 4,
'skip_end_seconds': 0,
},
"mid_library": {
'skip_start_seconds': 3,
'skip_end_seconds': 0,
'cam1_start': 700,
'cam1_end': 720,
'cam2_start': 118,
'cam2_end': 140,
},
"NLP_boulevard": {
'skip_start_seconds': 6,
'skip_end_seconds': 0,
'cam1_start': 220,
'cam1_end': 240,
'cam2_start': 164,
'cam2_end': 174,
},
}
# List of scenes to process
# Process all the scenes
# scenes_to_process = config.keys()
# or Process a subset of scenes
# scenes_to_process = ["library", "mid_library", "NLP_boulevard"]
scenes_to_process = ["campus_core"]
# Process each scene
for scene in scenes_to_process:
if scene in config:
process_scene(scene, config)
else:
print(f"Warning: Scene '{scene}' not found in configuration. Skipping.")
print("All scenes processed successfully!")
# find . -type f -name '._*.MP4' -delete |