{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":91498,"databundleVersionId":11655853},{"sourceType":"datasetVersion","sourceId":7884485,"datasetId":4628051,"databundleVersionId":7990559},{"sourceType":"datasetVersion","sourceId":12162657,"datasetId":7652929,"databundleVersionId":12698447},{"sourceType":"datasetVersion","sourceId":12148116,"datasetId":7651044,"databundleVersionId":12682545},{"sourceType":"modelInstanceVersion","sourceId":4534,"databundleVersionId":6346558,"modelInstanceId":3326,"modelId":986},{"sourceType":"kernelVersion","sourceId":311414320},{"sourceType":"kernelVersion","sourceId":311443146},{"sourceType":"kernelVersion","sourceId":311446373}],"dockerImageVersionId":31329,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"papermill":{"default_parameters":{},"duration":1848.324109,"end_time":"2026-04-13T03:49:17.661121","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2026-04-13T03:18:29.337012","version":"2.6.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## ","metadata":{"papermill":{"duration":0.005117,"end_time":"2026-04-13T03:18:33.784327","exception":false,"start_time":"2026-04-13T03:18:33.77921","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"**scene_graph: str = 'retrieval-20-25'**\n\n# **MASt3R-SfM IMC2025 Ong Sub (is_train:False)**","metadata":{"papermill":{"duration":0.005117,"end_time":"2026-04-13T03:18:33.784327","exception":false,"start_time":"2026-04-13T03:18:33.77921","status":"completed"},"tags":[]}},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.006553,"end_time":"2026-04-13T03:18:33.77355","exception":false,"start_time":"2026-04-13T03:18:33.766997","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\n\nclass CONFIG:\n # DEBUG Settings\n DRY_RUN = False\n DRY_RUN_MAX_IMAGES = 10\n\n # Pipeline settings\n NUM_CORES = 2\n MAST3R_MIN_PAIR = 15\n MATCH_CONF_TH = 1.001","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:42:31.148868Z","iopub.execute_input":"2026-04-19T05:42:31.149311Z","iopub.status.idle":"2026-04-19T05:42:31.156055Z","shell.execute_reply.started":"2026-04-19T05:42:31.149284Z","shell.execute_reply":"2026-04-19T05:42:31.155534Z"},"papermill":{"duration":0.01364,"end_time":"2026-04-13T03:18:33.813804","exception":false,"start_time":"2026-04-13T03:18:33.800164","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install torch torchvision torchaudio --no-index --find-links=/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r-wheels\n\n!pip install faiss-gpu-cu12 --no-index --find-links=/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r-wheels\n\n!pip install --no-index --find-links=/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r-wheels \\\n -r /kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/requirements.txt \\\n -r /kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/dust3r/requirements.txt \\\n -r /kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/dust3r/requirements_optional.txt\n\n!pip install --no-index /kaggle/input/imc2024-packages-lightglue-rerun-kornia/* --no-deps\n","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2026-04-19T05:42:31.157918Z","iopub.execute_input":"2026-04-19T05:42:31.158204Z","iopub.status.idle":"2026-04-19T05:42:57.598505Z","shell.execute_reply.started":"2026-04-19T05:42:31.158168Z","shell.execute_reply":"2026-04-19T05:42:57.597831Z"},"papermill":{"duration":189.000504,"end_time":"2026-04-13T03:21:42.819334","exception":false,"start_time":"2026-04-13T03:18:33.81883","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport sys\nprint(sys.version)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:42:57.599762Z","iopub.execute_input":"2026-04-19T05:42:57.600071Z","iopub.status.idle":"2026-04-19T05:42:57.604992Z","shell.execute_reply.started":"2026-04-19T05:42:57.600044Z","shell.execute_reply":"2026-04-19T05:42:57.604169Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install --no-index /kaggle/input/notebooks/stpeteishii/pycolmap-4-0-3-cp312/dist/pycolmap-4.0.3-cp312-cp312-manylinux_2_28_x86_64.whl --no-deps\n#!pip install --no-index /kaggle/input/pycolmap3-11/pycolmap-3.11.1-cp311-cp311-manylinux_2_28_x86_64.whl --no-deps\n\nimport pycolmap\n!pip show pycolmap\nprint(os.listdir(os.path.dirname(pycolmap.__file__)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:42:57.606152Z","iopub.execute_input":"2026-04-19T05:42:57.606561Z","iopub.status.idle":"2026-04-19T05:43:01.728458Z","shell.execute_reply.started":"2026-04-19T05:42:57.606524Z","shell.execute_reply":"2026-04-19T05:43:01.727467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install --no-index /kaggle/input/notebooks/stpeteishii/faiss-gpu-cu12-nvidia-cuda-runtime-cu12/faiss_wheels/faiss_gpu_cu12-1.14.1.post1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl --no-deps\n\n!pip install --no-index /kaggle/input/notebooks/stpeteishii/faiss-gpu-cu12-nvidia-cuda-runtime-cu12/faiss_wheels/nvidia_cublas_cu12-12.6.4.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl --no-deps\n\n!pip install --no-index /kaggle/input/notebooks/stpeteishii/faiss-gpu-cu12-nvidia-cuda-runtime-cu12/faiss_wheels/nvidia_cuda_runtime_cu12-12.9.79-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl --no-deps\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:01.729946Z","iopub.execute_input":"2026-04-19T05:43:01.730318Z","iopub.status.idle":"2026-04-19T05:43:20.192313Z","shell.execute_reply.started":"2026-04-19T05:43:01.730289Z","shell.execute_reply":"2026-04-19T05:43:20.191372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sys.path.insert(0, \"/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r\")\nsys.path.insert(0, '/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/asmk')\nsys.path.insert(0, '/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/dust3r/croco/models/curope')","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:20.193583Z","iopub.execute_input":"2026-04-19T05:43:20.19403Z","iopub.status.idle":"2026-04-19T05:43:20.198328Z","shell.execute_reply.started":"2026-04-19T05:43:20.193978Z","shell.execute_reply":"2026-04-19T05:43:20.197716Z"},"papermill":{"duration":0.016495,"end_time":"2026-04-13T03:21:42.847324","exception":false,"start_time":"2026-04-13T03:21:42.830829","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!rm -rf /kaggle/working/visualization_output\n!rm -rf /kaggle/working/temp\n!rm -rf /kaggle/working/result","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:20.201559Z","iopub.execute_input":"2026-04-19T05:43:20.201754Z","iopub.status.idle":"2026-04-19T05:43:20.549142Z","shell.execute_reply.started":"2026-04-19T05:43:20.201735Z","shell.execute_reply":"2026-04-19T05:43:20.548028Z"},"papermill":{"duration":0.355994,"end_time":"2026-04-13T03:21:43.21364","exception":false,"start_time":"2026-04-13T03:21:42.857646","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:20.550628Z","iopub.execute_input":"2026-04-19T05:43:20.55101Z","iopub.status.idle":"2026-04-19T05:43:22.999412Z","shell.execute_reply.started":"2026-04-19T05:43:20.550969Z","shell.execute_reply":"2026-04-19T05:43:22.998596Z"},"papermill":{"duration":2.003112,"end_time":"2026-04-13T03:21:45.227179","exception":false,"start_time":"2026-04-13T03:21:43.224067","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\nimport os\nimport numpy as np\nimport torch\nimport dataclasses\n\ndef seed_everything(seed: int = 42):\n \"\"\"Set seed for reproducibility across random, numpy, torch (CPU + CUDA).\"\"\"\n random.seed(seed)\n np.random.seed(seed)\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed) # for multi-GPU\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\nseed_everything()","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:23.001385Z","iopub.execute_input":"2026-04-19T05:43:23.00199Z","iopub.status.idle":"2026-04-19T05:43:27.759347Z","shell.execute_reply.started":"2026-04-19T05:43:23.001958Z","shell.execute_reply":"2026-04-19T05:43:27.758751Z"},"papermill":{"duration":1.792307,"end_time":"2026-04-13T03:21:47.030359","exception":false,"start_time":"2026-04-13T03:21:45.238052","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sys.path.append('/kaggle/input/datasets/yuanlin08/pycolmap3-11-imc-utils')\n\n# from database import *\nfrom h5_to_db import *\n\nimport sqlite3\nimport numpy as np\n\ndef import_into_colmap(img_dir, feature_dir, database_path):\n def log(msg):\n print(msg, flush=True)\n\n SIMPLE_RADIAL_ID = int(pycolmap.CameraModelId.SIMPLE_RADIAL)\n log(f\">>> SIMPLE_RADIAL model ID: {SIMPLE_RADIAL_ID}\")\n\n conn = sqlite3.connect(database_path)\n c = conn.cursor()\n\n c.executescript(\"\"\"\n CREATE TABLE IF NOT EXISTS cameras (\n camera_id INTEGER PRIMARY KEY AUTOINCREMENT,\n model INTEGER NOT NULL,\n width INTEGER NOT NULL,\n height INTEGER NOT NULL,\n params BLOB,\n prior_focal_length INTEGER NOT NULL);\n CREATE TABLE IF NOT EXISTS images (\n image_id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL UNIQUE,\n camera_id INTEGER NOT NULL,\n prior_qw REAL, prior_qx REAL, prior_qy REAL, prior_qz REAL,\n prior_tx REAL, prior_ty REAL, prior_tz REAL);\n CREATE TABLE IF NOT EXISTS keypoints (\n image_id INTEGER PRIMARY KEY,\n rows INTEGER NOT NULL,\n cols INTEGER NOT NULL,\n data BLOB);\n CREATE TABLE IF NOT EXISTS matches (\n pair_id INTEGER PRIMARY KEY,\n rows INTEGER NOT NULL,\n cols INTEGER NOT NULL,\n data BLOB);\n CREATE TABLE IF NOT EXISTS two_view_geometries (\n pair_id INTEGER PRIMARY KEY,\n rows INTEGER NOT NULL,\n cols INTEGER NOT NULL,\n data BLOB,\n config INTEGER,\n F BLOB, E BLOB, H BLOB,\n qvec BLOB, tvec BLOB);\n CREATE TABLE IF NOT EXISTS descriptors (\n image_id INTEGER PRIMARY KEY,\n rows INTEGER NOT NULL,\n cols INTEGER NOT NULL,\n data BLOB);\n \"\"\")\n conn.commit()\n log(\">>> DB schema created\")\n\n fname_to_id = {}\n\n with h5py.File(f'{feature_dir}/keypoints.h5', 'r') as f_kp:\n for filename in f_kp.keys():\n img_path = os.path.join(img_dir, filename)\n img = Image.open(img_path)\n w, h = img.size\n f = float(max(w, h))\n params = np.array([f, w/2.0, h/2.0, 0.0], dtype=np.float64)\n c.execute(\n \"INSERT INTO cameras (model, width, height, params, prior_focal_length) VALUES (?, ?, ?, ?, ?)\",\n (SIMPLE_RADIAL_ID, int(w), int(h), params.tobytes(), 0)\n )\n camera_id = c.lastrowid\n c.execute(\n \"INSERT INTO images (name, camera_id) VALUES (?, ?)\",\n (filename, camera_id)\n )\n image_id = c.lastrowid\n fname_to_id[filename] = image_id\n kpts = f_kp[filename][()].astype(np.float32)\n c.execute(\n \"INSERT INTO keypoints (image_id, rows, cols, data) VALUES (?, ?, ?, ?)\",\n (image_id, kpts.shape[0], kpts.shape[1], kpts.tobytes())\n )\n log(f\">>> inserted: {filename}, cam={camera_id}, img={image_id}, kpts={kpts.shape[0]}\")\n\n conn.commit()\n log(\">>> keypoints done, starting matches\")\n\n def image_ids_to_pair_id(id1, id2):\n if id1 > id2:\n id1, id2 = id2, id1\n return id1 * 2147483647 + id2\n\n with h5py.File(f'{feature_dir}/matches.h5', 'r') as f_match:\n for img1 in f_match.keys():\n for img2 in f_match[img1].keys():\n matches = f_match[img1][img2][()].astype(np.uint32)\n id1 = fname_to_id.get(img1)\n id2 = fname_to_id.get(img2)\n if id1 is not None and id2 is not None:\n pair_id = image_ids_to_pair_id(id1, id2)\n c.execute(\n \"INSERT OR IGNORE INTO matches (pair_id, rows, cols, data) VALUES (?, ?, ?, ?)\",\n (pair_id, matches.shape[0], matches.shape[1], matches.tobytes())\n )\n\n conn.commit()\n conn.close()\n log(\">>> DB closed\")","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:27.760223Z","iopub.execute_input":"2026-04-19T05:43:27.760608Z","iopub.status.idle":"2026-04-19T05:43:27.95794Z","shell.execute_reply.started":"2026-04-19T05:43:27.760566Z","shell.execute_reply":"2026-04-19T05:43:27.957298Z"},"papermill":{"duration":26.230867,"end_time":"2026-04-13T03:22:13.272067","exception":false,"start_time":"2026-04-13T03:21:47.0412","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import metric\nfrom pycolmap import verify_matches, TwoViewGeometryOptions\nfrom fastprogress import progress_bar\n\nfrom tqdm import tqdm\nfrom time import time, sleep\nimport gc\nimport h5py\nimport dataclasses\nimport pandas as pd\nfrom IPython.display import clear_output\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom PIL import Image\n\nimport cv2\nimport torch\nimport torch.nn.functional as F\nfrom transformers import AutoImageProcessor, AutoModel","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:27.958724Z","iopub.execute_input":"2026-04-19T05:43:27.959018Z","iopub.status.idle":"2026-04-19T05:43:45.20758Z","shell.execute_reply.started":"2026-04-19T05:43:27.958995Z","shell.execute_reply":"2026-04-19T05:43:45.206984Z"},"papermill":{"duration":26.230867,"end_time":"2026-04-13T03:22:13.272067","exception":false,"start_time":"2026-04-13T03:21:47.0412","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pycolmap\ndb = pycolmap.Database()\n\n#print([m for m in dir(db) if not m.startswith('_')])\n#print(dir(pycolmap.Database))\n#print(dir(pycolmap.Camera))\n#print(pycolmap.CameraModelId.__members__) \n#print(pycolmap.Camera.create.__doc__) \n#print(pycolmap.Camera.create_from_model_id.__doc__)\n#print(pycolmap.Camera.__init__.__doc__)\n\nprint(db.write_camera.__doc__)\nprint(db.write_image.__doc__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.208458Z","iopub.execute_input":"2026-04-19T05:43:45.209127Z","iopub.status.idle":"2026-04-19T05:43:45.213874Z","shell.execute_reply.started":"2026-04-19T05:43:45.209098Z","shell.execute_reply":"2026-04-19T05:43:45.213107Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"_ = verify_matches\n_ = TwoViewGeometryOptions()","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.229642Z","iopub.status.idle":"2026-04-19T05:43:45.229998Z","shell.execute_reply.started":"2026-04-19T05:43:45.229779Z","shell.execute_reply":"2026-04-19T05:43:45.229798Z"},"papermill":{"duration":0.016261,"end_time":"2026-04-13T03:22:13.299256","exception":false,"start_time":"2026-04-13T03:22:13.282995","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from mast3r.model import AsymmetricMASt3R\nfrom mast3r.fast_nn import fast_reciprocal_NNs, extract_correspondences_nonsym\n\nimport mast3r.utils.path_to_dust3r\nfrom dust3r.inference import inference\nfrom dust3r.utils.image import load_images","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.231128Z","iopub.status.idle":"2026-04-19T05:43:45.231835Z","shell.execute_reply.started":"2026-04-19T05:43:45.231578Z","shell.execute_reply":"2026-04-19T05:43:45.231608Z"},"papermill":{"duration":0.459918,"end_time":"2026-04-13T03:22:13.769532","exception":false,"start_time":"2026-04-13T03:22:13.309614","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!rm -rf /kaggle/working/result","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.23322Z","iopub.status.idle":"2026-04-19T05:43:45.233632Z","shell.execute_reply.started":"2026-04-19T05:43:45.23342Z","shell.execute_reply":"2026-04-19T05:43:45.233448Z"},"papermill":{"duration":0.152715,"end_time":"2026-04-13T03:22:13.932941","exception":false,"start_time":"2026-04-13T03:22:13.780226","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Configuration\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu' # Automatically use GPU if available\nprint(f\"Using device: {device}\")\n\nschedule = 'cosine' # These seem to be unused in the provided snippet, but keep for context\nlr = 0.01\nniter = 300\nlocal_model_path = \"/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/checkpoints/\"\nlocal_model_directory = \"/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth\"\nretrival_model_dir = '/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_trainingfree.pth'","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.235139Z","iopub.status.idle":"2026-04-19T05:43:45.235499Z","shell.execute_reply.started":"2026-04-19T05:43:45.235298Z","shell.execute_reply":"2026-04-19T05:43:45.235325Z"},"papermill":{"duration":33.002614,"end_time":"2026-04-13T03:22:46.950168","exception":false,"start_time":"2026-04-13T03:22:13.947554","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Now, we manually call `load_model` as suggested by `mast3r/model.py`'s `from_pretrained` logic\nfrom mast3r.model import load_model # Assuming load_model is defined in mast3r/model.py or accessible\n\nimport torch\nimport argparse\ntorch.serialization.add_safe_globals([argparse.Namespace])\n\nprint(f\"Loading model from local path: {local_model_directory}\")\nmast3r_model = load_model(local_model_directory, device=device) # Pass device to load_model\n\nprint(\"Model loaded successfully.\")","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.236727Z","iopub.status.idle":"2026-04-19T05:43:45.237068Z","shell.execute_reply.started":"2026-04-19T05:43:45.236922Z","shell.execute_reply":"2026-04-19T05:43:45.236959Z"},"papermill":{"duration":33.002614,"end_time":"2026-04-13T03:22:46.950168","exception":false,"start_time":"2026-04-13T03:22:13.947554","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.237598Z","iopub.status.idle":"2026-04-19T05:43:45.237993Z","shell.execute_reply.started":"2026-04-19T05:43:45.237832Z","shell.execute_reply":"2026-04-19T05:43:45.237862Z"},"papermill":{"duration":1.959817,"end_time":"2026-04-13T03:22:48.92086","exception":false,"start_time":"2026-04-13T03:22:46.961043","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def transform_keypoints_to_original(\n kpts_crop: np.ndarray,\n original_size: tuple[int, int], #H,W\n size_param: int = 512, # The 'size' parameter (e.g., 224, 512) used in load_images\n square_ok: bool = False\n) -> np.ndarray:\n \"\"\"\n Transforms keypoint coordinates from a DUST3R-processed (resized and cropped)\n image back to the original image's coordinate system.\n\n Args:\n kpts_crop: A NumPy array of shape (N, 2) where N is the number of keypoints,\n and each row is (x, y) coordinate on the processed image.\n original_size: A tuple (original_width, original_height) of the original image.\n resized_crop_size: A tuple (processed_width, processed_height) of the\n image after resizing and cropping (i.e., the dimensions\n of the input image to DUST3R). This is W2, H2 from the\n load_images function.\n size_param: The 'size' parameter (e.g., 224, 512) used in the\n original load_images function.\n square_ok: The 'square_ok' parameter used in the original load_images function.\n\n Returns:\n A NumPy array of shape (N, 2) with the transformed keypoint coordinates\n on the original image.\n \"\"\"\n # print(f\"original_size: {original_size}\")\n original_height, original_width = original_size\n original_height = float(original_height)\n original_width = float(original_width)\n\n # --- 1. Determine the dimensions after resizing but *before* cropping (W_res, H_res) ---\n # This logic mirrors the _resize_pil_image call in load_images\n if size_param == 224:\n # Target long side is used for resizing.\n target_long_side = round(size_param * max(original_width / original_height, original_height / original_width))\n if original_width >= original_height:\n W_res = target_long_side\n H_res = round(original_height * (target_long_side / original_width))\n else:\n H_res = target_long_side\n W_res = round(original_width * (target_long_side / original_height))\n else:\n # Long side is resized to size_param.\n if original_width >= original_height:\n W_res = size_param\n H_res = round(original_height * (size_param / original_width))\n else:\n H_res = size_param\n W_res = round(original_width * (size_param / original_height))\n\n # print(f\"H_res, W_res: {H_res}_{W_res}\")\n\n # --- 2. Calculate the cropping offsets used during processing ---\n cx, cy = W_res // 2, H_res // 2\n\n if size_param == 224:\n half = min(cx, cy)\n crop_left = cx - half\n crop_top = cy - half\n else:\n halfw = ((2 * cx) // 16) * 8\n halfh = ((2 * cy) // 16) * 8\n if not square_ok and W_res == H_res:\n halfh = round(3 * halfw / 4)\n \n crop_left = cx - halfw\n crop_top = cy - halfh\n\n # --- 4. Reverse the Resizing ---\n # Determine the actual scaling factor applied during the initial resize\n if original_width >= original_height:\n scale_factor = size_param / original_width\n else:\n scale_factor = size_param / original_height\n # --- 3. Reverse the Cropping ---\n # Add the crop offsets to the keypoints from the cropped image\n # print(crop_left, crop_top)\n kpts_resized = kpts_crop.astype(float) # Ensure float for accurate division\n kpts_resized[:, 0] = kpts_resized[:, 0] + crop_left\n kpts_resized[:, 1] = kpts_resized[:, 1] + crop_top\n\n # Divide by the scale factor to get original coordinates\n kpts_original = kpts_resized/ scale_factor \n\n return kpts_original","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.239437Z","iopub.status.idle":"2026-04-19T05:43:45.239707Z","shell.execute_reply.started":"2026-04-19T05:43:45.239573Z","shell.execute_reply":"2026-04-19T05:43:45.239588Z"},"papermill":{"duration":0.021945,"end_time":"2026-04-13T03:22:48.953998","exception":false,"start_time":"2026-04-13T03:22:48.932053","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\n\ndef draw_matches_on_original_images(img_path1, img_path2, matches_im0, matches_im1, save_path, n_viz=100):\n \"\"\"\n Draws matching lines between two original images and saves the result.\n\n Args:\n img_path1 (str): Path to the first original image.\n img_path2 (str): Path to the second original image.\n matches_im0 (numpy.ndarray): (N, 2) array of matching point coordinates on image 1.\n matches_im1 (numpy.ndarray): (N, 2) array of matching point coordinates on image 2.\n save_path (str): Directory path to save the output image.\n n_viz (int): Number of matches to visualize (default is 100).\n \"\"\"\n os.makedirs(save_path, exist_ok=True)\n\n # Load images\n img0 = cv2.imread(img_path1)\n img1 = cv2.imread(img_path2)\n key1 = os.path.basename(img_path1)\n key2 = os.path.basename(img_path2)\n\n if img0 is None or img1 is None:\n print(f\"Error: Cannot load {img_path1} or {img_path2}\")\n return\n\n # Convert BGR to RGB for consistent color mapping\n img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)\n\n # Create canvas\n H0, W0 = img0.shape[:2]\n H1, W1 = img1.shape[:2]\n canvas_h = max(H0, H1)\n canvas = np.zeros((canvas_h, W0 + W1, 3), dtype=np.uint8)\n canvas[:H0, :W0] = img0\n canvas[:H1, W0:] = img1\n\n # Select subset of matches for visualization\n num_matches = min(len(matches_im0), n_viz)\n idxs = np.round(np.linspace(0, len(matches_im0) - 1, num_matches)).astype(int)\n cmap = plt.get_cmap('rainbow')\n\n for i, idx in enumerate(idxs):\n (x0, y0) = matches_im0[idx]\n (x1, y1) = matches_im1[idx]\n \n # Generate color from colormap\n color = tuple((np.array(cmap(i / num_matches))[:3] * 255).astype(int).tolist())\n\n pt1 = (int(round(x0)), int(round(y0)))\n pt2 = (int(round(x1 + W0)), int(round(y1)))\n\n # Draw lines and points\n cv2.line(canvas, pt1, pt2, color, thickness=1, lineType=cv2.LINE_AA)\n cv2.circle(canvas, pt1, 2, color, -1, lineType=cv2.LINE_AA)\n cv2.circle(canvas, pt2, 2, color, -1, lineType=cv2.LINE_AA)\n\n # Save the output (Convert back to BGR for OpenCV saving)\n output_filename = os.path.join(save_path, f\"{key1}_{key2}.jpg\")\n cv2.imwrite(output_filename, cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR))\n # print(f\"Saved match debug image to {output_filename}\")","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.24181Z","iopub.status.idle":"2026-04-19T05:43:45.242249Z","shell.execute_reply.started":"2026-04-19T05:43:45.242056Z","shell.execute_reply":"2026-04-19T05:43:45.242084Z"},"papermill":{"duration":0.066871,"end_time":"2026-04-13T03:22:49.031343","exception":false,"start_time":"2026-04-13T03:22:48.964472","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls /kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/asmk/asmk","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.243653Z","iopub.status.idle":"2026-04-19T05:43:45.244041Z","shell.execute_reply.started":"2026-04-19T05:43:45.24385Z","shell.execute_reply":"2026-04-19T05:43:45.243875Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys, importlib.util\n\nbase = \"/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/asmk/asmk\"\n\ndef _load_so(module_name, path):\n spec = importlib.util.spec_from_file_location(module_name, path)\n mod = importlib.util.module_from_spec(spec)\n sys.modules[module_name] = mod\n spec.loader.exec_module(mod)\n return mod\n\n_load_so(\"asmk.hamming\", f\"{base}/hamming.cpython-312-x86_64-linux-gnu.so\")\n_load_so(\"asmk.functional\", f\"{base}/functional.py\")\n_load_so(\"asmk.io_helpers\", f\"{base}/io_helpers.py\")\n\nsys.path.insert(0, \"/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r/asmk\")\nimport asmk\n\nsys.path.insert(0, \"/kaggle/input/notebooks/stpeteishii/mast3r-cp312/mast3r\")\nfrom mast3r.retrieval.processor import Retriever","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.24547Z","iopub.status.idle":"2026-04-19T05:43:45.24585Z","shell.execute_reply.started":"2026-04-19T05:43:45.245644Z","shell.execute_reply":"2026-04-19T05:43:45.245668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import faiss\nimport asmk.index as asmk_index\nprint(dir(asmk_index))\n\ndef _cpu_index(self, dim):\n return faiss.IndexFlatL2(dim)\n\nasmk_index.FaissGpuL2Index.create_index = lambda self, points: faiss.IndexFlatL2(points.shape[1])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.247505Z","iopub.status.idle":"2026-04-19T05:43:45.247889Z","shell.execute_reply.started":"2026-04-19T05:43:45.247687Z","shell.execute_reply":"2026-04-19T05:43:45.247712Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import asmk.kernel as asmk_kernel\nprint(dir(asmk_kernel))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.249312Z","iopub.status.idle":"2026-04-19T05:43:45.24985Z","shell.execute_reply.started":"2026-04-19T05:43:45.249579Z","shell.execute_reply":"2026-04-19T05:43:45.24962Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import asmk.index as asmk_index\nimport inspect\nprint(inspect.getsource(asmk_index.FaissL2Index))\nprint(\"---\")\nprint(inspect.getsource(asmk_index.FaissGpuL2Index))\nprint(\"---\")\nprint(inspect.getsource(asmk_index.initialize_index))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.250986Z","iopub.status.idle":"2026-04-19T05:43:45.251257Z","shell.execute_reply.started":"2026-04-19T05:43:45.251138Z","shell.execute_reply":"2026-04-19T05:43:45.251155Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_img_pairs_exhaustive(img_fnames):\n index_pairs = []\n for i in range(len(img_fnames)):\n for j in range(i+1, len(img_fnames)):\n index_pairs.append((i,j))\n return index_pairs","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.252489Z","iopub.status.idle":"2026-04-19T05:43:45.252856Z","shell.execute_reply.started":"2026-04-19T05:43:45.252655Z","shell.execute_reply":"2026-04-19T05:43:45.252671Z"},"papermill":{"duration":0.022922,"end_time":"2026-04-13T03:22:51.21134","exception":false,"start_time":"2026-04-13T03:22:51.188418","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport torch\nimport PIL\nimport numpy as np # Ensure numpy is imported for checking np.ndarray\nfrom PIL import Image\nfrom mast3r.retrieval.processor import Retriever\nfrom mast3r.image_pairs import make_pairs\nfrom mast3r.model import AsymmetricMASt3R\n\n\ndef get_image_list(images_path):\n \"\"\"\n Scans the specified path for all image files and returns their relative paths.\n Skips unidentifiable or corrupt image files.\n \"\"\"\n file_list = [os.path.relpath(os.path.join(dirpath, filename), images_path)\n for dirpath, _, filenames in os.walk(images_path)\n for filename in filenames]\n file_list = sorted(file_list)\n image_list = []\n for filename in file_list:\n try:\n with Image.open(os.path.join(images_path, filename)) as im:\n im.verify() # Verify image file integrity\n image_list.append(filename)\n except (OSError, PIL.UnidentifiedImageError):\n print(f'Skipping invalid image file: {filename}')\n return image_list","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.254168Z","iopub.status.idle":"2026-04-19T05:43:45.254581Z","shell.execute_reply.started":"2026-04-19T05:43:45.254337Z","shell.execute_reply":"2026-04-19T05:43:45.254377Z"},"papermill":{"duration":0.228819,"end_time":"2026-04-13T03:22:51.457893","exception":false,"start_time":"2026-04-13T03:22:51.229074","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.255896Z","iopub.status.idle":"2026-04-19T05:43:45.256168Z","shell.execute_reply.started":"2026-04-19T05:43:45.25605Z","shell.execute_reply":"2026-04-19T05:43:45.256066Z"},"papermill":{"duration":1.978426,"end_time":"2026-04-13T03:22:53.455623","exception":false,"start_time":"2026-04-13T03:22:51.477197","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def make_pair_with_mast3r_return_pairs(\n image_dir: str,\n weights_path: str, # Path to the AsymmetricMASt3R model weights\n retrieval_model_path: str, # Path to the retrieval model (e.g., \"trainingfree.pth\")\n scene_graph: str = 'retrieval-20-25',\n device: str = 'cuda'\n):\n \"\"\"\n Generates image pairs using MASt3R + ASMK retrieval, returning a list of pairs.\n\n Args:\n image_dir (str): Path to the directory containing images.\n weights_path (str): Path to the AsymmetricMASt3R model weights.\n retrieval_model_path (str): Path to the retrieval model (e.g., \"trainingfree.pth\").\n scene_graph (str, optional): String defining the scene graph construction strategy. \n Defaults to 'retrieval-20-1-10-1'.\n device (str, optional): PyTorch device to use ('cuda' or 'cpu'). Defaults to 'cuda'.\n\n Returns:\n sorted_pairs: List[Tuple[str, str]], where each tuple contains \n the relative paths of the paired images (img1, img2).\n \"\"\"\n print(\"🖼️ Scanning images...\")\n imgs = get_image_list(image_dir)\n imgs_fp = [os.path.join(image_dir, f) for f in imgs]\n\n if not imgs:\n print(\"⚠️ No valid images found in the directory. Returning empty pairs.\")\n return []\n\n print(f\"⚙️ Loading backbone model from {weights_path}...\")\n backbone = AsymmetricMASt3R.from_pretrained(weights_path).to(device).eval()\n\n # print(\"🔍 Running ASMK retrieval...\")\n retriever = Retriever(retrieval_model_path, backbone=backbone)\n \n with torch.no_grad():\n sim_matrix_np = retriever(imgs_fp) \n \n # Cleanup GPU cache\n del retriever\n del backbone \n torch.cuda.empty_cache()\n\n raw_pairs = make_pairs(imgs, scene_graph, prefilter=None, symmetrize=True, sim_mat=sim_matrix_np)\n\n sorted_pairs = sorted(set(tuple(sorted([a, b])) for a, b in raw_pairs))\n\n print(f\"✅ Generated {len(sorted_pairs)} unique image pairs.\")\n return sorted_pairs","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.257022Z","iopub.status.idle":"2026-04-19T05:43:45.257331Z","shell.execute_reply.started":"2026-04-19T05:43:45.257204Z","shell.execute_reply":"2026-04-19T05:43:45.257222Z"},"papermill":{"duration":0.027648,"end_time":"2026-04-13T03:22:53.502112","exception":false,"start_time":"2026-04-13T03:22:53.474464","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import kornia as K\nimport kornia.feature as KF\nimport pycolmap\nprint(f\"pycolmap version: {pycolmap.__version__}\")","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.258065Z","iopub.status.idle":"2026-04-19T05:43:45.258341Z","shell.execute_reply.started":"2026-04-19T05:43:45.258218Z","shell.execute_reply":"2026-04-19T05:43:45.258234Z"},"papermill":{"duration":0.988127,"end_time":"2026-04-13T03:22:54.508134","exception":false,"start_time":"2026-04-13T03:22:53.520007","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_img_pairs_exhaustive(img_fnames):\n index_pairs = []\n for i in range(len(img_fnames)):\n for j in range(i+1, len(img_fnames)):\n index_pairs.append((i,j))\n return index_pairs","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.259663Z","iopub.status.idle":"2026-04-19T05:43:45.260102Z","shell.execute_reply.started":"2026-04-19T05:43:45.259889Z","shell.execute_reply":"2026-04-19T05:43:45.259916Z"},"papermill":{"duration":0.023027,"end_time":"2026-04-13T03:22:54.550073","exception":false,"start_time":"2026-04-13T03:22:54.527046","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Collect vital info from the dataset\n\n@dataclasses.dataclass\nclass Prediction:\n image_id: str | None # A unique identifier for the row -- unused otherwise. Used only on the hidden test set.\n dataset: str\n filename: str\n cluster_index: int | None = None\n rotation: np.ndarray | None = None\n translation: np.ndarray | None = None\n\n# Set is_train=True to run the notebook on the training data.\n# Set is_train=False if submitting an entry to the competition (test data is hidden, and different from what you see on the \"test\" folder).\nis_train = False\ndata_dir = '/kaggle/input/competitions/image-matching-challenge-2025'\nworkdir = '/kaggle/working/result/'\nos.makedirs(workdir, exist_ok=True)\n\nif is_train:\n sample_submission_csv = os.path.join(data_dir, 'train_labels.csv')\nelse:\n sample_submission_csv = os.path.join(data_dir, 'sample_submission.csv')\n\nsamples = {}\ncompetition_data = pd.read_csv(sample_submission_csv)\nfor _, row in competition_data.iterrows():\n # Note: For the test data, the \"scene\" column has no meaning, and the rotation_matrix and translation_vector columns are random.\n if row.dataset not in samples:\n samples[row.dataset] = []\n samples[row.dataset].append(\n Prediction(\n image_id=None if is_train else row.image_id,\n dataset=row.dataset,\n filename=row.image\n )\n )\n\nfor dataset in samples:\n print(f'Dataset \"{dataset}\" -> num_images={len(samples[dataset])}')","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.261129Z","iopub.status.idle":"2026-04-19T05:43:45.261621Z","shell.execute_reply.started":"2026-04-19T05:43:45.261435Z","shell.execute_reply":"2026-04-19T05:43:45.261462Z"},"papermill":{"duration":0.176962,"end_time":"2026-04-13T03:22:54.744889","exception":false,"start_time":"2026-04-13T03:22:54.567927","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import multiprocessing\nimport torch\nimport matplotlib.pyplot as plt\nimport cv2","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.262806Z","iopub.status.idle":"2026-04-19T05:43:45.263047Z","shell.execute_reply.started":"2026-04-19T05:43:45.262937Z","shell.execute_reply":"2026-04-19T05:43:45.262952Z"},"papermill":{"duration":0.022062,"end_time":"2026-04-13T03:22:54.785097","exception":false,"start_time":"2026-04-13T03:22:54.763035","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom typing import Dict, Tuple\nfrom collections import defaultdict\n\ndef unify_keypoints_and_matches(\n out_match: Dict[str, Dict[str, np.ndarray]], \n round_digits: int = 1\n) -> Tuple[\n Dict[str, np.ndarray], # global_keypoints[img] = (N, 2)\n Dict[Tuple[str, str], np.ndarray] # global_matches[(img1, img2)] = (M, 2) (using global IDs)\n]:\n \"\"\"\n Unifies keypoints across multiple images and converts local matches to global ID matches.\n\n Args:\n out_match: Dictionary where out_match[img1][img2] contains matching coordinates (x1, y1, x2, y2).\n round_digits: Number of decimal places to round coordinates for uniqueness matching.\n\n Returns:\n global_keypoints: A dictionary mapping image names to unique coordinate arrays.\n global_matches: A dictionary mapping image pairs to arrays of corresponding global keypoint IDs.\n \"\"\"\n \n # Step 1: Collect all coordinates for each image\n keypoints_per_image = defaultdict(list)\n\n for img1, subdict in out_match.items():\n for img2, match in subdict.items():\n pts1 = np.round(match[:, :2], decimals=round_digits)\n pts2 = np.round(match[:, 2:], decimals=round_digits)\n keypoints_per_image[img1].append(pts1)\n keypoints_per_image[img2].append(pts2)\n\n # Step 2: Build unique keypoints and coordinate-to-ID mapping for each image\n global_keypoints = {}\n coord_to_id = {}\n\n for img, kpt_list in keypoints_per_image.items():\n # Concatenate all points found for this image and round them\n all_pts = np.concatenate(kpt_list, axis=0)\n all_pts = np.round(all_pts, decimals=round_digits)\n \n # Get unique coordinates\n unique_pts = np.unique(all_pts, axis=0)\n global_keypoints[img] = unique_pts\n\n # Create mapping: coordinate tuple -> global index ID\n coord_to_id[img] = {tuple(pt): idx for idx, pt in enumerate(unique_pts)}\n\n # Step 3: Convert coordinate pairs into global ID pairs\n global_matches = {}\n\n for img1, subdict in out_match.items():\n for img2, match in subdict.items():\n pts1 = np.round(match[:, :2], decimals=round_digits)\n pts2 = np.round(match[:, 2:], decimals=round_digits)\n\n # Look up global IDs using the coordinate-to-ID map\n ids1 = np.array([coord_to_id[img1][tuple(pt)] for pt in pts1])\n ids2 = np.array([coord_to_id[img2][tuple(pt)] for pt in pts2])\n\n global_matches[(img1, img2)] = np.stack([ids1, ids2], axis=1)\n\n return global_keypoints, global_matches\n","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.263836Z","iopub.status.idle":"2026-04-19T05:43:45.264185Z","shell.execute_reply.started":"2026-04-19T05:43:45.264011Z","shell.execute_reply":"2026-04-19T05:43:45.264041Z"},"papermill":{"duration":0.028387,"end_time":"2026-04-13T03:22:54.831288","exception":false,"start_time":"2026-04-13T03:22:54.802901","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport h5py\nimport numpy as np\n\ndef save_unified_keypoints_and_matches(global_keypoints, global_matches, feature_dir, lock=None):\n \"\"\"\n Saves unified keypoints and matches to HDF5 files and generates a pairs list.\n\n Args:\n global_keypoints (dict): Dictionary mapping image names to keypoint coordinates.\n global_matches (dict): Dictionary mapping (img1, img2) tuples to match ID arrays.\n feature_dir (str): Directory where the output files will be saved.\n lock (threading.Lock, optional): Optional lock for thread-safe operations.\n \"\"\"\n os.makedirs(feature_dir, exist_ok=True)\n save_kpts_file = os.path.join(feature_dir, 'keypoints.h5')\n save_matches_file = os.path.join(feature_dir, 'matches.h5')\n save_matches_txt_file = os.path.join(feature_dir, 'pairs.txt')\n\n # Remove existing files to ensure a clean save\n for f in [save_kpts_file, save_matches_file, save_matches_txt_file]:\n if os.path.exists(f):\n os.remove(f)\n\n # Save keypoint coordinates\n with h5py.File(save_kpts_file, 'w') as f_kp:\n for img_name, kpts in global_keypoints.items():\n f_kp[img_name] = kpts\n \n print(f\"✅ Saved keypoints to: {save_kpts_file}\")\n\n # Save matches\n with h5py.File(save_matches_file, 'w') as f_match:\n for (img1, img2), match in global_matches.items():\n # Create or retrieve the group for the first image\n group = f_match.require_group(img1)\n \n # Filter matches based on the minimum pair threshold configuration\n if len(match) >= CONFIG.MAST3R_MIN_PAIR:\n group.create_dataset(img2, data=match)\n \n print(f\"✅ Saved matches to: {save_matches_file}\")\n \n # Generate the pairs.txt file based on the saved matches\n with h5py.File(save_matches_file, 'r') as f, open(save_matches_txt_file, 'w') as fout:\n for k1 in f.keys():\n group = f[k1]\n for k2 in group.keys():\n fout.write(f\"{k1} {k2}\\n\")\n \n print(f\"✅ Saved match pairs list to: {save_matches_txt_file}\")","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.265327Z","iopub.status.idle":"2026-04-19T05:43:45.265721Z","shell.execute_reply.started":"2026-04-19T05:43:45.265508Z","shell.execute_reply":"2026-04-19T05:43:45.265558Z"},"papermill":{"duration":0.025752,"end_time":"2026-04-13T03:22:54.874495","exception":false,"start_time":"2026-04-13T03:22:54.848743","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def match_with_mast3r_and_save(index_pairs, image_list, feature_dir, model, device, lock):\n os.makedirs(feature_dir, exist_ok=True)\n out_match = defaultdict(dict)\n\n for idx1, idx2 in tqdm(index_pairs):\n name1, name2 = image_list[idx1], image_list[idx2]\n key1, key2 = os.path.basename(name1), os.path.basename(name2)\n\n images = load_images([name1, name2], size=512, verbose=False)\n output = inference([tuple(images)], mast3r_model, device, batch_size=1, verbose=False)\n\n view1, pred1 = output['view1'], output['pred1']\n view2, pred2 = output['view2'], output['pred2']\n\n desc1 = pred1['desc'].squeeze(0).detach()\n desc2 = pred2['desc'].squeeze(0).detach()\n conf1 = pred1['desc_conf'].squeeze(0).detach()\n conf2 = pred2['desc_conf'].squeeze(0).detach()\n\n corres = extract_correspondences_nonsym(\n desc1, desc2, conf1, conf2,\n device=device, subsample=8, pixel_tol=5\n )\n mask = corres[2] >= CONFIG.MATCH_CONF_TH\n matches_im0 = corres[0][mask].cpu().numpy()\n matches_im1 = corres[1][mask].cpu().numpy()\n\n if len(matches_im0) < CONFIG.MAST3R_MIN_PAIR:\n continue\n\n H0, W0 = view1['true_shape'][0].tolist()\n H1, W1 = view2['true_shape'][0].tolist()\n valid = (\n (matches_im0[:, 0] >= 3) & (matches_im0[:, 0] < W0 - 3) &\n (matches_im0[:, 1] >= 3) & (matches_im0[:, 1] < H0 - 3) &\n (matches_im1[:, 0] >= 3) & (matches_im1[:, 0] < W1 - 3) &\n (matches_im1[:, 1] >= 3) & (matches_im1[:, 1] < H1 - 3)\n )\n matches_im0, matches_im1 = matches_im0[valid], matches_im1[valid]\n\n if len(matches_im0) < CONFIG.MAST3R_MIN_PAIR:\n continue\n\n img0 = cv2.imread(name1)\n img1 = cv2.imread(name2)\n H0, W0 = img0.shape[:2]\n H1, W1 = img1.shape[:2]\n matches_im0_org = transform_keypoints_to_original(matches_im0, (H0, W0))\n matches_im1_org = transform_keypoints_to_original(matches_im1, (H1, W1))\n\n out_match[key1][key2] = np.concatenate([matches_im0_org, matches_im1_org], axis=1)\n\n global_keypoints, global_matches = unify_keypoints_and_matches(out_match)\n save_unified_keypoints_and_matches(global_keypoints, global_matches, feature_dir, lock)\n","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.266946Z","iopub.status.idle":"2026-04-19T05:43:45.267172Z","shell.execute_reply.started":"2026-04-19T05:43:45.267065Z","shell.execute_reply":"2026-04-19T05:43:45.26708Z"},"papermill":{"duration":0.032595,"end_time":"2026-04-13T03:22:54.924641","exception":false,"start_time":"2026-04-13T03:22:54.892046","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import gc\nimport time\nimport concurrent.futures\nimport multiprocessing\nfrom pathlib import Path\nfrom time import sleep, time\n# from pycolmap import verify_matches, TwoViewGeometryOptions\n\ndef run_verify_matches_safe(database_path, pairs_path, max_retries=5):\n def _safe_verify():\n verify_matches(\n database_path=database_path,\n pairs_path=pairs_path,\n options=TwoViewGeometryOptions()\n )\n\n for attempt in range(max_retries):\n print(f\"🔁 Attempt {attempt + 1} to run verify_matches\")\n proc = multiprocessing.Process(target=_safe_verify)\n proc.start()\n proc.join()\n\n if proc.exitcode in [0, 1]:\n print(\"✅ verify_matches succeeded\")\n return\n else:\n print(f\"⚠️ verify_matches crashed with code {proc.exitcode}\")\n raise RuntimeError(\"❌ verify_matches failed after multiple retries.\")","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.268228Z","iopub.status.idle":"2026-04-19T05:43:45.268453Z","shell.execute_reply.started":"2026-04-19T05:43:45.268343Z","shell.execute_reply":"2026-04-19T05:43:45.268358Z"},"papermill":{"duration":0.054029,"end_time":"2026-04-13T03:22:54.999913","exception":false,"start_time":"2026-04-13T03:22:54.945884","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def reconstruct_from_db(feature_dir, img_dir):\n import sys\n def log(msg):\n print(msg, flush=True)\n sys.stdout.flush()\n\n result = {}\n local_timings = {'RANSAC': [], 'Reconstruction': []}\n database_path = f'{feature_dir}/colmap.db'\n pairs_txt = f'{feature_dir}/pairs.txt'\n\n # Remove existing database if it exists to start fresh\n if os.path.isfile(database_path):\n os.remove(database_path)\n gc.collect()\n sleep(1)\n\n log(\">>> Starting import_into_colmap\")\n import_into_colmap(img_dir, feature_dir=feature_dir, database_path=database_path)\n log(\">>> Completed import_into_colmap\")\n sleep(1)\n\n output_path = f'{feature_dir}/colmap_rec'\n os.makedirs(output_path, exist_ok=True)\n\n log(\">>> Starting run_verify_matches_safe\")\n t = time()\n run_verify_matches_safe(database_path, pairs_txt)\n log(\">>> Completed run_verify_matches_safe\")\n local_timings['RANSAC'].append(time() - t)\n\n log(\">>> Initializing pycolmap.IncrementalPipelineOptions\")\n mapper_options = pycolmap.IncrementalPipelineOptions()\n mapper_options.min_model_size = 3\n mapper_options.max_num_models = 5\n\n log(\">>> Starting pycolmap.incremental_mapping\")\n t = time()\n maps = pycolmap.incremental_mapping(\n database_path=database_path,\n image_path=img_dir,\n output_path=output_path,\n options=mapper_options\n )\n log(f\">>> Completed pycolmap.incremental_mapping: {maps}\")\n\n # Extracting rotation and translation data from the reconstructed maps\n for map_index, rec in maps.items():\n result[map_index] = {}\n for img_id, image in rec.images.items():\n result[map_index][image.name] = {\n 'R': image.cam_from_world().rotation.matrix().tolist(),\n 't': image.cam_from_world().translation.tolist()\n }\n \n local_timings['Reconstruction'].append(time() - t)\n log(f'Reconstruction done in {local_timings[\"Reconstruction\"][-1]:.4f} sec')\n return result, local_timings","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndef run_one_dataset(dataset, predictions, data_dir, workdir, is_train, model, device, lock=None):\n timings = {\n \"shortlisting\": [],\n \"feature_matching\": [],\n \"RANSAC\": [],\n \"Reconstruction\": [],\n }\n\n try:\n images_dir = os.path.join(data_dir, 'train' if is_train else 'test', dataset)\n images = [os.path.join(images_dir, p.filename) for p in predictions]\n\n print(f'Processing dataset \"{dataset}\": {len(images)} images')\n filename_to_index = {p.filename: idx for idx, p in enumerate(predictions)}\n feature_dir = os.path.join(workdir, 'featureout', dataset)\n os.makedirs(feature_dir, exist_ok=True)\n\n t = time()\n index_img_pairs = make_pair_with_mast3r_return_pairs(\n image_dir=images_dir,\n weights_path=local_model_directory,\n retrieval_model_path=retrival_model_dir,\n device=device\n )\n\n indexed_pairs = []\n for filename1, filename2 in index_img_pairs:\n try:\n idx1 = filename_to_index[filename1]\n idx2 = filename_to_index[filename2]\n indexed_pairs.append((idx1, idx2))\n except KeyError as e:\n print(f\"Warning: Filename not found in mapping: {e}. Skipping pair.\")\n\n timings['shortlisting'].append(time() - t)\n print(f'Shortlisting done: {len(indexed_pairs)} pairs')\n gc.collect()\n\n if len(indexed_pairs) == 0:\n print(f'⏭️ No pairs for \"{dataset}\", skipping reconstruction.')\n return f'Dataset \"{dataset}\" -> No images/pairs, skipped.', timings\n\n t = time()\n match_with_mast3r_and_save(indexed_pairs, images, feature_dir, model, device, lock)\n timings['feature_matching'].append(time() - t)\n print(f'MASt3R matching done in {time() - t:.2f} sec')\n gc.collect()\n\n maps, local_timings = reconstruct_from_db(feature_dir, images_dir)\n\n sorted_map_items = sorted(maps.items(), key=lambda x: len(x[1]))\n\n registered = 0\n for new_cluster_idx, (original_map_index, cur_map) in enumerate(sorted_map_items):\n for image_name, pose in cur_map.items():\n idx = filename_to_index[image_name]\n pred = predictions[idx]\n pred.cluster_index = new_cluster_idx\n pred.rotation = np.array(pose['R'])\n pred.translation = np.array(pose['t'])\n registered += 1\n\n mapping_result_str = f'Dataset \"{dataset}\" -> Registered {registered} / {len(images)} images with {len(maps)} clusters'\n return mapping_result_str, timings\n\n except Exception as e:\n import traceback\n print(f\"Error in dataset {dataset}: {e}\")\n traceback.print_exc() \n return f'Dataset \"{dataset}\" -> Failed!', timings","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T05:43:45.270847Z","iopub.status.idle":"2026-04-19T05:43:45.27123Z","shell.execute_reply.started":"2026-04-19T05:43:45.271049Z","shell.execute_reply":"2026-04-19T05:43:45.271073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def run_mast3r_pipeline(samples, data_dir, workdir, is_train, model, device):\n max_images = None\n datasets_to_process = ['stairs'] if is_train else list(samples.keys())\n\n overall_timings = {\n \"shortlisting\": [],\n \"feature_matching\": [],\n \"RANSAC\": [],\n \"Reconstruction\": [],\n }\n mapping_result_strs = []\n lock = multiprocessing.Lock()\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:\n futures = []\n for dataset, predictions in samples.items():\n if datasets_to_process and dataset not in datasets_to_process:\n print(f\"Skipping {dataset}\")\n continue\n futures.append(executor.submit(run_one_dataset, dataset, predictions, data_dir, workdir, is_train, model, device, lock))\n\n for future in concurrent.futures.as_completed(futures):\n result_str, timings = future.result()\n mapping_result_strs.append(result_str)\n for k in timings:\n overall_timings[k].extend(timings[k])\n\n print('\\nResults')\n for s in mapping_result_strs:\n print(s)","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.272543Z","iopub.status.idle":"2026-04-19T05:43:45.272907Z","shell.execute_reply.started":"2026-04-19T05:43:45.27271Z","shell.execute_reply":"2026-04-19T05:43:45.272734Z"},"papermill":{"duration":0.054029,"end_time":"2026-04-13T03:22:54.999913","exception":false,"start_time":"2026-04-13T03:22:54.945884","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.274219Z","iopub.status.idle":"2026-04-19T05:43:45.274619Z","shell.execute_reply.started":"2026-04-19T05:43:45.274415Z","shell.execute_reply":"2026-04-19T05:43:45.274441Z"},"papermill":{"duration":1.948727,"end_time":"2026-04-13T03:22:56.966414","exception":false,"start_time":"2026-04-13T03:22:55.017687","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import asmk.codebook as asmk_codebook\nimport faiss\nimport numpy as np\n\ndef _fixed_quantize(self, des, image_ids=None, nns=1, multiple_assignment=1, **kwargs):\n nns = int(np.asarray(nns).flat[0])\n multiple_assignment = int(np.asarray(multiple_assignment).flat[0])\n nns = max(nns, multiple_assignment)\n \n # Initialize the FAISS index if it hasn't been built yet\n if not hasattr(self, '_index_fixed'):\n centroids = np.ascontiguousarray(self.centroids, dtype=np.float32)\n dim = centroids.shape[1]\n new_index = faiss.IndexFlatL2(dim)\n new_index.add(centroids)\n self.index = new_index\n self._index_fixed = True\n print(f\"[FIX] faiss index rebuilt: {len(centroids)} centroids, dim={dim}\")\n \n des = np.ascontiguousarray(des, dtype=np.float32)\n _, word_ids = self.index.search(des, nns)\n \n # build_ivf: aggregate(*quantized) requires 3 arguments (des, word_ids, image_ids)\n if image_ids is not None:\n return des, word_ids, image_ids\n # query_ivf: aggregate_image(*quantized) requires 2 arguments (des, word_ids)\n else:\n return des, word_ids\n\n# Monkey-patch the ASMK Codebook class with the fixed quantization method\nasmk_codebook.Codebook.quantize = _fixed_quantize","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# run_mast3r_pipeline","metadata":{}},{"cell_type":"code","source":"run_mast3r_pipeline(samples, data_dir, workdir, is_train, mast3r_model, device)","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.280622Z","iopub.status.idle":"2026-04-19T05:43:45.281357Z","shell.execute_reply.started":"2026-04-19T05:43:45.281179Z","shell.execute_reply":"2026-04-19T05:43:45.281206Z"},"papermill":{"duration":1570.210636,"end_time":"2026-04-13T03:49:07.195573","exception":false,"start_time":"2026-04-13T03:22:56.984937","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"array_to_str = lambda array: ';'.join([f\"{x:.09f}\" for x in array])\nnone_to_str = lambda n: ';'.join(['nan'] * n)\nsubmission_file = '/kaggle/working/submission.csv'\nwith open(submission_file, 'w') as f:\n if is_train:\n f.write('dataset,scene,image,rotation_matrix,translation_vector\\n')\n for dataset, predictions in samples.items():\n for prediction in predictions:\n cluster_name = 'outliers' if prediction.cluster_index is None else f'cluster{prediction.cluster_index}'\n\n # ✅ `rotation` is a list of lists, flatten it\n if prediction.rotation is None:\n rotation_str = none_to_str(9)\n else:\n rotation_flat = prediction.rotation.flatten() # flatten 3x3 list -> 9 elems\n rotation_str = array_to_str(rotation_flat)\n\n # ✅ `translation` is a flat list\n if prediction.translation is None:\n translation_str = none_to_str(3)\n else:\n translation_str = array_to_str(prediction.translation)\n\n f.write(f'{prediction.dataset},{cluster_name},{prediction.filename},{rotation_str},{translation_str}\\n')\n else:\n f.write('image_id,dataset,scene,image,rotation_matrix,translation_vector\\n')\n for dataset, predictions in samples.items():\n for prediction in predictions:\n cluster_name = 'outliers' if prediction.cluster_index is None else f'cluster{prediction.cluster_index}'\n\n if prediction.rotation is None:\n rotation_str = none_to_str(9)\n else:\n rotation_flat = prediction.rotation.flatten()\n rotation_str = array_to_str(rotation_flat)\n\n if prediction.translation is None:\n translation_str = none_to_str(3)\n else:\n translation_str = array_to_str(prediction.translation)\n\n f.write(f'{prediction.image_id},{prediction.dataset},{cluster_name},{prediction.filename},{rotation_str},{translation_str}\\n')\n\n# Preview the output\n!head {submission_file}\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.283972Z","iopub.status.idle":"2026-04-19T05:43:45.284299Z","shell.execute_reply.started":"2026-04-19T05:43:45.284134Z","shell.execute_reply":"2026-04-19T05:43:45.28416Z"},"papermill":{"duration":2.311984,"end_time":"2026-04-13T03:49:10.398323","exception":false,"start_time":"2026-04-13T03:49:08.086339","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nif is_train:\n t = time()\n final_score, dataset_scores = metric.score(\n gt_csv='/kaggle/input/competitions/image-matching-challenge-2025/train_labels.csv',\n user_csv=submission_file,\n thresholds_csv='/kaggle/input/competitions/image-matching-challenge-2025/train_thresholds.csv',\n mask_csv=None if is_train else os.path.join(data_dir, 'mask.csv'),\n inl_cf=0,\n strict_cf=-1,\n verbose=True,\n )\n print(f'Computed metric in: {time() - t:.02f} sec.')","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.286032Z","iopub.status.idle":"2026-04-19T05:43:45.286474Z","shell.execute_reply.started":"2026-04-19T05:43:45.286267Z","shell.execute_reply":"2026-04-19T05:43:45.286284Z"},"papermill":{"duration":0.167251,"end_time":"2026-04-13T03:49:10.728052","exception":false,"start_time":"2026-04-13T03:49:10.560801","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"execution":{"iopub.status.busy":"2026-04-19T05:43:45.287714Z","iopub.status.idle":"2026-04-19T05:43:45.28808Z","shell.execute_reply.started":"2026-04-19T05:43:45.287936Z","shell.execute_reply":"2026-04-19T05:43:45.287961Z"},"papermill":{"duration":2.294004,"end_time":"2026-04-13T03:49:13.228103","exception":false,"start_time":"2026-04-13T03:49:10.934099","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}