# Standard Library Imports import os import sys import copy import time import argparse import datetime from pathlib import Path from collections import defaultdict, namedtuple import struct # Add local modules to path sys.path.append("/home/sebastian.cavada/scsv/mast3r_complete") sys.path.append("/home/sebastian.cavada/scsv/mast3r_complete/dust3r") sys.path.append("/home/sebastian.cavada/scsv/mast3r_complete/_evaluation") # Third-Party Imports import numpy as np import torch import torch.nn.functional as F import torch.backends.cudnn as cudnn # import matplotlib.pyplot as plt # import plotly.graph_objects as go from PIL import Image from tqdm import tqdm # Local Application/Library Imports import mast3r.utils.path_to_dust3r # noqa from mast3r.model import AsymmetricMASt3R from dust3r.datasets import get_data_loader # noqa from dust3r.model import AsymmetricCroCo3DStereo from dust3r.utils.geometry import geotrf, inv, normalize_pointcloud import dust3r.datasets import croco.utils.misc as misc # noqa from dust3r.inference import inference from dust3r.image_pairs import make_pairs from dust3r.utils.image import load_images, rgb from dust3r.utils.device import to_numpy from dust3r.viz import add_scene_cam, CAM_COLORS, OPENGL, pts3d_to_trimesh, cat_meshes from dust3r.cloud_opt import global_aligner, GlobalAlignerMode # Import utility functions from utils.general import get_batch_colmap, plot_3d_points_with_frustums, voxel_downsample_with_colors # noqa # creating a new dataloader from dust3r.datasets import CustomCOLMAP # Define infinity constant inf = float('inf') # Set random seed for reproducibility seed = 777 + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = False # Define Point3D namedtuple for COLMAP compatibility Point3D = namedtuple( "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"] ) # Default configuration DEFAULT_CONFIG = { 'device': 'cuda', 'batch_size': 4, 'schedule': 'cosine', 'lr': 0.01, 'niter': 300, 'min_conf_thr': 0 } # Model configurations MODEL_CONFIGS = { 'dust3r': { 'path': '/home/sebastian.cavada/scsv/thesis/mast3r_complete/checkpoints/dust3r_512dpt/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth', 'architecture': "AsymmetricCroCo3DStereo(pos_embed='RoPE100', patch_embed_cls='ManyAR_PatchEmbed', img_size=(512, 512), head_type='dpt', output_mode='pts3d', depth_mode=('exp', -inf, inf), conf_mode=('exp', 1, inf), enc_embed_dim=1024, enc_depth=24, enc_num_heads=16, dec_embed_dim=768, dec_depth=12, dec_num_heads=12)" }, 'mast3r': { 'path': '/home/sebastian.cavada/Documents/scsv/thesis/thesis_2025/mast3r_complete/checkpoints/dust3r_512dpt/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth', 'architecture': "AsymmetricMASt3R(pos_embed='RoPE100', patch_embed_cls='ManyAR_PatchEmbed', img_size=(512, 512), head_type='catmlp+dpt', output_mode='pts3d+desc24', depth_mode=('exp', -inf, inf), conf_mode=('exp', 1, inf), enc_embed_dim=1024, enc_depth=24, enc_num_heads=16, dec_embed_dim=768, dec_depth=12, dec_num_heads=12, two_confs=True, desc_conf_mode=('exp', 0, inf), use_intrinsics=False, use_extrinsics=False)" } } def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"): """Read and unpack the next bytes from a binary file. :param fid: :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc. :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. :param endian_character: Any of {@, =, <, >, !} :return: Tuple of read and unpacked values. """ data = fid.read(num_bytes) return struct.unpack(endian_character + format_char_sequence, data) def read_points3D_binary(path_to_model_file): """ Read Points3D from COLMAP binary file. Args: path_to_model_file: Path to COLMAP points3D.bin file Returns: points3D: Dictionary of Point3D objects """ points3D = {} with open(path_to_model_file, "rb") as fid: num_points = read_next_bytes(fid, 8, "Q")[0] for _ in range(num_points): binary_point_line_properties = read_next_bytes( fid, num_bytes=43, format_char_sequence="QdddBBBd" ) point3D_id = binary_point_line_properties[0] xyz = np.array(binary_point_line_properties[1:4]) rgb = np.array(binary_point_line_properties[4:7]) error = np.array(binary_point_line_properties[7]) track_length = read_next_bytes( fid, num_bytes=8, format_char_sequence="Q" )[0] track_elems = read_next_bytes( fid, num_bytes=8 * track_length, format_char_sequence="ii" * track_length, ) image_ids = np.array(tuple(map(int, track_elems[0::2]))) point2D_idxs = np.array(tuple(map(int, track_elems[1::2]))) points3D[point3D_id] = Point3D( id=point3D_id, xyz=xyz, rgb=rgb, error=error, image_ids=image_ids, point2D_idxs=point2D_idxs, ) return points3D def write_next_bytes(fid, data, format_char_sequence, endian_character="<"): """Pack and write to a binary file. :param fid: :param data: data to send, if multiple elements are sent at the same time, they should be encapsuled either in a list or a tuple :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. should be the same length as the data list or tuple :param endian_character: Any of {@, =, <, >, !} """ if isinstance(data, (list, tuple)): bytes = struct.pack(endian_character + format_char_sequence, *data) else: bytes = struct.pack(endian_character + format_char_sequence, data) fid.write(bytes) def write_points3D_binary(points3D, path_to_model_file): """ Write Points3D to COLMAP binary file. Args: points3D: Dictionary of Point3D objects path_to_model_file: Path to write COLMAP points3D.bin file """ with open(path_to_model_file, "wb") as fid: write_next_bytes(fid, len(points3D), "Q") for _, pt in points3D.items(): write_next_bytes(fid, pt.id, "Q") write_next_bytes(fid, pt.xyz.tolist(), "ddd") write_next_bytes(fid, pt.rgb.tolist(), "BBB") write_next_bytes(fid, pt.error, "d") track_length = pt.image_ids.shape[0] write_next_bytes(fid, track_length, "Q") for image_id, point2D_id in zip(pt.image_ids, pt.point2D_idxs): write_next_bytes(fid, [image_id, point2D_id], "ii") def load_model(model_name, device): """ Load the specified model. Args: model_name: Name of the model to load ('dust3r', 'mast3r') device: Device to load the model on Returns: loaded_model: The loaded model """ if model_name not in MODEL_CONFIGS: raise ValueError(f"Model {model_name} not supported. Choose from: {list(MODEL_CONFIGS.keys())}") config = MODEL_CONFIGS[model_name] model_path = config['path'] model_architecture = config['architecture'] # Create model instance based on architecture string model = eval(model_architecture) model.to(device) print(f'Loading pretrained model: {model_path}') checkpoint = torch.load(model_path, map_location=device) model.load_state_dict(checkpoint['model'], strict=False) model.eval() return model def get_transformation_between_cameras(target_poses, source_poses): """ Calculate transformation between source and target camera poses. Args: target_poses: Target camera poses (ground truth) source_poses: Source camera poses (predicted) Returns: scale: Scale factor rotation_matrix: Rotation matrix translation_shift: Translation vector """ source_translation_1 = source_poses[0][:3, 3] source_translation_2 = source_poses[1][:3, 3] source_rotation_1 = source_poses[0][:3, :3] source_rotation_2 = source_poses[1][:3, :3] target_translation_1 = target_poses[0][:3, 3] target_translation_2 = target_poses[1][:3, 3] target_rotation_1 = target_poses[0][:3, :3] target_rotation_2 = target_poses[1][:3, :3] # 1. Calculate scale: ratio of distances between corresponding positions (target vs source) source_distance = np.linalg.norm(source_translation_2 - source_translation_1) target_distance = np.linalg.norm(target_translation_2 - target_translation_1) scale = target_distance / source_distance # 2. Compute rotation matrix to align source with target rotation_matrix = source_rotation_1 @ np.linalg.inv(target_rotation_1) # 3. Calculate translation shift # since the first camera is always in the origin: translation_shift = target_translation_1 - source_translation_1 return scale, rotation_matrix, translation_shift def process_scene(scene_config, dataset, model, device): """ Process a scene with the given configuration. Args: scene_config: Configuration for the scene dataset: Dataset object model: Model to use for inference device: Device to run inference on Returns: points_cat: List of transformed point clouds colors_cat: List of point colors cameras_cat: List of camera poses """ # Extract scene configuration selected_indices = scene_config.get('selected_indices', []) if not selected_indices and scene_config.get('auto_select', False): # Generate indices automatically based on configuration num_images = scene_config.get('num_images', 120) distance = scene_config.get('distance', 10) offset = scene_config.get('offset', 0) step = scene_config.get('step', 3) selected_indices = [(i + j) + offset for i in range(0, num_images, distance) for j in (0, step) if i + j < num_images] # Make sure we have an even number of indices for pair processing if len(selected_indices) % 2 != 0: selected_indices = selected_indices[:-1] print(f"Processing scene with indices: {selected_indices}") # Get batch of data for selected indices batch = get_batch_colmap(dataset, scene_config.get('max_batch_size', 50), scene_id=scene_config.get('scene_id', 0), selected_indices=selected_indices) print(f"Batch size: {len(batch)}") predictions = [] camera_poses_gt_from_pred = [] # Process each pair of images for i in tqdm(range(0, len(selected_indices), 2), desc="Processing pairs"): print(f"Processing pair {i//2+1}/{len(selected_indices)//2}") pair_batch = batch[i:i+2] # Load images and make pairs images = load_images([pair_batch[0]['path'][0], pair_batch[1]['path'][0]], size=512) pairs = make_pairs(images, scene_graph='complete', prefilter=None, symmetrize=True) # Run inference output = inference(pairs, model, device, batch_size=scene_config.get('batch_size', 32)) # Global alignment scene = global_aligner(output, device=device, mode=GlobalAlignerMode.PointCloudOptimizer) scene.compute_global_alignment( init="mst", niter=scene_config.get('niter', 100), schedule=scene_config.get('schedule', 'cosine'), lr=scene_config.get('lr', 0.001) ) # Post-processing scene.mask_sky() scene.clean_pointcloud() predictions.append(scene) # Get ground truth camera poses gt_poses_0 = pair_batch[0]['camera_pose'] gt_poses_1 = pair_batch[1]['camera_pose'] gt_poses = torch.cat([gt_poses_0, gt_poses_1], dim=0).cpu() camera_poses_gt_from_pred.append(gt_poses) # Combine results points_cat = [] colors_cat = [] cameras_cat = [] for i, scene in enumerate(predictions): rgbimg = scene.imgs pts3d = to_numpy(scene.get_pts3d()) mask = to_numpy(scene.get_masks()) im_poses = scene.get_im_poses() # Concatenate points and colors points = np.concatenate([p[m] for p, m in zip(pts3d, mask)]) colors = np.concatenate([p[m] for p, m in zip(rgbimg, mask)]) * 255 # Transform to align with ground truth scale, rotation, translation = get_transformation_between_cameras( camera_poses_gt_from_pred[i].detach().cpu(), im_poses.detach().cpu() ) # Apply transformation to points points_scaled = points * scale points_translated = points_scaled @ rotation.numpy() + translation.numpy() points_cat.append(points_translated) colors_cat.append(colors) cameras_cat.append(camera_poses_gt_from_pred[i]) return points_cat, colors_cat, cameras_cat def main(): """ Main function to run the multi-scene reconstruction pipeline. """ # Define scene configurations scene_configs = [ # { # 'name': 'campus_hydro', # 'selected_indices': [0, 5, 10, 15, 20, 25, 30, 35] # }, { 'name': 'campus_core', 'selected_indices': [0, 5, 10, 15, 20, 25, 30, 35], 'voxel_size': 0.05 } # { # 'name': 'campus_hydro_secondary', # 'scene_id': 0, # 'selected_indices': [0, 5, 10, 15, 20, 25, 30, 35], # 'batch_size': 32, # 'schedule': 'cosine', # 'lr': 0.001, # 'niter': 100, # 'min_conf_thr': 0.5, # 'voxel_size': 0.05 # } ] # Setup paths base_path = "/l/users/sebastian.cavada/MBZUAI-Campus/global_OG" data_path = f"{base_path}/_data_global" output_path = f"{base_path}/_data_global_denser" # Parse arguments (using default values for now) args = argparse.Namespace( model='mast3r', device='cuda', batch_size=32 ) # Load model model = load_model(args.model, args.device) # Process each scene all_points = [] all_colors = [] for scene_config in scene_configs: print(f"\nLoading dataset for scene: {scene_config['name']}") # Load dataset dataset = CustomCOLMAP( size=200, split='train', images_path=f"{data_path}/images/", sfm_path=f"{data_path}/{scene_config['name']}/0", resolution=(512, 384), seed=777, ) print(f"\nProcessing scene: {scene_config['name']}") # Process scene points_cat, colors_cat, cameras_cat = process_scene( scene_config, dataset, model, args.device ) # Combine points and colors if points_cat: scene_points = np.concatenate(points_cat, axis=0) scene_colors = np.concatenate(colors_cat, axis=0) # Downsample if needed if scene_config.get('voxel_size', 0) > 0: scene_points, scene_colors, _ = voxel_downsample_with_colors( scene_points, scene_colors, voxel_size=scene_config.get('voxel_size', 0.05) ) all_points.append(scene_points) all_colors.append(scene_colors) print(f"Added {len(scene_points)} points from scene {scene_config['name']}") # Combine all scenes if all_points: points_total = np.concatenate(all_points, axis=0) colors_total = np.concatenate(all_colors, axis=0) print(f"Total points before final downsampling: {len(points_total)}") # Final downsampling total_points_downsampled, total_colors_downsampled, _ = voxel_downsample_with_colors( points_total, colors_total, voxel_size=0.05 ) print(f"Total points after final downsampling: {len(total_points_downsampled)}") # Read existing COLMAP points output_dir = f"{output_path}/campus_hydro" os.makedirs(output_dir, exist_ok=True) try: points_colmap = read_points3D_binary(f"{data_path}/campus_hydro/0/points3D.bin") print(f"Loaded {len(points_colmap)} existing points from COLMAP") except FileNotFoundError: points_colmap = {} print("No existing COLMAP points found, starting with empty set") # Find highest ID highest_id = max(points_colmap.keys()) if points_colmap else 0 # Add new points for xyz, rgb in zip(total_points_downsampled, total_colors_downsampled): xyz_np = np.array(xyz) rgb_int = rgb.astype(int) highest_id += 1 points_colmap[highest_id] = Point3D( id=highest_id, xyz=xyz_np, rgb=rgb_int, error=0, image_ids=np.array([]), point2D_idxs=np.array([]) ) print(f"Final point count: {len(points_colmap)}") # Write points to file write_points3D_binary(points_colmap, f"{output_dir}/points3D.bin") print(f"Points written to {output_dir}/points3D.bin") else: print("No points were processed. Check scene configurations.") if __name__ == "__main__": main()