Download prepare_data.py from sebothetramp/MBZUAI-Campus: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/datasets/sebothetramp/MBZUAI-Campus/resolve/main/prepare_data.py
- Command line
-
hf download hf://datasets/sebothetramp/MBZUAI-Campus/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/datasets/sebothetramp/MBZUAI-Campus/resolve/main/prepare_data.py
20.3 kB
| 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 |