stpete2 commited on
Commit
ed37d96
ยท
verified ยท
1 Parent(s): 7109aa0

Upload 3 files

Browse files
cp311-to-cp312-explained.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# **cp311 to cp312 explained**","metadata":{}},{"cell_type":"markdown","source":"## cp311\nhttps://www.kaggle.com/code/stpeteishii/mb-ongmx20-25-mast3r-sfm-imc2025-ong-sub-is\n\n## cp312\nhttps://www.kaggle.com/code/stpeteishii/ongmx20-25-mast3r-sfm-imc2025-ong-sub-is-t","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Here is a structured summary of all changes introduced in the cp312 version compared to cp311:\n\n---\n\n## Changes from cp311 โ†’ cp312\n\n### 1. Python & Wheel Compatibility\n\n- **pycolmap upgraded**: The cp311 wheel (`pycolmap-3.11.1-cp311`) is replaced with `pycolmap-4.0.3-cp312`, sourced from a user notebook dataset (`stpeteishii/pycolmap-4-0-3-cp312`).\n- All MASt3R-related wheels and paths are now loaded from `/kaggle/input/notebooks/stpeteishii/mast3r-cp312/` instead of `/kaggle/input/mast3r-fix/`.\n- `print(sys.version)` is added early on to explicitly verify the Python version.\n\n### 2. FAISS Installation\n\n- cp312 adds three explicit wheel installs for FAISS and its CUDA dependencies (`faiss_gpu_cu12`, `nvidia_cublas_cu12`, `nvidia_cuda_runtime_cu12`) from a dedicated dataset โ€” replacing the single `faiss-gpu-cu12` install used in cp311.\n\n### 3. `import_into_colmap` โ€” Full Rewrite\n\n- cp311 relied on the external `import_into_colmap` function from `h5_to_db`.\n- cp312 **rewrites this function from scratch** using raw `sqlite3`, manually creating the COLMAP database schema and inserting cameras, images, keypoints, and matches. This was necessary because the pycolmap 4.0.3 `Database` API changed significantly.\n- Debug introspection of `pycolmap.Database` methods (`db.write_camera.__doc__`, etc.) is also added.\n\n### 4. pycolmap API Breaking Change โ€” `cam_from_world`\n\n- In `reconstruct_from_db`, cp311 accesses `image.cam_from_world.rotation` (attribute).\n- cp312 changes this to `image.cam_from_world().rotation` (method call), adapting to the breaking API change in pycolmap 4.0.3.\n\n### 5. ASMK `.so` Loading for cp312\n\n- cp312 adds explicit manual loading of compiled C-extension `.so` files (`hamming.cpython-312-x86_64-linux-gnu.so`) using `importlib.util.spec_from_file_location`, since ASMK's compiled extensions are Python-version-specific.\n\n### 6. ASMK / FAISS Monkey-Patches\n\n- **`FaissGpuL2Index` patch**: `asmk_index.FaissGpuL2Index.create_index` is monkey-patched to use a CPU `IndexFlatL2` index instead, as a compatibility workaround.\n- **`Codebook.quantize` patch**: A `_fixed_quantize` function is added and monkey-patched onto `asmk_codebook.Codebook.quantize`. It rebuilds the FAISS index on demand and fixes argument-count mismatches between `build_ivf` (3 args) and `query_ivf` (2 args) paths.\n\n### 7. Model Loading โ€” `torch.serialization` Fix\n\n- cp312 adds `torch.serialization.add_safe_globals([argparse.Namespace])` before calling `load_model`, to satisfy PyTorch's stricter safe-deserialization requirements introduced in newer versions.\n\n### 8. Robustness Improvements in `run_one_dataset`\n\n- A guard is added: if `indexed_pairs` is empty after shortlisting, the dataset is skipped gracefully with a clear log message (instead of potentially crashing).\n- The `except` block now also calls `traceback.print_exc()` for more informative error reporting.\n\n### 9. `reconstruct_from_db` โ€” Verbose Logging\n\n- cp312 adds a `log()` helper with `sys.stdout.flush()` and step-by-step progress messages throughout `reconstruct_from_db`, making it easier to diagnose where failures occur.\n\n### 10. Thread Pool โ€” `max_workers` Reduced\n\n- `ThreadPoolExecutor` in `run_mast3r_pipeline` is changed from `max_workers=2` (cp311) to `max_workers=1` (cp312), likely to reduce memory pressure or avoid race conditions under the new setup.\n\n### 11. Dataset & Input Paths\n\n- `data_dir` is changed from `/kaggle/input/image-matching-challenge-2025` to `/kaggle/input/competitions/image-matching-challenge-2025`.\n- The `sys.path` entry for imc-utils is updated from `/kaggle/input/pycolmap3-11-imc-utils` to `/kaggle/input/datasets/yuanlin08/pycolmap3-11-imc-utils`.\n- Metric CSV paths in the scoring block are updated accordingly.\n\n---\n\n**Summary**: The cp312 migration is primarily driven by upgrading pycolmap from 3.11.1 โ†’ 4.0.3 (which has breaking API changes), adapting ASMK's compiled extensions and FAISS integration for Python 3.12, and fixing torch deserialization. Alongside these compatibility fixes, several robustness and observability improvements (error handling, logging, empty-pair guard) were also introduced.","metadata":{}},{"cell_type":"markdown","source":"Here is a detailed analysis of the full conversion pipeline from MASt3R outputs to COLMAP format, and exactly where cp311 and cp312 agree or differ.\n\n---\n\n## Overview of the Pipeline\n\nThe conversion consists of **six sequential stages**:\n\n```\nMASt3R inference\n โ†“\n [1] extract_correspondences_nonsym โ†’ raw pixel matches\n โ†“\n [2] transform_keypoints_to_original โ†’ coords in original image space\n โ†“\n [3] unify_keypoints_and_matches โ†’ global keypoint IDs\n โ†“\n [4] save_unified_keypoints_and_matches โ†’ keypoints.h5 / matches.h5 / pairs.txt\n โ†“\n [5] import_into_colmap โ†’ COLMAP SQLite database\n โ†“\n [6] verify_matches + incremental_mapping โ†’ reconstructed poses\n```\n\n---\n\n## Stage-by-Stage Breakdown\n\n### Stage 1 โ€” MASt3R Inference & Correspondence Extraction (`match_with_mast3r_and_save`)\n\nFor each image pair:\n1. `load_images()` resizes both images to 512px (DUST3R convention).\n2. `inference()` runs the MASt3R encoder-decoder to produce dense descriptor maps (`desc`) and confidence maps (`desc_conf`) for both views.\n3. `extract_correspondences_nonsym()` computes non-symmetric nearest-neighbor correspondences in descriptor space, returning matched pixel coordinates `(x, y)` in the **resized/cropped** image space, plus a per-match confidence score.\n4. Matches below `CONFIG.MATCH_CONF_TH = 1.001` are discarded, and a 3-pixel border exclusion mask is applied.\n\n**โ†’ Identical in cp311 and cp312.**\n\n---\n\n### Stage 2 โ€” Coordinate Back-Projection (`transform_keypoints_to_original`)\n\nBecause `load_images()` resizes and center-crops the image before feeding it to MASt3R, the match coordinates are in the **processed image space**, not the original. This function reverses both the crop offset and the scale factor to recover coordinates in the original image's pixel space.\n\nThe math:\n- Recomputes the resize scale factor (long-side โ†’ 512).\n- Recomputes the crop offsets (`halfw`, `halfh`, aligned to 16-pixel grid).\n- Adds crop offsets back, then divides by scale factor.\n\n**โ†’ Identical in cp311 and cp312.**\n\n---\n\n### Stage 3 โ€” Keypoint Unification (`unify_keypoints_and_matches`)\n\nSince each image appears in multiple pairs, the same physical point on an image may appear under slightly different floating-point coordinates from different pair runs. This stage:\n1. Collects all coordinates for each image across all pairs.\n2. Rounds them to 1 decimal place and takes `np.unique` to deduplicate.\n3. Assigns each unique coordinate a **global integer ID**.\n4. Converts every pair's coordinate-based match `(x1,y1,x2,y2)` into a global ID pair `(id1, id2)` via a coordinateโ†’ID lookup table.\n\nThis produces `global_keypoints[img]` and `global_matches[(img1, img2)]` which are the COLMAP-compatible data structures.\n\n**โ†’ Identical in cp311 and cp312.**\n\n---\n\n### Stage 4 โ€” HDF5 Serialization (`save_unified_keypoints_and_matches`)\n\nWrites three files to `feature_dir`:\n- `keypoints.h5` โ€” per-image `(N, 2)` coordinate arrays.\n- `matches.h5` โ€” per-pair `(M, 2)` global ID arrays (only pairs with โ‰ฅ `MAST3R_MIN_PAIR = 15` matches are written).\n- `pairs.txt` โ€” list of image name pairs, used as input to `verify_matches`.\n\n**โ†’ Identical in cp311 and cp312.**\n\n---\n\n### Stage 5 โ€” COLMAP Database Import (`import_into_colmap`) โš ๏ธ **DIFFERS**\n\nThis is the only stage with a **fundamental architectural difference** between the two versions.\n\n**cp311** โ€” delegates entirely to the external helper imported from `h5_to_db`:\n```python\nfrom h5_to_db import *\n# ...\nimport_into_colmap(img_dir, feature_dir=feature_dir, database_path=database_path)\n```\nThe implementation is hidden inside the `pycolmap3-11-imc-utils` dataset. It presumably uses the pycolmap 3.x `Database` high-level API.\n\n**cp312** โ€” fully reimplements this function from scratch using raw `sqlite3`, because the pycolmap 4.0.3 `Database` API changed incompatibly. It manually:\n1. Creates the COLMAP database schema with `CREATE TABLE IF NOT EXISTS` for all six COLMAP tables (`cameras`, `images`, `keypoints`, `matches`, `two_view_geometries`, `descriptors`).\n2. Reads `keypoints.h5` and for each image inserts a row into `cameras` (using `SIMPLE_RADIAL` model with `f = max(w,h)`, `cx = w/2`, `cy = h/2`, `k = 0`) and a row into `images`.\n3. Inserts keypoint blobs directly as `float32` bytes.\n4. Reads `matches.h5` and inserts match blobs as `uint32` bytes, using the standard COLMAP `pair_id = id1 * 2147483647 + id2` encoding.\n\nThe end result is the same SQLite database structure COLMAP expects, but the path to get there is completely different.\n\n---\n\n### Stage 6 โ€” Geometric Verification & Incremental Mapping (`reconstruct_from_db`) โš ๏ธ **Minor API difference**\n\nBoth versions call the same two pycolmap functions:\n\n```python\npycolmap.verify_matches(database_path, pairs_path, TwoViewGeometryOptions())\npycolmap.incremental_mapping(database_path, image_path, output_path, options)\n```\n\n`verify_matches` runs RANSAC (fundamental/essential matrix estimation) on each pair and writes verified inlier geometries back into `two_view_geometries`. \n`incremental_mapping` then performs full SfM โ€” incremental reconstruction of camera poses.\n\nThe only code-level difference is in how the resulting rotation/translation is accessed after mapping:\n\n| | cp311 | cp312 |\n|---|---|---|\n| Access pattern | `image.cam_from_world.rotation` | `image.cam_from_world().rotation` |\n| Reason | pycolmap 3.x: `cam_from_world` is an attribute | pycolmap 4.x: `cam_from_world` is a method |\n\n**โ†’ Semantically identical; syntax differs due to pycolmap API break.**\n\n---\n\n## Summary Table\n\n| Stage | cp311 | cp312 | Same? |\n|---|---|---|---|\n| MASt3R inference + correspondence extraction | `extract_correspondences_nonsym` | same | โœ… |\n| Coordinate back-projection to original space | `transform_keypoints_to_original` | same | โœ… |\n| Keypoint unification & global ID assignment | `unify_keypoints_and_matches` | same | โœ… |\n| HDF5 serialization | `save_unified_keypoints_and_matches` | same | โœ… |\n| COLMAP DB import | external `h5_to_db` helper (pycolmap 3.x API) | custom raw `sqlite3` reimplementation | โŒ |\n| Geometric verification + mapping | `verify_matches` + `incremental_mapping` | same (minor `cam_from_world()` syntax fix) | โš ๏ธ |\n\nThe overall **conversion strategy is identical** โ€” both pipelines go through the same intermediate HDF5 format before feeding COLMAP. The divergence is purely in **how the COLMAP database is populated** (Stage 5), forced by the breaking changes in pycolmap 4.0.3.","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"cp311ใ‹ใ‚‰cp312ใธใฎ็งป่กŒใซไผดใ†ๅค‰ๆ›ด็‚นใฎๆง‹้€ ๅŒ–ใ‚ตใƒžใƒชใƒผใ‚’ๆ—ฅๆœฌ่ชžใซ็ฟป่จณใ—ใพใ—ใŸใ€‚\n\n---\n\n## cp311 โ†’ cp312 ใฎๅค‰ๆ›ด็‚น\n\n### 1. Python ใŠใ‚ˆใณ Wheel ใฎไบ’ๆ›ๆ€ง\n- **pycolmapใฎใ‚ขใƒƒใƒ—ใ‚ฐใƒฌใƒผใƒ‰**: cp311็”จใฎWheel (`pycolmap-3.11.1-cp311`) ใŒใ€ใƒฆใƒผใ‚ถใƒผใƒ‡ใƒผใ‚ฟใ‚ปใƒƒใƒˆใ‹ใ‚‰ๅ–ๅพ—ใ—ใŸ `pycolmap-4.0.3-cp312` ใซ็ฝฎใๆ›ใˆใ‚‰ใ‚Œใพใ—ใŸใ€‚\n- ใ™ในใฆใฎMASt3R้–ข้€ฃใฎWheelใŠใ‚ˆใณใƒ‘ใ‚นใŒใ€`/kaggle/input/mast3r-fix/` ใ‹ใ‚‰ `/kaggle/input/notebooks/stpeteishii/mast3r-cp312/` ใซๅค‰ๆ›ดใ•ใ‚Œใพใ—ใŸใ€‚\n- Pythonใฎใƒใƒผใ‚ธใƒงใƒณใ‚’ๆ˜Ž็คบ็š„ใซ็ขบ่ชใ™ใ‚‹ใŸใ‚ใ€ๅˆๆœŸๆฎต้šŽใซ `print(sys.version)` ใŒ่ฟฝๅŠ ใ•ใ‚Œใพใ—ใŸใ€‚\n\n### 2. FAISS ใฎใ‚คใƒณใ‚นใƒˆใƒผใƒซ\n- cp311ใงใฏๅ˜ไธ€ใฎ `faiss-gpu-cu12` ใ‚’ใ‚คใƒณใ‚นใƒˆใƒผใƒซใ—ใฆใ„ใพใ—ใŸใŒใ€cp312ใงใฏๅฐ‚็”จใƒ‡ใƒผใ‚ฟใ‚ปใƒƒใƒˆใ‹ใ‚‰ FAISS ใŠใ‚ˆใณ CUDA ไพๅญ˜้–ขไฟ‚ (`faiss_gpu_cu12`, `nvidia_cublas_cu12`, `nvidia_cuda_runtime_cu12`) ใฎ3ใคใฎWheelใ‚’ๆ˜Ž็คบ็š„ใซใ‚คใƒณใ‚นใƒˆใƒผใƒซใ™ใ‚‹ใ‚ˆใ†ใซๅค‰ๆ›ดใ•ใ‚Œใพใ—ใŸใ€‚\n\n### 3. `import_into_colmap` โ€” ใƒ•ใƒซๆ›ธใๆ›ใˆ\n- cp311ใฏ `h5_to_db` ใฎๅค–้ƒจ้–ขๆ•ฐใซไพๅญ˜ใ—ใฆใ„ใพใ—ใŸใŒใ€cp312ใงใฏ **`sqlite3` ใ‚’ไฝฟ็”จใ—ใฆใ“ใฎ้–ขๆ•ฐใ‚’ไธ€ใ‹ใ‚‰ๆ›ธใ็›ดใ—ใฆใ„ใพใ™**ใ€‚\n- pycolmap 4.0.3 ใง `Database` API ใŒๅคงๅน…ใซๅค‰ๆ›ดใ•ใ‚ŒใŸใŸใ‚ใ€COLMAPใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚นใฎใ‚นใ‚ญใƒผใƒžไฝœๆˆใ€ใ‚ซใƒกใƒฉใ€็”ปๅƒใ€ใ‚ญใƒผใƒใ‚คใƒณใƒˆใ€ใƒžใƒƒใƒใƒณใ‚ฐๆƒ…ๅ ฑใฎๆŒฟๅ…ฅใ‚’ๆ‰‹ๅ‹•ใง่กŒใ†ๅฟ…่ฆใŒใ‚ใ‚Šใพใ—ใŸใ€‚ใพใŸใ€`pycolmap.Database` ใƒกใ‚ฝใƒƒใƒ‰ใฎใƒ‡ใƒใƒƒใ‚ฐ็”จใ‚คใƒณใƒˆใƒญใ‚นใƒšใ‚ฏใ‚ทใƒงใƒณใ‚‚่ฟฝๅŠ ใ•ใ‚Œใฆใ„ใพใ™ใ€‚\n\n### 4. pycolmap API ใฎ็ ดๅฃŠ็š„ๅค‰ๆ›ด โ€” `cam_from_world`\n- `reconstruct_from_db` ๅ†…ใซใŠใ„ใฆใ€cp311ใงใฏ `image.cam_from_world.rotation` (ๅฑžๆ€ง) ใจใ—ใฆใ‚ขใ‚ฏใ‚ปใ‚นใ—ใฆใ„ใพใ—ใŸใŒใ€cp312ใงใฏ `image.cam_from_world().rotation` (ใƒกใ‚ฝใƒƒใƒ‰ๅ‘ผใณๅ‡บใ—) ใซๅค‰ๆ›ดใ•ใ‚Œใพใ—ใŸใ€‚ใ“ใ‚Œใฏ pycolmap 4.0.3 ใฎๅค‰ๆ›ดใซ้ฉๅฟœใ—ใŸใ‚‚ใฎใงใ™ใ€‚\n\n### 5. cp312็”จ ASMK `.so` ใƒ•ใ‚กใ‚คใƒซใฎใƒญใƒผใƒ‰\n- ASMKใฎใ‚ณใƒณใƒ‘ใ‚คใƒซๆธˆใฟๆ‹กๅผตๆฉŸ่ƒฝใฏPythonใƒใƒผใ‚ธใƒงใƒณใซไพๅญ˜ใ™ใ‚‹ใŸใ‚ใ€cp312ใงใฏ `importlib.util.spec_from_file_location` ใ‚’ไฝฟ็”จใ—ใฆใ€็‰นๅฎšใฎ `.so` ใƒ•ใ‚กใ‚คใƒซ (`hamming.cpython-312-x86_64-linux-gnu.so`) ใ‚’ๆ‰‹ๅ‹•ใงใƒญใƒผใƒ‰ใ™ใ‚‹ๅ‡ฆ็†ใŒ่ฟฝๅŠ ใ•ใ‚Œใพใ—ใŸใ€‚\n\n### 6. ASMK / FAISS ใฎใƒขใƒณใ‚ญใƒผใƒ‘ใƒƒใƒ\n- **`FaissGpuL2Index` ใƒ‘ใƒƒใƒ**: ไบ’ๆ›ๆ€งใฎใŸใ‚ใฎๅ›ž้ฟ็ญ–ใจใ—ใฆใ€`asmk_index.FaissGpuL2Index.create_index` ใŒ CPU ็”จใฎ `IndexFlatL2` ใ‚’ไฝฟ็”จใ™ใ‚‹ใ‚ˆใ†ใซไฟฎๆญฃใ•ใ‚Œใพใ—ใŸใ€‚\n- **`Codebook.quantize` ใƒ‘ใƒƒใƒ**: `_fixed_quantize` ้–ขๆ•ฐใŒ่ฟฝๅŠ ใ•ใ‚Œใ€`asmk_codebook.Codebook.quantize` ใซใƒ‘ใƒƒใƒใŒ้ฉ็”จใ•ใ‚Œใพใ—ใŸใ€‚ใ“ใ‚Œใซใ‚ˆใ‚Šใ€ใ‚ชใƒณใƒ‡ใƒžใƒณใƒ‰ใงใฎ FAISS ใ‚คใƒณใƒ‡ใƒƒใ‚ฏใ‚นๅ†ๆง‹็ฏ‰ใ‚„ใ€`build_ivf` (ๅผ•ๆ•ฐ3ใค) ใจ `query_ivf` (ๅผ•ๆ•ฐ2ใค) ใฎใƒ‘ใ‚น้–“ใซใŠใ‘ใ‚‹ๅผ•ๆ•ฐใฎไธไธ€่‡ดใŒไฟฎๆญฃใ•ใ‚Œใพใ—ใŸใ€‚\n\n### 7. ใƒขใƒ‡ใƒซใฎใƒญใƒผใƒ‰ โ€” `torch.serialization` ใฎไฟฎๆญฃ\n- PyTorch ใฎๆ–ฐใ—ใ„ใƒใƒผใ‚ธใƒงใƒณใงๅฐŽๅ…ฅใ•ใ‚ŒใŸๅŽณๆ ผใชใ‚ปใƒผใƒ•ใƒปใƒ‡ใ‚ทใƒชใ‚ขใƒฉใ‚คใ‚ผใƒผใ‚ทใƒงใƒณ่ฆไปถใ‚’ๆบ€ใŸใ™ใŸใ‚ใ€`load_model` ใ‚’ๅ‘ผใณๅ‡บใ™ๅ‰ใซ `torch.serialization.add_safe_globals([argparse.Namespace])` ใŒ่ฟฝๅŠ ใ•ใ‚Œใพใ—ใŸใ€‚\n\n### 8. `run_one_dataset` ใฎๅ …็‰ขๆ€งๅ‘ไธŠ\n- ใ‚ทใƒงใƒผใƒˆใƒชใ‚นใƒˆไฝœๆˆๅพŒใซ `indexed_pairs` ใŒ็ฉบใฎๅ ดๅˆใ€ใ‚ฏใƒฉใƒƒใ‚ทใƒฅใ›ใšใซใƒญใ‚ฐใ‚’ๅ‡บๅŠ›ใ—ใฆๆญฃๅธธใซใ‚นใ‚ญใƒƒใƒ—ใ™ใ‚‹ใ‚ฌใƒผใƒ‰ๅ‡ฆ็†ใŒ่ฟฝๅŠ ใ•ใ‚Œใพใ—ใŸใ€‚\n- `except` ใƒ–ใƒญใƒƒใ‚ฏใซ `traceback.print_exc()` ใŒ่ฟฝๅŠ ใ•ใ‚Œใ€ใ‚ˆใ‚Š่ฉณ็ดฐใชใ‚จใƒฉใƒผใƒฌใƒใƒผใƒˆใŒๅฏ่ƒฝใซใชใ‚Šใพใ—ใŸใ€‚\n\n### 9. `reconstruct_from_db` โ€” ่ฉณ็ดฐใƒญใ‚ฐใฎๅ‡บๅŠ›\n- ้€ฒ่กŒ็Šถๆณใ‚’ใ‚นใƒ†ใƒƒใƒ—ใ”ใจใซๆŠŠๆกใ—ใ€ๅคฑๆ•—็ฎ‡ๆ‰€ใฎ่จบๆ–ญใ‚’ๅฎนๆ˜“ใซใ™ใ‚‹ใŸใ‚ใ€`sys.stdout.flush()` ใ‚’ๅซใ‚€ `log()` ใƒ˜ใƒซใƒ‘ใƒผ้–ขๆ•ฐใŒ่ฟฝๅŠ ใ•ใ‚Œใพใ—ใŸใ€‚\n\n### 10. ใ‚นใƒฌใƒƒใƒ‰ใƒ—ใƒผใƒซ โ€” `max_workers` ใฎๅ‰Šๆธ›\n- `run_mast3r_pipeline` ๅ†…ใฎ `ThreadPoolExecutor` ใŒใ€`max_workers=2` (cp311) ใ‹ใ‚‰ `max_workers=1` (cp312) ใซๅค‰ๆ›ดใ•ใ‚Œใพใ—ใŸใ€‚ใ“ใ‚Œใฏใƒกใƒขใƒช่ฒ ่ทใฎ่ปฝๆธ›ใ€ใพใŸใฏๆ–ฐใ—ใ„็’ฐๅขƒไธ‹ใงใฎใƒฌใƒผใ‚นใ‚ณใƒณใƒ‡ใ‚ฃใ‚ทใƒงใƒณๅ›ž้ฟใŒ็›ฎ็š„ใจ่€ƒใˆใ‚‰ใ‚Œใพใ™ใ€‚\n\n### 11. ใƒ‡ใƒผใ‚ฟใ‚ปใƒƒใƒˆใŠใ‚ˆใณๅ…ฅๅŠ›ใƒ‘ใ‚นใฎๅค‰ๆ›ด\n- `data_dir` ใŒ `/kaggle/input/image-matching-challenge-2025` ใ‹ใ‚‰ `/kaggle/input/competitions/image-matching-challenge-2025` ใซๅค‰ๆ›ดใ•ใ‚Œใพใ—ใŸใ€‚\n- imc-utils ใฎ `sys.path` ใ‚จใƒณใƒˆใƒชใŒๆ›ดๆ–ฐใ•ใ‚Œใ€ใ‚นใ‚ณใ‚ขใƒชใƒณใ‚ฐใƒ–ใƒญใƒƒใ‚ฏๅ†…ใฎใƒกใƒˆใƒชใƒƒใ‚ฏ CSV ใƒ‘ใ‚นใ‚‚ใใ‚Œใซๅˆใ‚ใ›ใฆไฟฎๆญฃใ•ใ‚Œใพใ—ใŸใ€‚\n\n---\n\n**ใพใจใ‚**: cp312 ใธใฎ็งป่กŒใฏใ€ไธปใซ pycolmap ใฎใ‚ขใƒƒใƒ—ใ‚ฐใƒฌใƒผใƒ‰ (3.11.1 โ†’ 4.0.3) ใซไผดใ† API ๅค‰ๆ›ดใธใฎๅฏพๅฟœใ€Python 3.12 ็”จใฎ ASMK ๆ‹กๅผตๆฉŸ่ƒฝใŠใ‚ˆใณ FAISS ็ตฑๅˆใฎ้ฉๅฟœใ€ใใ—ใฆ PyTorch ใฎใ‚ทใƒชใ‚ขใƒฉใ‚คใ‚ผใƒผใ‚ทใƒงใƒณไฟฎๆญฃใŒไธญๅฟƒใจใชใฃใฆใ„ใพใ™ใ€‚ใ“ใ‚Œใ‚‰ใฎไบ’ๆ›ๆ€งไฟฎๆญฃใซๅŠ ใˆใ€ใ‚จใƒฉใƒผใƒใƒณใƒ‰ใƒชใƒณใ‚ฐใ‚„ใƒญใ‚ฐๅ‡บๅŠ›ใ€็ฉบใƒšใ‚ขๅฏพ็ญ–ใชใฉใ€ๅ …็‰ขๆ€งใจ่ฆณๆธฌๆ€งใ‚’้ซ˜ใ‚ใ‚‹ใŸใ‚ใฎๆ”นๅ–„ใ‚‚ๆ•ฐๅคšใๅฐŽๅ…ฅใ•ใ‚Œใฆใ„ใพใ™ใ€‚","metadata":{}},{"cell_type":"markdown","source":"MASt3Rใฎๅ‡บๅŠ›ใ‹ใ‚‰COLMAPๅฝขๅผใธใฎๅค‰ๆ›ใƒ‘ใ‚คใƒ—ใƒฉใ‚คใƒณๅ…จ่กŒ็จ‹ใฎ่ฉณ็ดฐใชๅˆ†ๆžใจใ€cp311ใจcp312ใงๅ…ฑ้€šใ™ใ‚‹็‚นใƒป็•ฐใชใ‚‹็‚นใฎใพใจใ‚ใ‚’ๆ—ฅๆœฌ่ชžใซ็ฟป่จณใ—ใพใ—ใŸใ€‚\n\n---\n\n## ใƒ‘ใ‚คใƒ—ใƒฉใ‚คใƒณใฎๆฆ‚่ฆ\n\nๅค‰ๆ›ใฏไปฅไธ‹ใฎ **6ใคใฎ้€ฃ็ถšใ—ใŸใ‚นใƒ†ใƒผใ‚ธ** ใงๆง‹ๆˆใ•ใ‚Œใฆใ„ใพใ™ใ€‚\n\n\n\n```\nMASt3R ๆŽจ่ซ– (Inference)\n โ†“\n [1] extract_correspondences_nonsym โ†’ ็”Ÿใƒ”ใ‚ฏใ‚ปใƒซใƒžใƒƒใƒใƒณใ‚ฐ\n โ†“\n [2] transform_keypoints_to_original โ†’ ๅ…ƒ็”ปๅƒ็ฉบ้–“ใฎๅบงๆจ™ใธๅค‰ๆ›\n โ†“\n [3] unify_keypoints_and_matches โ†’ ใ‚ฐใƒญใƒผใƒใƒซใช็‰นๅพด็‚นIDใฎๅ‰ฒใ‚Šๅฝ“ใฆ\n โ†“\n [4] save_unified_keypoints_and_matches โ†’ keypoints.h5 / matches.h5 / pairs.txt\n โ†“\n [5] import_into_colmap โ†’ COLMAP SQLite ใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚น\n โ†“\n [6] verify_matches + incremental_mapping โ†’ ๅ†ๆง‹ๆˆใ•ใ‚ŒใŸใƒใƒผใ‚บ\n```\n\n---\n\n## ใ‚นใƒ†ใƒผใ‚ธๅˆฅ่ฉณ็ดฐ่งฃ่ชฌ\n\n### ใ‚นใƒ†ใƒผใ‚ธ 1 โ€” MASt3RๆŽจ่ซ–ใจๅฏพๅฟœ้–ขไฟ‚ใฎๆŠฝๅ‡บ (`match_with_mast3r_and_save`)\n\nๅ„็”ปๅƒใƒšใ‚ขใซๅฏพใ—ใฆไปฅไธ‹ใฎๅ‡ฆ็†ใ‚’่กŒใ„ใพใ™๏ผš\n1. `load_images()` ใงไธกๆ–นใฎ็”ปๅƒใ‚’512pxใซใƒชใ‚ตใ‚คใ‚บใ—ใพใ™๏ผˆDUST3Rใฎๆ…ฃ็ฟ’๏ผ‰ใ€‚\n2. `inference()` ใงMASt3Rใฎใ‚จใƒณใ‚ณใƒผใƒ€ใƒผใƒปใƒ‡ใ‚ณใƒผใƒ€ใƒผใ‚’ๅฎŸ่กŒใ—ใ€ไธกๆ–นใฎ่ฆ–็‚นใฎๅฏ†ใช่จ˜่ฟฐๅญใƒžใƒƒใƒ— (`desc`) ใจไฟก้ ผๅบฆใƒžใƒƒใƒ— (`desc_conf`) ใ‚’็”Ÿๆˆใ—ใพใ™ใ€‚\n3. `extract_correspondences_nonsym()` ใง่จ˜่ฟฐๅญ็ฉบ้–“ใซใŠใ‘ใ‚‹้žๅฏพ็งฐใชๆœ€่ฟ‘ๅ‚ๅฏพๅฟœใ‚’่จˆ็ฎ—ใ—ใ€**ใƒชใ‚ตใ‚คใ‚บ/ใ‚ฏใƒญใƒƒใƒ—ๅพŒ**ใฎ็”ปๅƒ็ฉบ้–“ใงใฎใƒžใƒƒใƒใƒณใ‚ฐใƒ”ใ‚ฏใ‚ปใƒซๅบงๆจ™ `(x, y)` ใจไฟก้ ผๅบฆใ‚นใ‚ณใ‚ขใ‚’่ฟ”ใ—ใพใ™ใ€‚\n4. `CONFIG.MATCH_CONF_TH = 1.001` ๆœชๆบ€ใฎใƒžใƒƒใƒใƒณใ‚ฐใฏ็ ดๆฃ„ใ•ใ‚Œใ€ใ•ใ‚‰ใซ็ซฏใฎ3ใƒ”ใ‚ฏใ‚ปใƒซใ‚’้™คๅค–ใ™ใ‚‹ใƒžใ‚นใ‚ฏใŒ้ฉ็”จใ•ใ‚Œใพใ™ใ€‚\n\n**โ†’ cp311 ใจ cp312 ใงๅŒไธ€ใ€‚**\n\n---\n\n### ใ‚นใƒ†ใƒผใ‚ธ 2 โ€” ๅบงๆจ™ใฎ้€†ๆŠ•ๅฝฑ (`transform_keypoints_to_original`)\n\n`load_images()` ใฏ็”ปๅƒใ‚’ใƒชใ‚ตใ‚คใ‚บใ—ใ€ใ‚ปใƒณใ‚ฟใƒผใ‚ฏใƒญใƒƒใƒ—ใ—ใฆใ‹ใ‚‰MASt3Rใซๆธกใ™ใŸใ‚ใ€ใƒžใƒƒใƒใƒณใ‚ฐๅบงๆจ™ใฏใ€Œๅ‡ฆ็†ๅพŒใฎ็”ปๅƒ็ฉบ้–“ใ€ใซใชใฃใฆใ„ใพใ™ใ€‚ใ“ใฎ้–ขๆ•ฐใฏใ‚ฏใƒญใƒƒใƒ—ใฎใ‚ชใƒ•ใ‚ปใƒƒใƒˆใจใ‚นใ‚ฑใƒผใƒซๅ› ๅญใ‚’้€†็ฎ—ใ—ใ€**ๅ…ƒใฎ็”ปๅƒ็ฉบ้–“**ใฎๅบงๆจ™ใ‚’ๅพฉๅ…ƒใ—ใพใ™ใ€‚\n\n่จˆ็ฎ—ๅ†…ๅฎน๏ผš\n- ใƒชใ‚ตใ‚คใ‚บใ‚นใ‚ฑใƒผใƒซๅ› ๅญ๏ผˆ้•ท่พบ โ†’ 512๏ผ‰ใ‚’ๅ†่จˆ็ฎ—ใ€‚\n- ใ‚ฏใƒญใƒƒใƒ—ใ‚ชใƒ•ใ‚ปใƒƒใƒˆ๏ผˆ16ใƒ”ใ‚ฏใ‚ปใƒซใ‚ฐใƒชใƒƒใƒ‰ใซๆ•ดๅˆ—ใ•ใ‚ŒใŸ `halfw`, `halfh`๏ผ‰ใ‚’ๅ†่จˆ็ฎ—ใ€‚\n- ใ‚ชใƒ•ใ‚ปใƒƒใƒˆใ‚’ๅŠ ็ฎ—ใ—ใ€ใ‚นใ‚ฑใƒผใƒซๅ› ๅญใงๅ‰ฒใ‚‹ใ“ใจใงๅ…ƒๅบงๆจ™ใ‚’็ฎ—ๅ‡บใ€‚\n\n**โ†’ cp311 ใจ cp312 ใงๅŒไธ€ใ€‚**\n\n---\n\n### ใ‚นใƒ†ใƒผใ‚ธ 3 โ€” ็‰นๅพด็‚นใฎ็ตฑไธ€ๅŒ– (`unify_keypoints_and_matches`)\n\n1ๆžšใฎ็”ปๅƒใฏ่ค‡ๆ•ฐใฎใƒšใ‚ขใซ็™ปๅ ดใ™ใ‚‹ใŸใ‚ใ€ๅŒใ˜็‰ฉ็†็š„ใช็‚นใŒใƒšใ‚ขใ”ใจใซๅพฎๅฆ™ใซ็•ฐใชใ‚‹ๆตฎๅ‹•ๅฐๆ•ฐ็‚นๅบงๆจ™ใจใ—ใฆๆคœๅ‡บใ•ใ‚Œใ‚‹ใ“ใจใŒใ‚ใ‚Šใพใ™ใ€‚ใ“ใฎใ‚นใƒ†ใƒผใ‚ธใงใฏ๏ผš\n1. ใ™ในใฆใฎใƒšใ‚ขใ‹ใ‚‰ใ€ๅ„็”ปๅƒใ”ใจใฎๅ…จๅบงๆจ™ใ‚’ๅŽ้›†ใ—ใพใ™ใ€‚\n2. ๅบงๆจ™ใ‚’ๅฐๆ•ฐ็‚น็ฌฌ1ไฝใงไธธใ‚ใ€`np.unique` ใ‚’ไฝฟใฃใฆ้‡่ค‡ใ‚’ๆŽ’้™คใ—ใพใ™ใ€‚\n3. ้‡่ค‡ใ‚’้™คใ„ใŸๅ„ๅบงๆจ™ใซ **ใ‚ฐใƒญใƒผใƒใƒซใชๆ•ดๆ•ฐID** ใ‚’ๅ‰ฒใ‚Šๅฝ“ใฆใพใ™ใ€‚\n4. ๅ„ใƒšใ‚ขใฎๅบงๆจ™ใƒ™ใƒผใ‚นใฎใƒžใƒƒใƒใƒณใ‚ฐ `(x1,y1,x2,y2)` ใ‚’ใ€ใƒซใƒƒใ‚ฏใ‚ขใƒƒใƒ—ใƒ†ใƒผใƒ–ใƒซใ‚’็”จใ„ใฆใ‚ฐใƒญใƒผใƒใƒซIDใฎใƒšใ‚ข `(id1, id2)` ใซๅค‰ๆ›ใ—ใพใ™ใ€‚\n\nใ“ใ‚Œใซใ‚ˆใ‚Šใ€COLMAPไบ’ๆ›ใฎใƒ‡ใƒผใ‚ฟๆง‹้€ ใงใ‚ใ‚‹ `global_keypoints[img]` ใจ `global_matches[(img1, img2)]` ใŒ็”Ÿๆˆใ•ใ‚Œใพใ™ใ€‚\n\n**โ†’ cp311 ใจ cp312 ใงๅŒไธ€ใ€‚**\n\n---\n\n### ใ‚นใƒ†ใƒผใ‚ธ 4 โ€” HDF5 ใ‚ทใƒชใ‚ขใƒฉใ‚คใ‚บ (`save_unified_keypoints_and_matches`)\n\n`feature_dir` ใซไปฅไธ‹ใฎ3ใคใฎใƒ•ใ‚กใ‚คใƒซใ‚’ๅ‡บๅŠ›ใ—ใพใ™๏ผš\n- `keypoints.h5` โ€” ็”ปๅƒใ”ใจใฎ `(N, 2)` ๅบงๆจ™้…ๅˆ—ใ€‚\n- `matches.h5` โ€” ใƒšใ‚ขใ”ใจใฎ `(M, 2)` ใ‚ฐใƒญใƒผใƒใƒซID้…ๅˆ—๏ผˆ`MAST3R_MIN_PAIR = 15` ไปฅไธŠใฎใƒžใƒƒใƒใƒณใ‚ฐใŒใ‚ใ‚‹ใƒšใ‚ขใฎใฟ๏ผ‰ใ€‚\n- `pairs.txt` โ€” ็”ปๅƒๅใฎใƒšใ‚ขใƒชใ‚นใƒˆ๏ผˆ`verify_matches` ใฎๅ…ฅๅŠ›ใซไฝฟ็”จ๏ผ‰ใ€‚\n\n**โ†’ cp311 ใจ cp312 ใงๅŒไธ€ใ€‚**\n\n---\n\n### ใ‚นใƒ†ใƒผใ‚ธ 5 โ€” COLMAP ใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚นใธใฎใ‚คใƒณใƒใƒผใƒˆ (`import_into_colmap`) โš ๏ธ **็›ธ้•็‚น**\n\nใ“ใฎใ‚นใƒ†ใƒผใ‚ธใฏใ€2ใคใฎใƒใƒผใ‚ธใƒงใƒณ้–“ใง**ๆ นๆœฌ็š„ใช่จญ่จˆใŒ็•ฐใชใ‚‹ๅ”ฏไธ€ใฎ็ฎ‡ๆ‰€**ใงใ™ใ€‚\n\n**cp311** โ€” `h5_to_db` ใ‹ใ‚‰ใ‚คใƒณใƒใƒผใƒˆใ•ใ‚ŒใŸๅค–้ƒจใƒ˜ใƒซใƒ‘ใƒผ้–ขๆ•ฐใซใ™ในใฆใ‚’ๅง”ใญใพใ™ใ€‚\n```python\nfrom h5_to_db import *\nimport_into_colmap(img_dir, feature_dir=feature_dir, database_path=database_path)\n```\nๅฎŸ่ฃ…ใฏ `pycolmap3-11-imc-utils` ใƒ‡ใƒผใ‚ฟใ‚ปใƒƒใƒˆๅ†…ใซ้š ่”ฝใ•ใ‚ŒใฆใŠใ‚Šใ€ใŠใใ‚‰ใ pycolmap 3.x ใฎ้ซ˜ใƒฌใƒ™ใƒซ `Database` API ใ‚’ไฝฟ็”จใ—ใฆใ„ใพใ™ใ€‚\n\n**cp312** โ€” pycolmap 4.0.3 ใฎ `Database` API ใซ้žไบ’ๆ›ใชๅค‰ๆ›ดใŒใ‚ใฃใŸใŸใ‚ใ€็”Ÿใฎ `sqlite3` ใ‚’ไฝฟ็”จใ—ใฆ**ใ“ใฎ้–ขๆ•ฐใ‚’ใ‚ผใƒญใ‹ใ‚‰ๅฎŒๅ…จใซๅ†ๅฎŸ่ฃ…**ใ—ใฆใ„ใพใ™ใ€‚ๆ‰‹ๅ‹•ใงไปฅไธ‹ใฎๅ‡ฆ็†ใ‚’่กŒใ„ใพใ™๏ผš\n1. COLMAPใฎ6ใคใฎใƒ†ใƒผใƒ–ใƒซ๏ผˆ`cameras`, `images`, `keypoints`, `matches`, `two_view_geometries`, `descriptors`๏ผ‰ใฎใ‚นใ‚ญใƒผใƒžใ‚’ `CREATE TABLE IF NOT EXISTS` ใงไฝœๆˆใ€‚\n2. `keypoints.h5` ใ‚’่ชญใฟ่พผใฟใ€ๅ„็”ปๅƒใซๅฏพใ—ใฆ `cameras` ่กŒ๏ผˆ`SIMPLE_RADIAL` ใƒขใƒ‡ใƒซใ‚’ไฝฟ็”จใ—ใ€`f = max(w,h)`, `cx = w/2`, `cy = h/2`, `k = 0` ใจ่จญๅฎš๏ผ‰ใจ `images` ่กŒใ‚’ๆŒฟๅ…ฅใ€‚\n3. ็‰นๅพด็‚นใฎใƒใ‚คใƒŠใƒชใƒ‡ใƒผใ‚ฟ๏ผˆBlob๏ผ‰ใ‚’ `float32` ใƒใ‚คใƒˆใจใ—ใฆ็›ดๆŽฅๆŒฟๅ…ฅใ€‚\n4. `matches.h5` ใ‚’่ชญใฟ่พผใฟใ€ๆจ™ๆบ–็š„ใช COLMAP ใฎใ‚จใƒณใ‚ณใƒผใƒ‡ใ‚ฃใƒณใ‚ฐๆ–นๅผ `pair_id = id1 * 2147483647 + id2` ใ‚’็”จใ„ใฆใƒžใƒƒใƒใƒณใ‚ฐใƒ‡ใƒผใ‚ฟใ‚’ `uint32` ใƒใ‚คใƒˆใจใ—ใฆๆŒฟๅ…ฅใ€‚\n\nๆœ€็ต‚็š„ใซ็”Ÿๆˆใ•ใ‚Œใ‚‹ SQLite ใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚นใฎๆง‹้€ ใฏๅŒใ˜ใงใ™ใŒใ€ใใ“ใซ่‡ณใ‚‹ใƒ—ใƒญใ‚ปใ‚นใŒๅฎŒๅ…จใซ็•ฐใชใ‚Šใพใ™ใ€‚\n\n---\n\n### ใ‚นใƒ†ใƒผใ‚ธ 6 โ€” ๅนพไฝ•ๅญฆ็š„ๆคœ่จผใจๅข—ๅˆ†ๅพฉๅ…ƒ (`reconstruct_from_db`) โš ๏ธ **่ปฝๅพฎใชAPIใฎๅทฎ**\n\nไธกๆ–นใฎใƒใƒผใ‚ธใƒงใƒณใงๅŒใ˜2ใคใฎ pycolmap ้–ขๆ•ฐใ‚’ๅ‘ผใณๅ‡บใ—ใพใ™๏ผš\n```python\npycolmap.verify_matches(database_path, pairs_path, TwoViewGeometryOptions())\npycolmap.incremental_mapping(database_path, image_path, output_path, options)\n```\n- `verify_matches`: ๅ„ใƒšใ‚ขใซๅฏพใ—ใฆ RANSAC๏ผˆๅŸบ็คŽ่กŒๅˆ—/ๆœฌ่ณช่กŒๅˆ—ใฎๆŽจๅฎš๏ผ‰ใ‚’ๅฎŸ่กŒใ—ใ€ๆคœ่จผๆธˆใฟใฎใ‚คใƒณใƒฉใ‚คใ‚ขๅนพไฝ•ๆƒ…ๅ ฑใ‚’ `two_view_geometries` ใซๆ›ธใๆˆปใ—ใพใ™ใ€‚\n- `incremental_mapping`: ๅฎŒๅ…จใช SfM๏ผˆStructure from Motion๏ผ‰ใ‚’ๅฎŸ่กŒใ—ใ€ใ‚ซใƒกใƒฉใƒใƒผใ‚บใ‚’ๆฎต้šŽ็š„ใซๅพฉๅ…ƒใ—ใพใ™ใ€‚\n\nใ‚ณใƒผใƒ‰ไธŠใฎๅ”ฏไธ€ใฎ้•ใ„ใฏใ€ใƒžใƒƒใƒ”ใƒณใ‚ฐๅพŒใฎๅ›ž่ปขใƒปไธฆ้€ฒๆƒ…ๅ ฑใฎๅ–ๅพ—ๆ–นๆณ•ใงใ™ใ€‚\n\n| | cp311 | cp312 |\n|---|---|---|\n| ใ‚ขใ‚ฏใ‚ปใ‚นๅฝขๅผ | `image.cam_from_world.rotation` | `image.cam_from_world().rotation` |\n| ็†็”ฑ | pycolmap 3.x: ๅฑžๆ€ง(attribute) | pycolmap 4.x: ใƒกใ‚ฝใƒƒใƒ‰ๅ‘ผใณๅ‡บใ— |\n\n**โ†’ ๆ„ๅ‘ณ็š„ใซใฏๅŒไธ€ใงใ™ใŒใ€APIใฎๅค‰ๆ›ดใซใ‚ˆใ‚Šๆง‹ๆ–‡ใŒ็•ฐใชใ‚Šใพใ™ใ€‚**\n\n---\n\n## ๆฏ”่ผƒใพใจใ‚่กจ\n\n| ใ‚นใƒ†ใƒผใ‚ธ | cp311 | cp312 | ๅŒไธ€๏ผŸ |\n|---|---|---|---|\n| MASt3RๆŽจ่ซ– + ๅฏพๅฟœ้–ขไฟ‚ๆŠฝๅ‡บ | `extract_correspondences_nonsym` | ๅŒๅทฆ | โœ… |\n| ๅ…ƒ็”ปๅƒ็ฉบ้–“ใธใฎๅบงๆจ™้€†ๆŠ•ๅฝฑ | `transform_keypoints_to_original` | ๅŒๅทฆ | โœ… |\n| ็‰นๅพด็‚น็ตฑไธ€ & ใ‚ฐใƒญใƒผใƒใƒซIDไป˜ไธŽ | `unify_keypoints_and_matches` | ๅŒๅทฆ | โœ… |\n| HDF5 ใ‚ทใƒชใ‚ขใƒฉใ‚คใ‚บ | `save_unified_keypoints_and_matches` | ๅŒๅทฆ | โœ… |\n| COLMAP DB ใ‚คใƒณใƒใƒผใƒˆ | ๅค–้ƒจ `h5_to_db` (pycolmap 3.x API) | ็‹ฌ่‡ชใฎ `sqlite3` ๅ†ๅฎŸ่ฃ… | โŒ |\n| ๅนพไฝ•ๆคœ่จผ + ใƒžใƒƒใƒ”ใƒณใ‚ฐ | `verify_matches` + `incremental_mapping` | ๅŒๅทฆ๏ผˆ`cam_from_world()` ๆง‹ๆ–‡ใฎใฟไฟฎๆญฃ๏ผ‰ | โš ๏ธ |\n\nๅ…จไฝ“ใจใ—ใฆใ€**ๅค‰ๆ›ๆˆฆ็•ฅใใฎใ‚‚ใฎใฏๅŒไธ€**ใงใ™ใ€‚ใฉใกใ‚‰ใฎใƒ‘ใ‚คใƒ—ใƒฉใ‚คใƒณใ‚‚ COLMAP ใซๆŠ•ๅ…ฅใ™ใ‚‹ๅ‰ใซๅŒใ˜ไธญ้–“ HDF5 ๅฝขๅผใ‚’็ตŒ็”ฑใ—ใพใ™ใ€‚็›ธ้•็‚นใฏ็ด”็ฒ‹ใซใ€pycolmap 4.0.3 ใฎ็ ดๅฃŠ็š„ๅค‰ๆ›ดใซใ‚ˆใฃใฆๅผทๅˆถใ•ใ‚ŒใŸ **COLMAP ใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚นใธใฎใƒ‡ใƒผใ‚ฟๆŠ•ๅ…ฅๆ–นๆณ•๏ผˆใ‚นใƒ†ใƒผใ‚ธ 5๏ผ‰** ใซใ‚ใ‚Šใพใ™ใ€‚","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}}]}
cp311_2025-05-mg20-25-mast3r-imc2025-submission-is-trai.ipynb ADDED
@@ -0,0 +1 @@
 
 
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}]}
cp312_mb-ongmx20-25-mast3r-sfm-imc2025-ong-sub-is.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"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}]}