File size: 48,546 Bytes
ed37d96
1
{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":12148061,"datasetId":7651041,"databundleVersionId":12682483},{"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":244142953}],"dockerImageVersionId":31041,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **scene_graph: str = 'retrieval-20-25'**\n\n# **MASt3R IMC2025 Submission (is_train:False)**\n","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:20.463697Z","iopub.execute_input":"2025-06-19T23:00:20.463957Z","iopub.status.idle":"2025-06-19T23:00:20.472697Z","shell.execute_reply.started":"2025-06-19T23:00:20.463937Z","shell.execute_reply":"2025-06-19T23:00:20.471758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install torch torchvision torchaudio --no-index --find-links=/kaggle/input/mast3r-fix/mast3r-wheels\n\n!pip install faiss-gpu-cu12 --no-index --find-links=/kaggle/input/mast3r-fix/mast3r-wheels\n\n!pip install --no-index --find-links=/kaggle/input/mast3r-fix/mast3r-wheels \\\n    -r /kaggle/input/mast3r-fix/mast3r/requirements.txt \\\n    -r /kaggle/input/mast3r-fix/mast3r/dust3r/requirements.txt \\\n    -r /kaggle/input/mast3r-fix/mast3r/dust3r/requirements_optional.txt\n\n!pip install --no-index /kaggle/input/imc2024-packages-lightglue-rerun-kornia/* --no-deps\n\n!pip install --no-index /kaggle/input/pycolmap3-11/pycolmap-3.11.1-cp311-cp311-manylinux_2_28_x86_64.whl --no-deps","metadata":{"trusted":true,"_kg_hide-output":true,"scrolled":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:20.490948Z","iopub.execute_input":"2025-06-19T23:00:20.491211Z","iopub.status.idle":"2025-06-19T23:00:23.848074Z","shell.execute_reply.started":"2025-06-19T23:00:20.491187Z","shell.execute_reply":"2025-06-19T23:00:23.847377Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sys.path.insert(0, \"/kaggle/input/mast3r-fix/mast3r\")\nsys.path.insert(0, '/kaggle/input/mast3r-fix/mast3r/asmk')\nsys.path.insert(0, '/kaggle/input/mast3r-fix/mast3r/dust3r/croco/models/curope')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:34.306042Z","iopub.execute_input":"2025-06-19T23:00:34.306296Z","iopub.status.idle":"2025-06-19T23:00:34.330204Z","shell.execute_reply.started":"2025-06-19T23:00:34.306268Z","shell.execute_reply":"2025-06-19T23:00:34.329602Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:34.349053Z","iopub.execute_input":"2025-06-19T23:00:34.349335Z","iopub.status.idle":"2025-06-19T23:00:34.713224Z","shell.execute_reply.started":"2025-06-19T23:00:34.34931Z","shell.execute_reply":"2025-06-19T23:00:34.712345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:34.714259Z","iopub.execute_input":"2025-06-19T23:00:34.714455Z","iopub.status.idle":"2025-06-19T23:00:36.364949Z","shell.execute_reply.started":"2025-06-19T23:00:34.714433Z","shell.execute_reply":"2025-06-19T23:00:36.364392Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pycolmap\n!pip show pycolmap\n\nprint(os.listdir(os.path.dirname(pycolmap.__file__)))\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\n\nsys.path.append('/kaggle/input/pycolmap3-11-imc-utils')\n\n# from database import *\nfrom h5_to_db import *\nimport metric\nfrom pycolmap import verify_matches, TwoViewGeometryOptions\n\nfrom fastprogress import progress_bar","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:36.370102Z","iopub.execute_input":"2025-06-19T23:00:36.370409Z","iopub.status.idle":"2025-06-19T23:00:38.444455Z","shell.execute_reply.started":"2025-06-19T23:00:36.370381Z","shell.execute_reply":"2025-06-19T23:00:38.443636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"_ = verify_matches\n_ = TwoViewGeometryOptions()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:45.542593Z","iopub.execute_input":"2025-06-19T23:00:45.543064Z","iopub.status.idle":"2025-06-19T23:00:45.54708Z","shell.execute_reply.started":"2025-06-19T23:00:45.543044Z","shell.execute_reply":"2025-06-19T23:00:45.546184Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:45.548011Z","iopub.execute_input":"2025-06-19T23:00:45.548324Z","iopub.status.idle":"2025-06-19T23:00:45.711027Z","shell.execute_reply.started":"2025-06-19T23:00:45.548305Z","shell.execute_reply":"2025-06-19T23:00:45.710186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!rm -rf /kaggle/working/result","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:45.712052Z","iopub.execute_input":"2025-06-19T23:00:45.712365Z","iopub.status.idle":"2025-06-19T23:00:45.869864Z","shell.execute_reply.started":"2025-06-19T23:00:45.712337Z","shell.execute_reply":"2025-06-19T23:00:45.868653Z"}},"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/mast3r-fix/mast3r/checkpoints/\"\nlocal_model_directory = \"/kaggle/input/mast3r-fix/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth\"\nretrival_model_dir = '/kaggle/input/mast3r-fix/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_trainingfree.pth'\n\n# 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\nprint(f\"Loading model from local path: {local_model_directory}\")\nmast3r_model = load_model(local_model_directory, device=device) # Pass device to load_model\nprint(\"Model loaded successfully.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:45.871093Z","iopub.execute_input":"2025-06-19T23:00:45.871363Z","iopub.status.idle":"2025-06-19T23:00:57.554773Z","shell.execute_reply.started":"2025-06-19T23:00:45.871336Z","shell.execute_reply":"2025-06-19T23:00:57.553891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:57.555727Z","iopub.execute_input":"2025-06-19T23:00:57.556021Z","iopub.status.idle":"2025-06-19T23:00:57.565028Z","shell.execute_reply.started":"2025-06-19T23:00:57.555997Z","shell.execute_reply":"2025-06-19T23:00:57.564061Z"}},"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_path1 = '/kaggle/input/image-matching-challenge-2025/train/ETs/et_et003.png'\nimg_path2 = '/kaggle/input/image-matching-challenge-2025/train/ETs/et_et006.png'\nimages = load_images([img_path1, img_path2], size=512)\noutput = inference([tuple(images)], mast3r_model, device, batch_size=1, verbose=True)\n\n# at this stage, you have the raw dust3r predictions\nview1, pred1 = output['view1'], output['pred1']\nview2, pred2 = output['view2'], output['pred2']\n\ndesc1, desc2 = pred1['desc'].squeeze(0).detach(), pred2['desc'].squeeze(0).detach()\n\n# find 2D-2D matches between the two images\n# matches_im0, matches_im1 = fast_reciprocal_NNs(desc1, desc2, subsample_or_initxy1=8,\n#                                                device=device, dist='dot', block_size=2**13)\nconf1, conf2 = pred1['desc_conf'].squeeze(0).detach(), pred2['desc_conf'].squeeze(0).detach()\nprint(f\"desc1 shape: {desc1.shape}\")\nprint(f\"conf1 shape: {conf1.shape}\")\ncorres = extract_correspondences_nonsym(desc1, desc2, conf1, conf2,\n                                        device=device, subsample=8, pixel_tol=5)\nprint(f\"corres[0].shape: {corres[0].shape}\")\nprint(f\"corres[2].shape: {corres[2].shape}\")\nscore = corres[2]\n\nprint(\"conf min:\",score.min().item())\nprint(\"conf max:\", score.max().item())\nprint(\"conf mean:\", score.float().mean().item())\nprint(\"conf std:\", score.float().std().item())\nprint(\"conf median:\", score.float().median().item())\n\nmask = score >= CONFIG.MATCH_CONF_TH\nmatches_im0 = corres[0][mask].cpu().numpy()\nmatches_im1 = corres[1][mask].cpu().numpy()\nprint(f\"matches_im0.shape: {matches_im0.shape}\")\n\n# matches_im0 = corres[0].cpu().numpy()\n# matches_im1 = corres[1].cpu().numpy()\n\n# ignore small border around the edge\nH0, W0 = view1['true_shape'][0]\nvalid_matches_im0 = (matches_im0[:, 0] >= 3) & (matches_im0[:, 0] < int(W0) - 3) & (\n    matches_im0[:, 1] >= 3) & (matches_im0[:, 1] < int(H0) - 3)\n\nH1, W1 = view2['true_shape'][0]\nvalid_matches_im1 = (matches_im1[:, 0] >= 3) & (matches_im1[:, 0] < int(W1) - 3) & (\n    matches_im1[:, 1] >= 3) & (matches_im1[:, 1] < int(H1) - 3)\n\nvalid_matches = valid_matches_im0 & valid_matches_im1\nmatches_im0, matches_im1 = matches_im0[valid_matches], matches_im1[valid_matches]\n\n# visualize a few matches\nimport numpy as np\nimport torch\nimport torchvision.transforms.functional\nfrom matplotlib import pyplot as pl\n\nn_viz = 100\nnum_matches = matches_im0.shape[0]\nmatch_idx_to_viz = np.round(np.linspace(0, num_matches - 1, n_viz)).astype(int)\nviz_matches_im0, viz_matches_im1 = matches_im0[match_idx_to_viz], matches_im1[match_idx_to_viz]\n\nimage_mean = torch.as_tensor([0.5, 0.5, 0.5], device='cpu').reshape(1, 3, 1, 1)\nimage_std = torch.as_tensor([0.5, 0.5, 0.5], device='cpu').reshape(1, 3, 1, 1)\n\nviz_imgs = []\nfor i, view in enumerate([view1, view2]):\n    rgb_tensor = view['img'] * image_std + image_mean\n    viz_imgs.append(rgb_tensor.squeeze(0).permute(1, 2, 0).cpu().numpy())\n\nH0, W0, H1, W1 = *viz_imgs[0].shape[:2], *viz_imgs[1].shape[:2]\nprint(H0,W0,H1,W1)\nimg0 = np.pad(viz_imgs[0], ((0, max(H1 - H0, 0)), (0, 0), (0, 0)), 'constant', constant_values=0)\nimg1 = np.pad(viz_imgs[1], ((0, max(H0 - H1, 0)), (0, 0), (0, 0)), 'constant', constant_values=0)\nimg = np.concatenate((img0, img1), axis=1)\npl.figure()\npl.imshow(img)\ncmap = pl.get_cmap('jet')\nfor i in range(n_viz):\n    (x0, y0), (x1, y1) = viz_matches_im0[i].T, viz_matches_im1[i].T\n    pl.plot([x0, x1 + W0], [y0, y1], '-+', color=cmap(i / (n_viz - 1)), scalex=False, scaley=False)\npl.show(block=True)\n\nimg0 = cv2.imread(img_path1)\nimg1 = cv2.imread(img_path2)\nH0, W0 = img0.shape[:2]\nH1, W1 = img1.shape[:2]\nviz_matches_im0_org = transform_keypoints_to_original(viz_matches_im0, (H0, W0))\nviz_matches_im1_org = transform_keypoints_to_original(viz_matches_im1, (H1, W1))\n\nout_org_dir= os.path.join(\"/kaggle/working\", \"temp\")\nos.makedirs(out_org_dir, exist_ok=True)\n\ndraw_matches_on_original_images(img_path1, img_path2, viz_matches_im0_org, viz_matches_im1_org, out_org_dir, n_viz=100)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:57.590938Z","iopub.execute_input":"2025-06-19T23:00:57.591116Z","iopub.status.idle":"2025-06-19T23:00:59.299533Z","shell.execute_reply.started":"2025-06-19T23:00:57.591102Z","shell.execute_reply":"2025-06-19T23:00:59.298886Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.300359Z","iopub.execute_input":"2025-06-19T23:00:59.300975Z","iopub.status.idle":"2025-06-19T23:00:59.305194Z","shell.execute_reply.started":"2025-06-19T23:00:59.300954Z","shell.execute_reply":"2025-06-19T23:00:59.30457Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.30581Z","iopub.execute_input":"2025-06-19T23:00:59.305981Z","iopub.status.idle":"2025-06-19T23:00:59.439663Z","shell.execute_reply.started":"2025-06-19T23:00:59.305959Z","shell.execute_reply":"2025-06-19T23:00:59.43887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.30581Z","iopub.execute_input":"2025-06-19T23:00:59.305981Z","iopub.status.idle":"2025-06-19T23:00:59.439663Z","shell.execute_reply.started":"2025-06-19T23:00:59.305959Z","shell.execute_reply":"2025-06-19T23:00:59.43887Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.440597Z","iopub.execute_input":"2025-06-19T23:00:59.441178Z","iopub.status.idle":"2025-06-19T23:00:59.591717Z","shell.execute_reply.started":"2025-06-19T23:00:59.441134Z","shell.execute_reply":"2025-06-19T23:00:59.590884Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.592643Z","iopub.execute_input":"2025-06-19T23:00:59.59295Z","iopub.status.idle":"2025-06-19T23:00:59.600456Z","shell.execute_reply.started":"2025-06-19T23:00:59.592927Z","shell.execute_reply":"2025-06-19T23:00:59.59962Z"}},"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/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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.648804Z","iopub.execute_input":"2025-06-19T23:00:59.649085Z","iopub.status.idle":"2025-06-19T23:00:59.798087Z","shell.execute_reply.started":"2025-06-19T23:00:59.64906Z","shell.execute_reply":"2025-06-19T23:00:59.797316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import multiprocessing\nimport torch\nimport matplotlib.pyplot as plt\nimport cv2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.79904Z","iopub.execute_input":"2025-06-19T23:00:59.799331Z","iopub.status.idle":"2025-06-19T23:00:59.80341Z","shell.execute_reply.started":"2025-06-19T23:00:59.799311Z","shell.execute_reply":"2025-06-19T23:00:59.802456Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.821635Z","iopub.execute_input":"2025-06-19T23:00:59.821807Z","iopub.status.idle":"2025-06-19T23:00:59.845897Z","shell.execute_reply.started":"2025-06-19T23:00:59.821793Z","shell.execute_reply":"2025-06-19T23:00:59.845316Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.846599Z","iopub.execute_input":"2025-06-19T23:00:59.846805Z","iopub.status.idle":"2025-06-19T23:00:59.860716Z","shell.execute_reply.started":"2025-06-19T23:00:59.84679Z","shell.execute_reply":"2025-06-19T23:00:59.859975Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.861495Z","iopub.execute_input":"2025-06-19T23:00:59.86191Z","iopub.status.idle":"2025-06-19T23:00:59.88296Z","shell.execute_reply.started":"2025-06-19T23:00:59.861891Z","shell.execute_reply":"2025-06-19T23:00:59.882405Z"}},"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.\")\n\ndef reconstruct_from_db(feature_dir, img_dir):\n    result = {}\n    local_timings = {'RANSAC': [], 'Reconstruction': []}\n\n    database_path = f'{feature_dir}/colmap.db'\n    pairs_txt = f'{feature_dir}/pairs.txt'\n    if os.path.isfile(database_path):\n        os.remove(database_path)\n    gc.collect()\n    sleep(1)\n\n    import_into_colmap(img_dir, feature_dir=feature_dir, database_path=database_path)\n    sleep(1)\n    print(f\"import {database_path} done!\")\n    output_path = f'{feature_dir}/colmap_rec'\n    os.makedirs(output_path, exist_ok=True)\n    print(\"colmap database\")\n\n    t = time()\n    run_verify_matches_safe(database_path, pairs_txt)\n    print(\"verify matching done!!!!\")\n    local_timings['RANSAC'].append(time() - t)\n    print(f'RANSAC in {local_timings[\"RANSAC\"][-1]:.4f} sec')\n\n    t = time()\n    mapper_options = pycolmap.IncrementalPipelineOptions()\n    mapper_options.min_model_size = 3\n    mapper_options.max_num_models = 5\n    maps = pycolmap.incremental_mapping(database_path=database_path, image_path=img_dir, \n                                        output_path=output_path, options=mapper_options)\n    print(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    local_timings['Reconstruction'].append(time() - t)\n    print(f'Reconstruction done in {local_timings[\"Reconstruction\"][-1]:.4f} sec')\n\n    return result, local_timings\n\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\n        index_img_pairs = make_pair_with_mast3r_return_pairs(image_dir=images_dir,\n                      weights_path = local_model_directory,  # Path to the AsymmetricMASt3R model weights (e.g., \"naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\" or local path)\n                      retrieval_model_path = retrival_model_dir,  # Path to the retrieval model (e.g., \"trainingfree.pth\")\n                      device = device)\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 ({filename1}, {filename2}).\")\n\n        timings['shortlisting'].append(time() - t)\n        print(f'Shortlisting done: {len(indexed_pairs)} pairs')\n        gc.collect()\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        # print(maps)\n        \n        # Sort map clusters by number of registered images (ascending)\n        sorted_map_items = sorted(maps.items(), key=lambda x: len(x[1]))\n        # print(sorted_map_items)\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  # use the sorted order\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        print(f\"Error in dataset {dataset}: {e}\")\n        return f\"Dataset \\\"{dataset}\\\" -> Failed!\", timings\n\ndef 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=2) 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.906651Z","iopub.execute_input":"2025-06-19T23:00:59.906894Z","iopub.status.idle":"2025-06-19T23:00:59.930741Z","shell.execute_reply.started":"2025-06-19T23:00:59.906873Z","shell.execute_reply":"2025-06-19T23:00:59.930194Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"run_mast3r_pipeline(samples, data_dir, workdir, is_train, mast3r_model, device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:00:59.931424Z","iopub.execute_input":"2025-06-19T23:00:59.931606Z","iopub.status.idle":"2025-06-19T23:05:51.127237Z","shell.execute_reply.started":"2025-06-19T23:00:59.931592Z","shell.execute_reply":"2025-06-19T23:05:51.126199Z"}},"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,"execution":{"iopub.status.busy":"2025-06-19T23:05:51.128724Z","iopub.execute_input":"2025-06-19T23:05:51.129092Z","iopub.status.idle":"2025-06-19T23:05:51.433089Z","shell.execute_reply.started":"2025-06-19T23:05:51.129055Z","shell.execute_reply":"2025-06-19T23:05:51.432385Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"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/image-matching-challenge-2025/train_labels.csv',\n        user_csv=submission_file,\n        thresholds_csv='/kaggle/input/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":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-19T23:05:51.434476Z","iopub.execute_input":"2025-06-19T23:05:51.434955Z","iopub.status.idle":"2025-06-19T23:05:51.853889Z","shell.execute_reply.started":"2025-06-19T23:05:51.434916Z","shell.execute_reply":"2025-06-19T23:05:51.852982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip show numpy | grep Version:","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}