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}]}
|