{ "cells": [ { "cell_type": "markdown", "id": "3a915c6d", "metadata": { "papermill": { "duration": 0.013745, "end_time": "2026-01-03T14:33:41.440977", "exception": false, "start_time": "2026-01-03T14:33:41.427232", "status": "completed" }, "tags": [] }, "source": [] }, { "cell_type": "markdown", "id": "ad9a3936", "metadata": { "papermill": { "duration": 0.013431, "end_time": "2026-01-03T14:33:41.467558", "exception": false, "start_time": "2026-01-03T14:33:41.454127", "status": "completed" }, "tags": [] }, "source": [ "# **Fe IMC2025_11th**\n", "### **image matching and 3D reconstruction**" ] }, { "cell_type": "markdown", "id": "8950f00e", "metadata": { "papermill": { "duration": 0.014338, "end_time": "2026-01-03T14:33:41.496041", "exception": false, "start_time": "2026-01-03T14:33:41.481703", "status": "completed" }, "tags": [] }, "source": [ "gpu required" ] }, { "cell_type": "markdown", "id": "367fc283", "metadata": { "papermill": { "duration": 0.013687, "end_time": "2026-01-03T14:33:41.523802", "exception": false, "start_time": "2026-01-03T14:33:41.510115", "status": "completed" }, "tags": [] }, "source": [ "2026/01/03 11:30" ] }, { "cell_type": "code", "execution_count": 1, "id": "20bd9f2e", "metadata": { "execution": { "iopub.execute_input": "2026-01-03T14:33:41.553098Z", "iopub.status.busy": "2026-01-03T14:33:41.552605Z", "iopub.status.idle": "2026-01-03T14:34:01.627508Z", "shell.execute_reply": "2026-01-03T14:34:01.626475Z" }, "papermill": { "duration": 20.091557, "end_time": "2026-01-03T14:34:01.629248", "exception": false, "start_time": "2026-01-03T14:33:41.537691", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selecting previously unselected package colmap.\r\n", "(Reading database ... 127400 files and directories currently installed.)\r\n", "Preparing to unpack ./colmap_3.7-2_amd64.deb ...\r\n", "Unpacking colmap (3.7-2) ...\r\n", "Selecting previously unselected package libamd2:amd64.\r\n", "Preparing to unpack .../libamd2_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libcamd2:amd64.\r\n", "Preparing to unpack .../libcamd2_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libcamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libccolamd2:amd64.\r\n", "Preparing to unpack .../libccolamd2_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libccolamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libceres2.\r\n", "Preparing to unpack .../libceres2_2.0.0+dfsg1-5_amd64.deb ...\r\n", "Unpacking libceres2 (2.0.0+dfsg1-5) ...\r\n", "Selecting previously unselected package libcholmod3:amd64.\r\n", "Preparing to unpack .../libcholmod3_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libcholmod3:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libcolamd2:amd64.\r\n", "Preparing to unpack .../libcolamd2_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libcolamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libcxsparse3:amd64.\r\n", "Preparing to unpack .../libcxsparse3_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libcxsparse3:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libevdev2:amd64.\r\n", "Preparing to unpack .../libevdev2_1.12.1+dfsg-1_amd64.deb ...\r\n", "Unpacking libevdev2:amd64 (1.12.1+dfsg-1) ...\r\n", "Selecting previously unselected package libfreeimage3:amd64.\r\n", "Preparing to unpack .../libfreeimage3_3.18.0+ds2-6ubuntu5.1_amd64.deb ...\r\n", "Unpacking libfreeimage3:amd64 (3.18.0+ds2-6ubuntu5.1) ...\r\n", "Selecting previously unselected package libgflags2.2.\r\n", "Preparing to unpack .../libgflags2.2_2.2.2-2_amd64.deb ...\r\n", "Unpacking libgflags2.2 (2.2.2-2) ...\r\n", "Selecting previously unselected package libgoogle-glog0v5.\r\n", "Preparing to unpack .../libgoogle-glog0v5_0.5.0+really0.4.0-2_amd64.deb ...\r\n", "Unpacking libgoogle-glog0v5 (0.5.0+really0.4.0-2) ...\r\n", "Selecting previously unselected package libgudev-1.0-0:amd64.\r\n", "Preparing to unpack .../libgudev-1.0-0_1%3a237-2build1_amd64.deb ...\r\n", "Unpacking libgudev-1.0-0:amd64 (1:237-2build1) ...\r\n", "Selecting previously unselected package libinput10:amd64.\r\n", "Preparing to unpack .../libinput10_1.20.0-1ubuntu0.3_amd64.deb ...\r\n", "Unpacking libinput10:amd64 (1.20.0-1ubuntu0.3) ...\r\n", "Selecting previously unselected package libinput-bin.\r\n", "Preparing to unpack .../libinput-bin_1.20.0-1ubuntu0.3_amd64.deb ...\r\n", "Unpacking libinput-bin (1.20.0-1ubuntu0.3) ...\r\n", "Selecting previously unselected package libmd4c0:amd64.\r\n", "Preparing to unpack ./libmd4c0_0.4.8-1_amd64.deb ...\r\n", "Unpacking libmd4c0:amd64 (0.4.8-1) ...\r\n", "Selecting previously unselected package libmetis5:amd64.\r\n", "Preparing to unpack .../libmetis5_5.1.0.dfsg-7build2_amd64.deb ...\r\n", "Unpacking libmetis5:amd64 (5.1.0.dfsg-7build2) ...\r\n", "Selecting previously unselected package libmtdev1:amd64.\r\n", "Preparing to unpack .../libmtdev1_1.1.6-1build4_amd64.deb ...\r\n", "Unpacking libmtdev1:amd64 (1.1.6-1build4) ...\r\n", "Selecting previously unselected package libqt5core5a:amd64.\r\n", "Preparing to unpack .../libqt5core5a_5.15.3+dfsg-2ubuntu0.2_amd64.deb ...\r\n", "Unpacking libqt5core5a:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Selecting previously unselected package libqt5dbus5:amd64.\r\n", "Preparing to unpack .../libqt5dbus5_5.15.3+dfsg-2ubuntu0.2_amd64.deb ...\r\n", "Unpacking libqt5dbus5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Selecting previously unselected package libqt5gui5:amd64.\r\n", "Preparing to unpack .../libqt5gui5_5.15.3+dfsg-2ubuntu0.2_amd64.deb ...\r\n", "Unpacking libqt5gui5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Selecting previously unselected package libqt5network5:amd64.\r\n", "Preparing to unpack .../libqt5network5_5.15.3+dfsg-2ubuntu0.2_amd64.deb ...\r\n", "Unpacking libqt5network5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Selecting previously unselected package libqt5svg5:amd64.\r\n", "Preparing to unpack .../libqt5svg5_5.15.3-1_amd64.deb ...\r\n", "Unpacking libqt5svg5:amd64 (5.15.3-1) ...\r\n", "Selecting previously unselected package libqt5widgets5:amd64.\r\n", "Preparing to unpack .../libqt5widgets5_5.15.3+dfsg-2ubuntu0.2_amd64.deb ...\r\n", "Unpacking libqt5widgets5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Selecting previously unselected package libraw20:amd64.\r\n", "Preparing to unpack .../libraw20_0.20.2-2ubuntu2.22.04.1_amd64.deb ...\r\n", "Unpacking libraw20:amd64 (0.20.2-2ubuntu2.22.04.1) ...\r\n", "Selecting previously unselected package libspqr2:amd64.\r\n", "Preparing to unpack .../libspqr2_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libspqr2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libsuitesparseconfig5:amd64.\r\n", "Preparing to unpack .../libsuitesparseconfig5_1%3a5.10.1+dfsg-4build1_amd64.deb ...\r\n", "Unpacking libsuitesparseconfig5:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Selecting previously unselected package libwacom9:amd64.\r\n", "Preparing to unpack ./libwacom9_2.2.0-1_amd64.deb ...\r\n", "Unpacking libwacom9:amd64 (2.2.0-1) ...\r\n", "Selecting previously unselected package libwacom-bin.\r\n", "Preparing to unpack .../libwacom-bin_2.2.0-1_amd64.deb ...\r\n", "Unpacking libwacom-bin (2.2.0-1) ...\r\n", "Selecting previously unselected package libwacom-common.\r\n", "Preparing to unpack .../libwacom-common_2.2.0-1_all.deb ...\r\n", "Unpacking libwacom-common (2.2.0-1) ...\r\n", "Selecting previously unselected package libxcb-icccm4:amd64.\r\n", "Preparing to unpack .../libxcb-icccm4_0.4.1-1.1build2_amd64.deb ...\r\n", "Unpacking libxcb-icccm4:amd64 (0.4.1-1.1build2) ...\r\n", "Selecting previously unselected package libxcb-image0:amd64.\r\n", "Preparing to unpack .../libxcb-image0_0.4.0-2_amd64.deb ...\r\n", "Unpacking libxcb-image0:amd64 (0.4.0-2) ...\r\n", "Selecting previously unselected package libxcb-keysyms1:amd64.\r\n", "Preparing to unpack .../libxcb-keysyms1_0.4.0-1build3_amd64.deb ...\r\n", "Unpacking libxcb-keysyms1:amd64 (0.4.0-1build3) ...\r\n", "Selecting previously unselected package libxcb-render-util0:amd64.\r\n", "Preparing to unpack .../libxcb-render-util0_0.3.9-1build3_amd64.deb ...\r\n", "Unpacking libxcb-render-util0:amd64 (0.3.9-1build3) ...\r\n", "Selecting previously unselected package libxcb-util1:amd64.\r\n", "Preparing to unpack .../libxcb-util1_0.4.0-1build2_amd64.deb ...\r\n", "Unpacking libxcb-util1:amd64 (0.4.0-1build2) ...\r\n", "Selecting previously unselected package libxcb-xinerama0:amd64.\r\n", "Preparing to unpack .../libxcb-xinerama0_1.14-3ubuntu3_amd64.deb ...\r\n", "Unpacking libxcb-xinerama0:amd64 (1.14-3ubuntu3) ...\r\n", "Selecting previously unselected package libxcb-xinput0:amd64.\r\n", "Preparing to unpack .../libxcb-xinput0_1.14-3ubuntu3_amd64.deb ...\r\n", "Unpacking libxcb-xinput0:amd64 (1.14-3ubuntu3) ...\r\n", "Selecting previously unselected package libxcb-xkb1:amd64.\r\n", "Preparing to unpack .../libxcb-xkb1_1.14-3ubuntu3_amd64.deb ...\r\n", "Unpacking libxcb-xkb1:amd64 (1.14-3ubuntu3) ...\r\n", "Selecting previously unselected package libxkbcommon-x11-0:amd64.\r\n", "Preparing to unpack .../libxkbcommon-x11-0_1.4.0-1_amd64.deb ...\r\n", "Unpacking libxkbcommon-x11-0:amd64 (1.4.0-1) ...\r\n", "Selecting previously unselected package qt5-gtk-platformtheme:amd64.\r\n", "Preparing to unpack .../qt5-gtk-platformtheme_5.15.3+dfsg-2ubuntu0.2_amd64.deb ...\r\n", "Unpacking qt5-gtk-platformtheme:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Selecting previously unselected package qttranslations5-l10n.\r\n", "Preparing to unpack .../qttranslations5-l10n_5.15.3-1_all.deb ...\r\n", "Unpacking qttranslations5-l10n (5.15.3-1) ...\r\n", "Setting up libcxsparse3:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libevdev2:amd64 (1.12.1+dfsg-1) ...\r\n", "Setting up libgflags2.2 (2.2.2-2) ...\r\n", "Setting up libgoogle-glog0v5 (0.5.0+really0.4.0-2) ...\r\n", "Setting up libgudev-1.0-0:amd64 (1:237-2build1) ...\r\n", "Setting up libmd4c0:amd64 (0.4.8-1) ...\r\n", "Setting up libmetis5:amd64 (5.1.0.dfsg-7build2) ...\r\n", "Setting up libmtdev1:amd64 (1.1.6-1build4) ...\r\n", "Setting up libqt5core5a:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Setting up libqt5dbus5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Setting up libqt5network5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Setting up libraw20:amd64 (0.20.2-2ubuntu2.22.04.1) ...\r\n", "Setting up libsuitesparseconfig5:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libwacom-common (2.2.0-1) ...\r\n", "Setting up libxcb-icccm4:amd64 (0.4.1-1.1build2) ...\r\n", "Setting up libxcb-keysyms1:amd64 (0.4.0-1build3) ...\r\n", "Setting up libxcb-render-util0:amd64 (0.3.9-1build3) ...\r\n", "Setting up libxcb-util1:amd64 (0.4.0-1build2) ...\r\n", "Setting up libxcb-xinerama0:amd64 (1.14-3ubuntu3) ...\r\n", "Setting up libxcb-xinput0:amd64 (1.14-3ubuntu3) ...\r\n", "Setting up libxcb-xkb1:amd64 (1.14-3ubuntu3) ...\r\n", "Setting up libxkbcommon-x11-0:amd64 (1.4.0-1) ...\r\n", "Setting up qttranslations5-l10n (5.15.3-1) ...\r\n", "Setting up libamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libcamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libccolamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libcolamd2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libfreeimage3:amd64 (3.18.0+ds2-6ubuntu5.1) ...\r\n", "Setting up libwacom9:amd64 (2.2.0-1) ...\r\n", "Setting up libwacom-bin (2.2.0-1) ...\r\n", "Setting up libxcb-image0:amd64 (0.4.0-2) ...\r\n", "Setting up libcholmod3:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libinput-bin (1.20.0-1ubuntu0.3) ...\r\n", "Setting up libspqr2:amd64 (1:5.10.1+dfsg-4build1) ...\r\n", "Setting up libceres2 (2.0.0+dfsg1-5) ...\r\n", "Setting up libinput10:amd64 (1.20.0-1ubuntu0.3) ...\r\n", "Setting up libqt5gui5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Setting up libqt5widgets5:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Setting up qt5-gtk-platformtheme:amd64 (5.15.3+dfsg-2ubuntu0.2) ...\r\n", "Setting up colmap (3.7-2) ...\r\n", "Setting up libqt5svg5:amd64 (5.15.3-1) ...\r\n", "Processing triggers for man-db (2.10.2-1) ...\r\n", "Processing triggers for libc-bin (2.35-0ubuntu3.4) ...\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtcm.so.1 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libumf.so.0 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtcm_debug.so.1 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libhwloc.so.15 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libur_loader.so.0 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libur_adapter_level_zero.so.0 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libur_adapter_opencl.so.0 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtbbbind_2_5.so.3 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtbbbind_2_0.so.3 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtbb.so.12 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtbbmalloc_proxy.so.2 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtbbmalloc.so.2 is not a symbolic link\r\n", "\r\n", "/sbin/ldconfig.real: /usr/local/lib/libtbbbind.so.3 is not a symbolic link\r\n", "\r\n", "COLMAP 3.7 -- Structure-from-Motion and Multi-View Stereo\r\n", " (Commit Unknown on Unknown without CUDA)\r\n", "\r\n", "Usage:\r\n", " colmap [command] [options]\r\n", "\r\n", "Documentation:\r\n", " https://colmap.github.io/\r\n", "\r\n", "Example usage:\r\n", " colmap help [ -h, --help ]\r\n", " colmap gui\r\n", " colmap gui -h [ --help ]\r\n", " colmap automatic_reconstructor -h [ --help ]\r\n", " colmap automatic_reconstructor --image_path IMAGES --workspace_path WORKSPACE\r\n", " colmap feature_extractor --image_path IMAGES --database_path DATABASE\r\n", " colmap exhaustive_matcher --database_path DATABASE\r\n", " colmap mapper --image_path IMAGES --database_path DATABASE --output_path MODEL\r\n", " ...\r\n", "\r\n", "Available commands:\r\n", " help\r\n", " gui\r\n", " automatic_reconstructor\r\n", " bundle_adjuster\r\n", " color_extractor\r\n", " database_cleaner\r\n", " database_creator\r\n", " database_merger\r\n", " delaunay_mesher\r\n", " exhaustive_matcher\r\n", " feature_extractor\r\n", " feature_importer\r\n", " hierarchical_mapper\r\n", " image_deleter\r\n", " image_filterer\r\n", " image_rectifier\r\n", " image_registrator\r\n", " image_undistorter\r\n", " image_undistorter_standalone\r\n", " mapper\r\n", " matches_importer\r\n", " model_aligner\r\n", " model_analyzer\r\n", " model_comparer\r\n", " model_converter\r\n", " model_cropper\r\n", " model_merger\r\n", " model_orientation_aligner\r\n", " model_splitter\r\n", " model_transformer\r\n", " patch_match_stereo\r\n", " point_filtering\r\n", " point_triangulator\r\n", " poisson_mesher\r\n", " project_generator\r\n", " rig_bundle_adjuster\r\n", " sequential_matcher\r\n", " spatial_matcher\r\n", " stereo_fusion\r\n", " transitive_matcher\r\n", " vocab_tree_builder\r\n", " vocab_tree_matcher\r\n", " vocab_tree_retriever\r\n", "\r\n", "Processing /kaggle/input/imc2024-packages-lightglue-rerun-kornia/kornia-0.7.2-py2.py3-none-any.whl\r\n", "Processing /kaggle/input/imc2024-packages-lightglue-rerun-kornia/kornia_moons-0.2.9-py3-none-any.whl\r\n", "Processing /kaggle/input/imc2024-packages-lightglue-rerun-kornia/kornia_rs-0.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\r\n", "Processing /kaggle/input/imc2024-packages-lightglue-rerun-kornia/lightglue-0.0-py3-none-any.whl\r\n", "Processing /kaggle/input/imc2024-packages-lightglue-rerun-kornia/pycolmap-0.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\r\n", "Processing /kaggle/input/imc2024-packages-lightglue-rerun-kornia/rerun_sdk-0.15.0a2-cp38-abi3-manylinux_2_31_x86_64.whl\r\n", "Installing collected packages: rerun-sdk, pycolmap, lightglue, kornia-rs, kornia-moons, kornia\r\n", " Attempting uninstall: kornia-rs\r\n", " Found existing installation: kornia_rs 0.1.8\r\n", " Uninstalling kornia_rs-0.1.8:\r\n", " Successfully uninstalled kornia_rs-0.1.8\r\n", " Attempting uninstall: kornia\r\n", " Found existing installation: kornia 0.8.0\r\n", " Uninstalling kornia-0.8.0:\r\n", " Successfully uninstalled kornia-0.8.0\r\n", "Successfully installed kornia-0.7.2 kornia-moons-0.2.9 kornia-rs-0.1.2 lightglue-0.0 pycolmap-0.6.1 rerun-sdk-0.15.0a2\r\n" ] } ], "source": [ "# Install colmap (CPU)\n", "!cd /kaggle/input/pkg-colmap/colmap_offline && dpkg -i ./*.deb\n", "\n", "# Test\n", "!colmap -h\n", "\n", "# IMPORTANT\n", "# Install dependencies and copy model weights to run the notebook without internet access when submitting to the competition.\n", "\n", "!pip install --no-index /kaggle/input/imc2024-packages-lightglue-rerun-kornia/* --no-deps\n", "!mkdir -p /root/.cache/torch/hub/checkpoints\n", "\n", "!cp /kaggle/input/aliked/pytorch/aliked-n16/1/aliked-n16.pth /root/.cache/torch/hub/checkpoints/\n", "!cp /kaggle/input/lightglue/pytorch/aliked/1/aliked_lightglue.pth /root/.cache/torch/hub/checkpoints/\n", "!cp /kaggle/input/lightglue/pytorch/aliked/1/aliked_lightglue.pth /root/.cache/torch/hub/checkpoints/aliked_lightglue_v0-1_arxiv-pth" ] }, { "cell_type": "code", "execution_count": 2, "id": "6cdc2bcd", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:01.674943Z", "iopub.status.busy": "2026-01-03T14:34:01.674627Z", "iopub.status.idle": "2026-01-03T14:34:35.263514Z", "shell.execute_reply": "2026-01-03T14:34:35.262594Z" }, "papermill": { "duration": 33.611542, "end_time": "2026-01-03T14:34:35.265111", "exception": false, "start_time": "2026-01-03T14:34:01.653569", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.10/dist-packages/kornia/feature/lightglue.py:44: FutureWarning: `torch.cuda.amp.custom_fwd(args...)` is deprecated. Please use `torch.amp.custom_fwd(args..., device_type='cuda')` instead.\n", " @torch.cuda.amp.custom_fwd(cast_inputs=torch.float32)\n", "/usr/local/lib/python3.10/dist-packages/lightglue/lightglue.py:24: FutureWarning: `torch.cuda.amp.custom_fwd(args...)` is deprecated. Please use `torch.amp.custom_fwd(args..., device_type='cuda')` instead.\n", " @torch.cuda.amp.custom_fwd(cast_inputs=torch.float32)\n" ] } ], "source": [ "import sys\n", "import os, glob\n", "from tqdm import tqdm\n", "from fastprogress import progress_bar\n", "from time import time, sleep\n", "import gc\n", "import numpy as np\n", "import h5py\n", "import dataclasses\n", "import pandas as pd\n", "from IPython.display import clear_output\n", "from collections import defaultdict\n", "from copy import deepcopy\n", "from PIL import Image\n", "import networkx as nx\n", "\n", "import cv2\n", "import torch\n", "import torch.nn.functional as F\n", "import kornia as K\n", "import kornia.feature as KF\n", "\n", "import torch\n", "from lightglue import match_pair\n", "from lightglue import ALIKED, LightGlue\n", "from lightglue.utils import load_image, rbd\n", "from transformers import AutoImageProcessor, AutoModel\n", "\n", "# IMPORTANT Utilities: importing data into colmap and competition metric\n", "import pycolmap\n", "sys.path.append('/kaggle/input/imc25-utils')\n", "from database import *\n", "from h5_to_db import *\n", "import metric\n", "\n", "# Do not forget to select an accelerator on the sidebar to the right.\n", "#device = K.utils.get_cuda_device_if_available(0)\n", "#print(f'{device=}')\n", "\n", "import concurrent.futures" ] }, { "cell_type": "markdown", "id": "9343ca2d", "metadata": { "papermill": { "duration": 0.017383, "end_time": "2026-01-03T14:34:35.300654", "exception": false, "start_time": "2026-01-03T14:34:35.283271", "status": "completed" }, "tags": [] }, "source": [ " # Param_AlikedLightGlue Class\n", " # Configuration for Aliked + LightGlue feature matching\n" ] }, { "cell_type": "markdown", "id": "bb0da0c6", "metadata": { "papermill": { "duration": 0.017002, "end_time": "2026-01-03T14:34:35.334772", "exception": false, "start_time": "2026-01-03T14:34:35.317770", "status": "completed" }, "tags": [] }, "source": [ "このソースコードは、「Param_AlikedLightGlue」というクラスを定義しており、画像処理における重要なパラメータを設定することを目的としています。具体的には、このクラスは初期化メソッドにおいて、特徴点マッチングの際に必要となる最低限のマッチング数(min_matchesが15)、画像から検出されるキーポイントの最大数(max_num_keypointsが4096)、そして処理される入力画像のサイズ(image_sizeが1024)といった値を規定しています。これらの初期値は、画像間の対応付けや特徴点の抽出を行うアルゴリズムの動作を制御し、性能と精度のバランスを決定するために使用されます。" ] }, { "cell_type": "code", "execution_count": 3, "id": "9bc7e677", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.370549Z", "iopub.status.busy": "2026-01-03T14:34:35.369950Z", "iopub.status.idle": "2026-01-03T14:34:35.374117Z", "shell.execute_reply": "2026-01-03T14:34:35.373269Z" }, "papermill": { "duration": 0.023527, "end_time": "2026-01-03T14:34:35.375514", "exception": false, "start_time": "2026-01-03T14:34:35.351987", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "class Param_AlikedLightGlue:\n", " def __init__(\n", " self,\n", " min_matches = 15,\n", " max_num_keypoints = 4096,\n", " image_size = 1024,\n", " ):\n", " self.min_matches = min_matches\n", " self.max_num_keypoints = max_num_keypoints\n", " self.image_size = image_size" ] }, { "cell_type": "markdown", "id": "952a8cfb", "metadata": { "papermill": { "duration": 0.017082, "end_time": "2026-01-03T14:34:35.410050", "exception": false, "start_time": "2026-01-03T14:34:35.392968", "status": "completed" }, "tags": [] }, "source": [ "このソースコードの抜粋は、「画像処理とSfM構成パラメータ」と題され、Structure from Motion (SfM) のプロセスを制御するための様々な設定を定義しています。特に、画像を比較する際の類似度の閾値 (sim_th = 1.0) や、特徴点抽出の数 (N_KEYPOINTS = 2048) のように、画像ペアリングとマッチングに不可欠なパラメータが含まれています。また、マッチングアルゴリズム(例:AlikedLightGlue)の具体的な制約、例えば最小マッチ数や最大キーポイント数も指定されており、これらが全体の処理効率と精度に大きく影響します。最後に、SfM計算を並列処理する数 (num_pallalel_sfm = 4) を設定することで、計算資源の利用方法を最適化しています。" ] }, { "cell_type": "code", "execution_count": 4, "id": "0b3fb93e", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.445794Z", "iopub.status.busy": "2026-01-03T14:34:35.445543Z", "iopub.status.idle": "2026-01-03T14:34:35.449913Z", "shell.execute_reply": "2026-01-03T14:34:35.449090Z" }, "papermill": { "duration": 0.023682, "end_time": "2026-01-03T14:34:35.451319", "exception": false, "start_time": "2026-01-03T14:34:35.427637", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "class CONFIG:\n", " # Image pairs\n", " sim_th = 1.0 ####\n", " min_pairs = 10\n", " MATCH_THRESH = 10\n", " GLOBAL_TOPK = 200\n", " RATIO_THR = 1.2\n", " exhaustive_if_less = 20\n", " N_KEYPOINTS = 2048 \n", "\n", " # Image Matching\n", " params_alikedlg = [\n", " Param_AlikedLightGlue( min_matches = 50, max_num_keypoints = 8192, image_size = 1536 ),\n", " ]\n", "\n", " roma_max_num_keypoints = 512\n", " roma_image_size = 140\n", " roma_batch_size = 20\n", "\n", " # SfM\n", " num_pallalel_sfm = 4" ] }, { "cell_type": "markdown", "id": "6efbbc1d", "metadata": { "papermill": { "duration": 0.01761, "end_time": "2026-01-03T14:34:35.486349", "exception": false, "start_time": "2026-01-03T14:34:35.468739", "status": "completed" }, "tags": [] }, "source": [ " # CV Evaluation Functions\n", " # Analyze Initial Image Pairs\n", " # Evaluate Matching Quality\n", " # Evaluate Final Matches\n", " # Analyze Connectivity Before SfM\n", " # Evaluate Clustering Quality\n", " # Print CV Metrics\n", " # GPU Switching Utilities\n", " # Import Keypoints and Matches into COLMAP\n", " # Add Keypoints for Specific Scene\n", " # Add Matches for Specific Scene\n", " # Import Data into COLMAP for Specific Scene\n" ] }, { "cell_type": "markdown", "id": "f2b54de1", "metadata": { "papermill": { "duration": 0.017125, "end_time": "2026-01-03T14:34:35.521275", "exception": false, "start_time": "2026-01-03T14:34:35.504150", "status": "completed" }, "tags": [] }, "source": [ "このソースコードは、「初期ペア選択の評価」を行うための関数を定義しており、与えられたインデックスペアのリストと画像総数に基づいて、複数の重要なメトリクスを計算します。具体的には、選択されたペアの総数、画像あたりのペアの平均数、そして選択されたペアが可能な全ペアに対してどれだけをカバーしているかをパーセンテージで推定するカバレッジの見積もりが含まれています。この関数の目的は、初期のペア選択プロセスが、データのセット全体をどの程度効率的かつ包括的に網羅しているかを定量的に分析することにあります。" ] }, { "cell_type": "code", "execution_count": 5, "id": "56bae4c9", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.556541Z", "iopub.status.busy": "2026-01-03T14:34:35.556304Z", "iopub.status.idle": "2026-01-03T14:34:35.560246Z", "shell.execute_reply": "2026-01-03T14:34:35.559623Z" }, "papermill": { "duration": 0.023075, "end_time": "2026-01-03T14:34:35.561371", "exception": false, "start_time": "2026-01-03T14:34:35.538296", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# =========================================================\n", "# CV Evaluation Functions\n", "# =========================================================\n", "\n", "def analyze_initial_pairs(index_pairs, total_images):\n", " \"\"\"初期ペア選択の評価\"\"\"\n", " return {\n", " 'total_pairs': len(index_pairs),\n", " 'pairs_per_image': len(index_pairs) / total_images if total_images > 0 else 0,\n", " 'coverage_estimate': min(100, len(index_pairs) / (total_images * (total_images-1)/2) * 100)\n", " }" ] }, { "cell_type": "markdown", "id": "b111e112", "metadata": { "papermill": { "duration": 0.017171, "end_time": "2026-01-03T14:34:35.596352", "exception": false, "start_time": "2026-01-03T14:34:35.579181", "status": "completed" }, "tags": [] }, "source": [ "このPythonの関数は、画像特徴量マッチングの品質を数値的に評価するために設計されています。具体的には、入力されたファイル群に含まれる特徴点間の「マッチ」の数を集計し、その結果から評価指標を算出します。主要な目的は、平均や中央値、有効なペアの総数といった統計量を通じて、マッチングの精度と信頼性を定量化することです。さらに、マッチ数が15未満や50を超えるペアの数もカウントすることで、マッチング結果のばらつきや外れ値を詳細に把握できるようになっています。" ] }, { "cell_type": "code", "execution_count": 6, "id": "ce7d04ad", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.632039Z", "iopub.status.busy": "2026-01-03T14:34:35.631766Z", "iopub.status.idle": "2026-01-03T14:34:35.636872Z", "shell.execute_reply": "2026-01-03T14:34:35.636209Z" }, "papermill": { "duration": 0.024366, "end_time": "2026-01-03T14:34:35.638184", "exception": false, "start_time": "2026-01-03T14:34:35.613818", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def evaluate_matching_quality(files_keypoints, images, index_pairs):\n", " \"\"\"マッチング品質の評価\"\"\"\n", " match_counts = []\n", " \n", " for file in files_keypoints:\n", " with h5py.File(file, 'r') as f:\n", " for key1 in f.keys():\n", " for key2 in f[key1].keys():\n", " matches = f[key1][key2][:]\n", " match_counts.append(len(matches))\n", " \n", " if not match_counts:\n", " return {'avg_matches': 0, 'valid_pairs': 0}\n", " \n", " return {\n", " 'avg_matches': np.mean(match_counts),\n", " 'median_matches': np.median(match_counts),\n", " 'valid_pairs': len(match_counts),\n", " 'pairs_under_15': sum(1 for x in match_counts if x < 15),\n", " 'pairs_over_50': sum(1 for x in match_counts if x > 50)\n", " }" ] }, { "cell_type": "markdown", "id": "5f18806a", "metadata": { "papermill": { "duration": 0.016845, "end_time": "2026-01-03T14:34:35.673191", "exception": false, "start_time": "2026-01-03T14:34:35.656346", "status": "completed" }, "tags": [] }, "source": [] }, { "cell_type": "markdown", "id": "deef50e6", "metadata": { "papermill": { "duration": 0.018331, "end_time": "2026-01-03T14:34:35.709336", "exception": false, "start_time": "2026-01-03T14:34:35.691005", "status": "completed" }, "tags": [] }, "source": [ "このコードスニペットは、「最終マッチング評価関数」の一部であり、画像セット間の特徴点マッチングの結果を定量的に分析することを目的としています。具体的には、保存されたマッチングデータ(matches.h5ファイル内)を読み込み、それぞれの画像ペア間で見つかったマッチングの総数をカウントします。そして、平均マッチ数、マッチングが見つかったペアの総数、マッチ数が15未満のペアの数、さらには最終カバレッジ(可能な全ペアに対するマッチングが確認されたペアの割合)といった重要な評価指標を算出して返します。この評価関数は、大規模な画像処理パイプラインにおけるマッチング工程の性能と網羅性を理解するために不可欠なツールです。" ] }, { "cell_type": "code", "execution_count": 7, "id": "7a1b8c5f", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.785926Z", "iopub.status.busy": "2026-01-03T14:34:35.785589Z", "iopub.status.idle": "2026-01-03T14:34:35.790508Z", "shell.execute_reply": "2026-01-03T14:34:35.789921Z" }, "papermill": { "duration": 0.064231, "end_time": "2026-01-03T14:34:35.791649", "exception": false, "start_time": "2026-01-03T14:34:35.727418", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def evaluate_final_matches(feature_dir, images):\n", " \"\"\"最終マッチング結果の評価\"\"\"\n", " matches_file = f'{feature_dir}/matches.h5'\n", " match_counts = []\n", " \n", " with h5py.File(matches_file, 'r') as f:\n", " for key1 in f.keys():\n", " for key2 in f[key1].keys():\n", " match_counts.append(len(f[key1][key2]))\n", " \n", " total_possible_pairs = len(images) * (len(images)-1) // 2\n", " \n", " return {\n", " 'final_avg_matches': np.mean(match_counts) if match_counts else 0,\n", " 'final_total_pairs': len(match_counts),\n", " 'final_pairs_under_15': sum(1 for x in match_counts if x < 15),\n", " 'final_coverage': len(match_counts) / total_possible_pairs * 100 if total_possible_pairs > 0 else 0\n", " }" ] }, { "cell_type": "markdown", "id": "1b0547bb", "metadata": { "papermill": { "duration": 0.017418, "end_time": "2026-01-03T14:34:35.826695", "exception": false, "start_time": "2026-01-03T14:34:35.809277", "status": "completed" }, "tags": [] }, "source": [ "このコードは、Structure from Motion (SfM) を実行する前に、画像間の連結性を評価するための分析関数を定義しています。具体的には、画像間のマッチングデータからネットワークグラフを構築し、そのグラフがいくつの連結成分に分かれているかを調べます。分析結果として、全体の成分数、最大の連結成分のサイズ、孤立している画像の数、そして最大の成分サイズを全画像数で割った連結性スコアといった、重要な指標を提供します。これにより、SfM処理を始める前に、データセット全体がどの程度関連し合っているかを効率的に把握できます。" ] }, { "cell_type": "code", "execution_count": 8, "id": "f26bd7fb", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.863274Z", "iopub.status.busy": "2026-01-03T14:34:35.863040Z", "iopub.status.idle": "2026-01-03T14:34:35.867466Z", "shell.execute_reply": "2026-01-03T14:34:35.866805Z" }, "papermill": { "duration": 0.02428, "end_time": "2026-01-03T14:34:35.868572", "exception": false, "start_time": "2026-01-03T14:34:35.844292", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def analyze_connectivity_before_sfm(matches_file, fnames):\n", " \"\"\"SfM前の連結性分析\"\"\"\n", " G, _, _ = get_network_from_matches_h5(matches_file, fnames, th_matches=150)\n", " components = list(nx.connected_components(G))\n", " component_sizes = [len(comp) for comp in components]\n", " \n", " return {\n", " 'num_components': len(components),\n", " 'largest_component': max(component_sizes) if component_sizes else 0,\n", " 'isolated_images': sum(1 for size in component_sizes if size == 1),\n", " 'connectivity_score': max(component_sizes) / len(fnames) if fnames else 0\n", " }" ] }, { "cell_type": "markdown", "id": "ac3d557f", "metadata": { "papermill": { "duration": 0.018092, "end_time": "2026-01-03T14:34:35.904227", "exception": false, "start_time": "2026-01-03T14:34:35.886135", "status": "completed" }, "tags": [] }, "source": [ "このソースコードは、特に画像データに対して行われたクラスタリングの品質を評価するための関数を定義しています。この関数は、分割されたシーン(クラスター)の数、それぞれのシーンの平均的なサイズ、そして最も大きなシーンのサイズといった重要な指標を計算します。さらに、クラスタリングが全体の画像数に対してどれだけを網羅しているかを示す「カバレッジ」や、どのクラスターにも含まれなかった未分類の画像の数も算出することで、クラスタリングがどれほど効果的であったかを総合的に判断することを目的としています。" ] }, { "cell_type": "code", "execution_count": 9, "id": "38e6d941", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:35.938533Z", "iopub.status.busy": "2026-01-03T14:34:35.938323Z", "iopub.status.idle": "2026-01-03T14:34:35.942052Z", "shell.execute_reply": "2026-01-03T14:34:35.941450Z" }, "papermill": { "duration": 0.02206, "end_time": "2026-01-03T14:34:35.943140", "exception": false, "start_time": "2026-01-03T14:34:35.921080", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def evaluate_clustering_quality(scenes, total_images):\n", " \"\"\"クラスタリング品質の評価\"\"\"\n", " scene_sizes = [len(scene) for scene in scenes]\n", " \n", " return {\n", " 'num_scenes': len(scenes),\n", " 'avg_scene_size': np.mean(scene_sizes) if scene_sizes else 0,\n", " 'largest_scene': max(scene_sizes) if scene_sizes else 0,\n", " 'coverage': sum(scene_sizes) / total_images * 100 if total_images > 0 else 0,\n", " 'unclustered_images': total_images - sum(scene_sizes) if scene_sizes else total_images\n", " }" ] }, { "cell_type": "markdown", "id": "74603173", "metadata": { "papermill": { "duration": 0.016932, "end_time": "2026-01-03T14:34:35.977732", "exception": false, "start_time": "2026-01-03T14:34:35.960800", "status": "completed" }, "tags": [] }, "source": [ "このソースコードは、クロスバリデーション(CV)の評価指標を表示するためのPython関数print_cv_metricsと、機械学習モデルの計算に使用するデバイスの設定を定義しています。print_cv_metrics関数は、指定されたステージ名と共に、渡された評価指標のディクショナリを整形して出力し、特に浮動小数点数の値は小数点以下2桁に丸めて表示するよう設計されています。また、このコードには、GPUを利用するためのPyTorchデバイスとしてcuda:0とcuda:1が定義されており、計算資源を明示的に指定できることが示されています。" ] }, { "cell_type": "code", "execution_count": 10, "id": "b1a9be54", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.013878Z", "iopub.status.busy": "2026-01-03T14:34:36.013625Z", "iopub.status.idle": "2026-01-03T14:34:36.017480Z", "shell.execute_reply": "2026-01-03T14:34:36.016851Z" }, "papermill": { "duration": 0.023654, "end_time": "2026-01-03T14:34:36.018680", "exception": false, "start_time": "2026-01-03T14:34:35.995026", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def print_cv_metrics(metrics, stage_name):\n", " \"\"\"CVメトリクスの表示\"\"\"\n", " print(f\"=== {stage_name} CV Metrics ===\")\n", " for key, value in metrics.items():\n", " if isinstance(value, float):\n", " print(f\" {key}: {value:.2f}\")\n", " else:\n", " print(f\" {key}: {value}\")\n", "\n", "device0=torch.device('cuda:0')\n", "device1=torch.device('cuda:1')" ] }, { "cell_type": "markdown", "id": "01f48118", "metadata": { "papermill": { "duration": 0.01718, "end_time": "2026-01-03T14:34:36.053102", "exception": false, "start_time": "2026-01-03T14:34:36.035922", "status": "completed" }, "tags": [] }, "source": [ "この「GPUデバイス切替関数」のコードは、利用可能な2つのGPUデバイス(device0とdevice1)を切り替えるシンプルなロジックを実装しています。関数switch_gpuは、現在のデバイスが指定されていない場合(None)、または現在device1を使用している場合、デフォルトのdevice0とそのインデックス0を返します。対照的に、現在のデバイスが既にdevice0である場合には、次に使用すべきdevice1とそのインデックス1へと切り替えます。この目的は、特定の処理に応じてGPUリソースを循環的かつ規則的に切り替えることです。" ] }, { "cell_type": "code", "execution_count": 11, "id": "3e601e78", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.088761Z", "iopub.status.busy": "2026-01-03T14:34:36.088549Z", "iopub.status.idle": "2026-01-03T14:34:36.091742Z", "shell.execute_reply": "2026-01-03T14:34:36.091132Z" }, "papermill": { "duration": 0.022766, "end_time": "2026-01-03T14:34:36.092999", "exception": false, "start_time": "2026-01-03T14:34:36.070233", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def switch_gpu(device, device_index):\n", " if device is None:\n", " return device0, 0\n", " elif device == device0:\n", " return device1, 1\n", " else:\n", " return device0, 0" ] }, { "cell_type": "markdown", "id": "4338ef80", "metadata": { "papermill": { "duration": 0.016742, "end_time": "2026-01-03T14:34:36.127993", "exception": false, "start_time": "2026-01-03T14:34:36.111251", "status": "completed" }, "tags": [] }, "source": [ "このプログラムの断片は、画像群から三次元構造を復元するソフトウェアである COLMAP にデータをインポートするための一連の処理を定義しています。具体的には、まず COLMAPのデータベースファイル を作成し、次に指定された画像ディレクトリと特徴点データを使用して、画像ファイル名とIDの対応付けを行いながら キーポイント(特徴点)をデータベースに追加 しています。最後に、これらの画像間の 対応点(マッチ) の情報をデータベースに書き込み、一連のインポート作業を完了させています。この関数の目的は、外部で処理された特徴点とマッチングの結果をCOLMAPの処理パイプラインに取り込むための準備を行うことです。" ] }, { "cell_type": "code", "execution_count": 12, "id": "7c7196ee", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.164153Z", "iopub.status.busy": "2026-01-03T14:34:36.163896Z", "iopub.status.idle": "2026-01-03T14:34:36.167493Z", "shell.execute_reply": "2026-01-03T14:34:36.166903Z" }, "papermill": { "duration": 0.023456, "end_time": "2026-01-03T14:34:36.168684", "exception": false, "start_time": "2026-01-03T14:34:36.145228", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def import_into_colmap(img_dir, feature_dir ='.featureout', database_path = 'colmap.db'):\n", " db = COLMAPDatabase.connect(database_path)\n", " db.create_tables()\n", " single_camera = False\n", " fname_to_id = add_keypoints(db, feature_dir, img_dir, '', 'simple-radial', single_camera)\n", " add_matches(\n", " db,\n", " feature_dir,\n", " fname_to_id,\n", " )\n", " db.commit()\n", " return" ] }, { "cell_type": "markdown", "id": "626d36fb", "metadata": { "papermill": { "duration": 0.016751, "end_time": "2026-01-03T14:34:36.202641", "exception": false, "start_time": "2026-01-03T14:34:36.185890", "status": "completed" }, "tags": [] }, "source": [ "このPython関数add_keypoints_with_sceneは、画像認識における特徴点とシーンの情報をデータベースに追加するための処理を担っています。具体的には、特定のシーンに含まれる画像ファイル群をHDF5ファイルから読み込み、各画像に対してカメラモデルに基づいてカメラIDを生成または取得します。そして、画像ファイル名とカメラIDを用いてデータベースに画像を登録し、最後に読み込んだ特徴点データをその画像IDに関連付けて保存することがこの関数の主要な目的です。この一連のプロセスにより、後続のコンピュータビジョン処理に必要な構造化されたデータセットが構築されます。" ] }, { "cell_type": "code", "execution_count": 13, "id": "a782f42e", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.237041Z", "iopub.status.busy": "2026-01-03T14:34:36.236789Z", "iopub.status.idle": "2026-01-03T14:34:36.241460Z", "shell.execute_reply": "2026-01-03T14:34:36.240881Z" }, "papermill": { "duration": 0.023164, "end_time": "2026-01-03T14:34:36.242635", "exception": false, "start_time": "2026-01-03T14:34:36.219471", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def add_keypoints_with_scene(db, scene, h5_path, image_path, img_ext, camera_model, single_camera = True):\n", " keypoint_f = h5py.File(os.path.join(h5_path, 'keypoints.h5'), 'r')\n", "\n", " camera_id = None\n", " fname_to_id = {}\n", " for filename in tqdm(list(keypoint_f.keys())):\n", " if not filename in scene:\n", " continue\n", " \n", " keypoints = keypoint_f[filename][()]\n", "\n", " fname_with_ext = filename# + img_ext\n", " path = os.path.join(image_path, fname_with_ext)\n", " if not os.path.isfile(path):\n", " raise IOError(f'Invalid image path {path}')\n", "\n", " if camera_id is None or not single_camera:\n", " camera_id = create_camera(db, path, camera_model)\n", " image_id = db.add_image(fname_with_ext, camera_id)\n", " fname_to_id[filename] = image_id\n", "\n", " db.add_keypoints(image_id, keypoints)\n", "\n", " return fname_to_id" ] }, { "cell_type": "code", "execution_count": 14, "id": "03e36b4f", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.277366Z", "iopub.status.busy": "2026-01-03T14:34:36.277168Z", "iopub.status.idle": "2026-01-03T14:34:36.282271Z", "shell.execute_reply": "2026-01-03T14:34:36.281601Z" }, "papermill": { "duration": 0.02374, "end_time": "2026-01-03T14:34:36.283423", "exception": false, "start_time": "2026-01-03T14:34:36.259683", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def add_matches_with_scene(db, scene, h5_path, fname_to_id):\n", " match_file = h5py.File(os.path.join(h5_path, 'matches.h5'), 'r')\n", " \n", " added = set()\n", " n_keys = len(match_file.keys())\n", " n_total = (n_keys * (n_keys - 1)) // 2\n", "\n", " with tqdm(total=n_total) as pbar:\n", " for key_1 in match_file.keys():\n", " if not key_1 in scene:\n", " continue\n", "\n", " group = match_file[key_1]\n", " for key_2 in group.keys():\n", " if not key_2 in scene:\n", " continue\n", " \n", " id_1 = fname_to_id[key_1]\n", " id_2 = fname_to_id[key_2]\n", "\n", " pair_id = image_ids_to_pair_id(id_1, id_2)\n", " if pair_id in added:\n", " warnings.warn(f'Pair {pair_id} ({id_1}, {id_2}) already added!')\n", " continue\n", " \n", " matches = group[key_2][()]\n", " db.add_matches(id_1, id_2, matches)\n", " added.add(pair_id)\n", " pbar.update(1)" ] }, { "cell_type": "code", "execution_count": 15, "id": "5e6e49e0", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.318619Z", "iopub.status.busy": "2026-01-03T14:34:36.318405Z", "iopub.status.idle": "2026-01-03T14:34:36.321756Z", "shell.execute_reply": "2026-01-03T14:34:36.321188Z" }, "papermill": { "duration": 0.022571, "end_time": "2026-01-03T14:34:36.322995", "exception": false, "start_time": "2026-01-03T14:34:36.300424", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def import_into_colmap_with_scene(img_dir, scene, feature_dir ='.featureout', database_path = 'colmap.db'):\n", " db = COLMAPDatabase.connect(database_path)\n", " db.create_tables()\n", " single_camera = False\n", " fname_to_id = add_keypoints(db, feature_dir, img_dir, '', 'simple-radial', single_camera)\n", " add_matches_with_scene(\n", " db,\n", " scene,\n", " feature_dir,\n", " fname_to_id,\n", " )\n", " db.commit()\n", " return" ] }, { "cell_type": "markdown", "id": "c73e9e3b", "metadata": { "papermill": { "duration": 0.017066, "end_time": "2026-01-03T14:34:36.356997", "exception": false, "start_time": "2026-01-03T14:34:36.339931", "status": "completed" }, "tags": [] }, "source": [ "\n", " # Global DINO Embedding Extraction\n", " # Build Top-K Neighbor Lists\n", " # ALIKED Local Feature Extraction\n", " # Extract Local Features with ALIKED\n", " # Good-Match Counting (Torch)\n", " # Build Final Verified Pairs\n", " # Get Image Pairs Function\n" ] }, { "cell_type": "markdown", "id": "37ca7be1", "metadata": { "papermill": { "duration": 0.01687, "end_time": "2026-01-03T14:34:36.391023", "exception": false, "start_time": "2026-01-03T14:34:36.374153", "status": "completed" }, "tags": [] }, "source": [] }, { "cell_type": "code", "execution_count": 16, "id": "1fb92b1e", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.425750Z", "iopub.status.busy": "2026-01-03T14:34:36.425546Z", "iopub.status.idle": "2026-01-03T14:34:36.430976Z", "shell.execute_reply": "2026-01-03T14:34:36.430201Z" }, "papermill": { "duration": 0.024194, "end_time": "2026-01-03T14:34:36.432323", "exception": false, "start_time": "2026-01-03T14:34:36.408129", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import os, torch, urllib.request, tempfile\n", "from PIL import Image\n", "from tqdm import tqdm\n", "from torchvision import transforms\n", "\n", "# ---------- Global embeddings ---------- #\n", "def _extract_dino_embeddings(fnames, device = torch.device('cuda')):\n", " processor = AutoImageProcessor.from_pretrained('/kaggle/input/dinov2/pytorch/base/1')\n", " model = AutoModel.from_pretrained('/kaggle/input/dinov2/pytorch/base/1')\n", " model = model.eval()\n", " model = model.to(device)\n", " global_descs_dinov2 = []\n", " for i, img_fname_full in tqdm(enumerate(fnames),total= len(fnames)):\n", " key = os.path.splitext(os.path.basename(img_fname_full))[0]\n", " timg = load_torch_image(img_fname_full)\n", " with torch.inference_mode():\n", " inputs = processor(images=timg, return_tensors=\"pt\", do_rescale=False).to(device)\n", " outputs = model(**inputs)\n", " dino_mac = F.normalize(outputs.last_hidden_state[:,1:].max(dim=1)[0], dim=1, p=2)\n", " global_descs_dinov2.append(dino_mac.detach().cpu())\n", " global_descs_dinov2 = torch.cat(global_descs_dinov2, dim=0)\n", " return global_descs_dinov2" ] }, { "cell_type": "code", "execution_count": 17, "id": "0a1b523a", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.467271Z", "iopub.status.busy": "2026-01-03T14:34:36.467041Z", "iopub.status.idle": "2026-01-03T14:34:36.471430Z", "shell.execute_reply": "2026-01-03T14:34:36.470588Z" }, "papermill": { "duration": 0.023321, "end_time": "2026-01-03T14:34:36.472665", "exception": false, "start_time": "2026-01-03T14:34:36.449344", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def _build_topk_lists(global_feats, device):\n", " \"\"\"\n", " global_feats : (N, D) L2‑normed\n", " returns : list of length‑≤(N‑1) neighbor indices for each image\n", " \"\"\"\n", " g = global_feats.to(device) # (N,D)\n", " sim = g @ g.T # cosine similarity\n", " sim.fill_diagonal_(-1)\n", "\n", " N = sim.size(0)\n", " k = min(CONFIG.GLOBAL_TOPK, N - 1) # ★ Modified point here\n", " k = max(k, 1) # Ensure k=1 even if N==2\n", "\n", " topk = torch.topk(sim, k, dim=1).indices.cpu()\n", " return [row.tolist() for row in topk]" ] }, { "cell_type": "code", "execution_count": 18, "id": "5204d6d3", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.508167Z", "iopub.status.busy": "2026-01-03T14:34:36.507954Z", "iopub.status.idle": "2026-01-03T14:34:36.511645Z", "shell.execute_reply": "2026-01-03T14:34:36.510886Z" }, "papermill": { "duration": 0.023092, "end_time": "2026-01-03T14:34:36.513055", "exception": false, "start_time": "2026-01-03T14:34:36.489963", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# ---------- ALIKED local features ---------- #\n", "def _get_aliked_model(device, num_features, resize_to=1024, detection_threshold=0.01):\n", " dtype = torch.float32 # ALIKED has issues with float16\n", " extractor = ALIKED(\n", " model_name=\"aliked-n16\",\n", " max_num_keypoints=num_features,\n", " detection_threshold=detection_threshold, \n", " resize=resize_to\n", " ).eval().to(device, dtype)\n", " extractor.preprocess_conf[\"resize\"] = resize_to\n", " return extractor" ] }, { "cell_type": "code", "execution_count": 19, "id": "27a1214e", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.548033Z", "iopub.status.busy": "2026-01-03T14:34:36.547778Z", "iopub.status.idle": "2026-01-03T14:34:36.552030Z", "shell.execute_reply": "2026-01-03T14:34:36.551373Z" }, "papermill": { "duration": 0.023032, "end_time": "2026-01-03T14:34:36.553252", "exception": false, "start_time": "2026-01-03T14:34:36.530220", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "@torch.no_grad()\n", "def _extract_local_features(img_paths, model, device):\n", " dtype = torch.float32\n", " descs = []\n", " for p in tqdm(img_paths, desc=\"ALIKED\"):\n", " image0 = load_torch_image(p, device=device).to(dtype)\n", " h, w = image0.shape[2], image0.shape[3]\n", " feats0 = model.extract(image0) # auto-resize the image, disable with resize=None\n", " d = feats0['descriptors'].reshape(-1, 128).detach()\n", " descs.append(torch.nn.functional.normalize(d, dim=1).half().cpu())\n", " return descs" ] }, { "cell_type": "code", "execution_count": 20, "id": "340ee560", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.588949Z", "iopub.status.busy": "2026-01-03T14:34:36.588718Z", "iopub.status.idle": "2026-01-03T14:34:36.592554Z", "shell.execute_reply": "2026-01-03T14:34:36.591969Z" }, "papermill": { "duration": 0.022834, "end_time": "2026-01-03T14:34:36.593637", "exception": false, "start_time": "2026-01-03T14:34:36.570803", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# ---------- Good‑match counting (Torch) ---------- #\n", "@torch.no_grad()\n", "def _mutual_nn_score(desc1, desc2, device):\n", " if desc1.size(0) == 0 or desc2.size(0) == 0:\n", " return 0\n", " d12 = torch.cdist(desc1.to(device), desc2.to(device), p=2)\n", " min_val, _ = torch.min(d12, 1)\n", " n_matches = np.sum( min_val.cpu().numpy() < (CONFIG.RATIO_THR ** 2) )\n", " return n_matches" ] }, { "cell_type": "code", "execution_count": 21, "id": "18e5372b", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.629079Z", "iopub.status.busy": "2026-01-03T14:34:36.628822Z", "iopub.status.idle": "2026-01-03T14:34:36.632906Z", "shell.execute_reply": "2026-01-03T14:34:36.632221Z" }, "papermill": { "duration": 0.023222, "end_time": "2026-01-03T14:34:36.634040", "exception": false, "start_time": "2026-01-03T14:34:36.610818", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def _build_final_pairs(topk_lists, descs, device):\n", " pairs = []\n", " for i, nbrs in enumerate(tqdm(topk_lists, desc=\"Local verify\")):\n", " for j in nbrs:\n", " if i < j:\n", " score = _mutual_nn_score(descs[i], descs[j], device)\n", " if score >= CONFIG.MATCH_THRESH:\n", " pairs.append((i, j))\n", " pairs = sorted(list(set(pairs)))\n", " return pairs" ] }, { "cell_type": "markdown", "id": "dc3fb044", "metadata": { "papermill": { "duration": 0.019101, "end_time": "2026-01-03T14:34:36.671312", "exception": false, "start_time": "2026-01-03T14:34:36.652211", "status": "completed" }, "tags": [] }, "source": [ "_extract_dino_embeddingsが実行されている" ] }, { "cell_type": "code", "execution_count": 22, "id": "194e9121", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.706734Z", "iopub.status.busy": "2026-01-03T14:34:36.706509Z", "iopub.status.idle": "2026-01-03T14:34:36.711429Z", "shell.execute_reply": "2026-01-03T14:34:36.710644Z" }, "papermill": { "duration": 0.02389, "end_time": "2026-01-03T14:34:36.712809", "exception": false, "start_time": "2026-01-03T14:34:36.688919", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_image_pairs(fnames, device=torch.device(\"cuda\")):\n", " \"\"\"\n", " fnames: list[str] - List of image file paths\n", " device: torch.device - GPU / CPU to use for computation\n", " returns: list[tuple[int,int]] - Image index pairs to match\n", " \"\"\"\n", " assert len(fnames) > 1, \"fnames must contain at least two images\"\n", "\n", " # 1) DINO global features\n", " global_feats = _extract_dino_embeddings(fnames, device)\n", " topk_lists = _build_topk_lists(global_feats, device)\n", " cnt = 0\n", " for topk_list in topk_lists:\n", " cnt += len(topk_list)\n", " print(cnt)\n", "\n", " # 2) ALIKED local descriptors\n", " aliked = _get_aliked_model(device, CONFIG.N_KEYPOINTS)\n", " descs = _extract_local_features(fnames, aliked, device)\n", "\n", " # 3) local verification\n", " pairs = _build_final_pairs(topk_lists, descs, device)\n", "\n", " del aliked\n", " torch.cuda.empty_cache()\n", " gc.collect()\n", " return pairs" ] }, { "cell_type": "markdown", "id": "49382a56", "metadata": { "papermill": { "duration": 0.018419, "end_time": "2026-01-03T14:34:36.748792", "exception": false, "start_time": "2026-01-03T14:34:36.730373", "status": "completed" }, "tags": [] }, "source": [ " # Torch Image Loader\n", " # EfficientNet / DINO Global Descriptor Extraction\n", " # Exhaustive Image Pair Generation\n", " # Shortlist Image Pairs with Global + Local Features\n", " # Coordinate Conversion for Rotated Images\n", " # ALIKED + LightGlue Matching with Rotation\n", " # Unique Indices Utility\n", " # Load Keypoints from H5\n", " # Merge Multiple Keypoints H5 Files\n", " # Merge Matches with Optional Fundamental Matrix Filtering\n", " # Retrieve Adjacent Edges with Weights\n", " # Filter Keypoints by Graph Connectivity\n", " # Merge Keypoints and Matches into Final H5\n", " # Execute Full Feature Extraction Pipeline\n" ] }, { "cell_type": "code", "execution_count": 23, "id": "5fa229d7", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.784416Z", "iopub.status.busy": "2026-01-03T14:34:36.784202Z", "iopub.status.idle": "2026-01-03T14:34:36.787655Z", "shell.execute_reply": "2026-01-03T14:34:36.786888Z" }, "papermill": { "duration": 0.022658, "end_time": "2026-01-03T14:34:36.788779", "exception": false, "start_time": "2026-01-03T14:34:36.766121", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def load_torch_image(fname, device=torch.device('cuda')):\n", " img = K.io.load_image(fname, K.io.ImageLoadType.RGB32, device=device)[None, ...]\n", " return img" ] }, { "cell_type": "markdown", "id": "90082f0a", "metadata": { "papermill": { "duration": 0.016687, "end_time": "2026-01-03T14:34:36.823061", "exception": false, "start_time": "2026-01-03T14:34:36.806374", "status": "completed" }, "tags": [] }, "source": [ "このPythonコードは、DINOv2モデルを使用して画像データから大域的記述子(global descriptors)を抽出するプロセスを示しています。まず、EfficientNetの記述子を利用してマッチングの候補リスト(shortlists)を取得することが前提とされています。具体的な関数get_global_descの中では、DINOv2の事前学習済みモデルと画像プロセッサが読み込まれ、提供された画像ファイル群を反復処理します。各画像に対して、前処理後にモデルの推論モードで処理を実行し、その出力から最大値プーリング(max pooling)とL2正規化を施すことで、最終的な大域的特徴ベクトルが生成され、これが後の画像マッチングなどに使用されます。" ] }, { "cell_type": "markdown", "id": "806ff678", "metadata": { "papermill": { "duration": 0.01767, "end_time": "2026-01-03T14:34:36.858447", "exception": false, "start_time": "2026-01-03T14:34:36.840777", "status": "completed" }, "tags": [] }, "source": [ "get_global_desc関数は定義されているが、どこで実行されているのか、実はこの関数は使われておらず、\n", "_extract_dino_embeddingsが実行されているらしい" ] }, { "cell_type": "markdown", "id": "0295254a", "metadata": { "_kg_hide-output": false, "execution": { "iopub.status.busy": "2025-10-31T11:31:45.250788Z", "iopub.status.idle": "2025-10-31T11:31:45.25133Z", "shell.execute_reply": "2025-10-31T11:31:45.25112Z" }, "papermill": { "duration": 0.017366, "end_time": "2026-01-03T14:34:36.893179", "exception": false, "start_time": "2026-01-03T14:34:36.875813", "status": "completed" }, "tags": [] }, "source": [ " # Must Use efficientnet global descriptor to get matching shortlists.\n", " def get_global_desc(fnames, device = torch.device('cuda')):\n", " processor = AutoImageProcessor.from_pretrained('/kaggle/input/dinov2/pytorch/base/1')\n", " model = AutoModel.from_pretrained('/kaggle/input/dinov2/pytorch/base/1')\n", " model = model.eval()\n", " model = model.to(device)\n", " global_descs_dinov2 = []\n", " for i, img_fname_full in tqdm(enumerate(fnames),total= len(fnames)):\n", " key = os.path.splitext(os.path.basename(img_fname_full))[0]\n", " timg = load_torch_image(img_fname_full)\n", " with torch.inference_mode():\n", " inputs = processor(images=timg, return_tensors=\"pt\", do_rescale=False).to(device)\n", " outputs = model(**inputs)\n", " dino_mac = F.normalize(outputs.last_hidden_state[:,1:].max(dim=1)[0], dim=1, p=2)\n", " global_descs_dinov2.append(dino_mac.detach().cpu())\n", " global_descs_dinov2 = torch.cat(global_descs_dinov2, dim=0)\n", " return global_descs_dinov2" ] }, { "cell_type": "code", "execution_count": 24, "id": "a2944061", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.928178Z", "iopub.status.busy": "2026-01-03T14:34:36.927912Z", "iopub.status.idle": "2026-01-03T14:34:36.931647Z", "shell.execute_reply": "2026-01-03T14:34:36.930848Z" }, "papermill": { "duration": 0.02249, "end_time": "2026-01-03T14:34:36.932790", "exception": false, "start_time": "2026-01-03T14:34:36.910300", "status": "completed" }, "tags": [] }, "outputs": [], "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" ] }, { "cell_type": "code", "execution_count": 25, "id": "d1d9cd05", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:36.967819Z", "iopub.status.busy": "2026-01-03T14:34:36.967581Z", "iopub.status.idle": "2026-01-03T14:34:36.971401Z", "shell.execute_reply": "2026-01-03T14:34:36.970611Z" }, "papermill": { "duration": 0.022802, "end_time": "2026-01-03T14:34:36.972634", "exception": false, "start_time": "2026-01-03T14:34:36.949832", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_image_pairs_shortlist(fnames,\n", " sim_th = 0.6, # should be strict\n", " min_pairs = 20,\n", " exhaustive_if_less = 20,\n", " device=torch.device('cuda')):\n", " num_imgs = len(fnames)\n", " if num_imgs <= exhaustive_if_less:\n", " return get_img_pairs_exhaustive(fnames)\n", " matching_list = get_image_pairs(fnames, device)\n", " return matching_list" ] }, { "cell_type": "code", "execution_count": 26, "id": "fcd8e9b6", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.007708Z", "iopub.status.busy": "2026-01-03T14:34:37.007478Z", "iopub.status.idle": "2026-01-03T14:34:37.012171Z", "shell.execute_reply": "2026-01-03T14:34:37.011382Z" }, "papermill": { "duration": 0.02369, "end_time": "2026-01-03T14:34:37.013486", "exception": false, "start_time": "2026-01-03T14:34:36.989796", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def convert_coord(r, w, h, rotk):\n", " if rotk == 0:\n", " return r\n", " elif rotk == 1:\n", " rx = w-1-r[:, 1]\n", " ry = r[:, 0]\n", " return torch.concat([rx[None], ry[None]], dim=0).T\n", " elif rotk == 2:\n", " rx = w-1-r[:, 0]\n", " ry = h-1-r[:, 1]\n", " return torch.concat([rx[None], ry[None]], dim=0).T\n", " elif rotk == 3:\n", " rx = r[:, 1]\n", " ry = h-1-r[:, 0]\n", " return torch.concat([rx[None], ry[None]], dim=0).T" ] }, { "cell_type": "markdown", "id": "8896fef5", "metadata": { "papermill": { "duration": 0.017528, "end_time": "2026-01-03T14:34:37.048750", "exception": false, "start_time": "2026-01-03T14:34:37.031222", "status": "completed" }, "tags": [] }, "source": [ "このソースコードは、**ALIKEDとLightGlue**という二つの主要なライブラリを用いて、**回転された画像間の特徴点マッチング**を実行するPython関数を定義しています。具体的には、`matching_aliked_lightglue_rot`関数が、指定された画像ファイルパスと回転角`rot`に基づき、まず**ALIKEDエクストラクター**を使用して各画像からキーポイントとディスクリプタを抽出します。画像が回転されている場合は、**特徴点を抽出した後で座標を補正**しています。次に、これらの特徴点を利用して**LightGlueマッチャー**が画像ペア間で対応する特徴点を特定し、**最小マッチ数**を満たす結果のみを保存ファイルに格納します。" ] }, { "cell_type": "code", "execution_count": 27, "id": "bf381aed", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.083659Z", "iopub.status.busy": "2026-01-03T14:34:37.083458Z", "iopub.status.idle": "2026-01-03T14:34:37.096685Z", "shell.execute_reply": "2026-01-03T14:34:37.096075Z" }, "papermill": { "duration": 0.032183, "end_time": "2026-01-03T14:34:37.097844", "exception": false, "start_time": "2026-01-03T14:34:37.065661", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def matching_aliked_lightglue_rot(\n", " img_fnames,\n", " index_pairs,\n", " rot,\n", " saved_file,\n", " feature_dir = '.featureout',\n", " num_features = 4096,\n", " resize_to = 1024,\n", " device=torch.device('cuda'),\n", " min_matches=15,\n", " verbose=True,\n", "):\n", " if not os.path.isdir(feature_dir):\n", " os.makedirs(feature_dir)\n", "\n", " #####################################################\n", " # Extract keypoints and descriptions\n", " #####################################################\n", " dtype = torch.float32 # ALIKED has issues with float16\n", " extractor = ALIKED(\n", " model_name=\"aliked-n16\",\n", " max_num_keypoints=num_features,\n", " detection_threshold=0.01,\n", " resize=resize_to\n", " ).eval().to(device, dtype)\n", " print(\"aliked> image size =\", extractor.preprocess_conf[\"resize\"], \"-->\", resize_to )\n", " extractor.preprocess_conf[\"resize\"] = resize_to\n", " if not os.path.isdir(feature_dir):\n", " os.makedirs(feature_dir)\n", " \n", " dict_kpts_cuda = {}\n", " dict_descs_cuda = {}\n", " for img_path in img_fnames:\n", " img_fname = img_path.split('/')[-1]\n", " key = img_fname\n", "\n", " with torch.inference_mode():\n", " rot_k = 0\n", " image0 = load_torch_image(img_path, device=device).to(dtype)\n", " h, w = image0.shape[2], image0.shape[3]\n", " feats0 = extractor.extract(image0)\n", " kpts = feats0['keypoints'].reshape(-1, 2).detach()\n", " descs = feats0['descriptors'].reshape(len(kpts), -1).detach()\n", " dict_kpts_cuda[f\"{key}_{rot_k}\"] = kpts\n", " dict_descs_cuda[f\"{key}_{rot_k}\"] = descs\n", " if verbose:\n", " print(f\"aliked_rot> rot_k={rot_k}, kpts.shape={kpts.shape}, descs.shape={descs.shape}\")\n", "\n", " if rot != 0:\n", " with torch.inference_mode():\n", " rot_k = rot\n", " image0 = load_torch_image(img_path, device=device).to(dtype)\n", " h, w = image0.shape[2], image0.shape[3]\n", " image1 = torch.rot90(image0, rot, [2, 3])\n", " feats0 = extractor.extract(image1)\n", " kpts = feats0['keypoints'].reshape(-1, 2).detach()\n", " descs = feats0['descriptors'].reshape(len(kpts), -1).detach()\n", " kpts = convert_coord(kpts, w, h, rot_k)\n", " dict_kpts_cuda[f\"{key}_{rot_k}\"] = kpts\n", " dict_descs_cuda[f\"{key}_{rot_k}\"] = descs\n", " if verbose:\n", " print(f\"aliked_rot> rot_k={rot_k}, kpts.shape={kpts.shape}, descs.shape={descs.shape}\")\n", " del extractor\n", " gc.collect()\n", "\n", " #####################################################\n", " # Matching keypoints\n", " #####################################################\n", " lg_matcher = KF.LightGlueMatcher(\n", " \"aliked\", {\n", " \"width_confidence\": -1,\n", " \"depth_confidence\": -1,\n", " \"mp\": True if 'cuda' in str(device) else False\n", " }\n", " ).eval().to(device).half()\n", " \n", " cnt_pairs = 0\n", " with h5py.File(saved_file, mode='w') as f_match:\n", " for pair_idx in tqdm(index_pairs):\n", " idx1, idx2 = pair_idx\n", " fname1, fname2 = img_fnames[idx1], img_fnames[idx2]\n", " if (\"outliers\" in fname1) or ( \"outliers\" in fname2 ):\n", " continue\n", " key1, key2 = fname1.split('/')[-1], fname2.split('/')[-1]\n", " \n", " kp1 = dict_kpts_cuda[f\"{key1}_0\"]\n", " desc1 = dict_descs_cuda[f\"{key1}_0\"]\n", " \n", " kp2 = dict_kpts_cuda[f\"{key2}_{rot}\"]\n", " desc2 = dict_descs_cuda[f\"{key2}_{rot}\"]\n", " with torch.inference_mode():\n", " dists, idxs = lg_matcher(desc1.half(),\n", " desc2.half(),\n", " KF.laf_from_center_scale_ori(kp1.half()[None]),\n", " KF.laf_from_center_scale_ori(kp2.half()[None]))\n", " if len(idxs) == 0:\n", " continue\n", " kp1 = kp1[idxs[:,0], :].cpu().numpy().reshape(-1, 2).astype(np.float32)\n", " kp2 = kp2[idxs[:,1], :].cpu().numpy().reshape(-1, 2).astype(np.float32)\n", " confs = (1.0-dists).cpu().numpy().reshape(-1, 1).astype(np.float32)\n", " n_matches = kp1.shape[0]\n", " group = f_match.require_group(key1)\n", " if n_matches >= min_matches:\n", " matches = np.concatenate([kp1, kp2, confs], axis=1)\n", " group.create_dataset(key2, data=matches)\n", " cnt_pairs+=1\n", " if verbose:\n", " print (f'aliked_rot> {key1}-{key2}@rot={rot}: {n_matches} matches @ {cnt_pairs}th pair') \n", " else:\n", " if verbose:\n", " print (f'aliked_rot> {key1}-{key2}: {n_matches} matches --> skipped')\n", " del lg_matcher\n", " torch.cuda.empty_cache()\n", " gc.collect()\n", " return" ] }, { "cell_type": "code", "execution_count": 28, "id": "d9b775b0", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.132766Z", "iopub.status.busy": "2026-01-03T14:34:37.132548Z", "iopub.status.idle": "2026-01-03T14:34:37.136859Z", "shell.execute_reply": "2026-01-03T14:34:37.135962Z" }, "papermill": { "duration": 0.023221, "end_time": "2026-01-03T14:34:37.138200", "exception": false, "start_time": "2026-01-03T14:34:37.114979", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_unique_idxs(A, dim=0):\n", " unique, idx, counts = torch.unique(A, dim=dim, sorted=True, return_inverse=True, return_counts=True)\n", " _, ind_sorted = torch.sort(idx, stable=True)\n", " cum_sum = counts.cumsum(0)\n", " cum_sum = torch.cat((torch.tensor([0],device=cum_sum.device), cum_sum[:-1]))\n", " first_indices = ind_sorted[cum_sum]\n", " return first_indices" ] }, { "cell_type": "markdown", "id": "c7411f6e", "metadata": { "papermill": { "duration": 0.018566, "end_time": "2026-01-03T14:34:37.174377", "exception": false, "start_time": "2026-01-03T14:34:37.155811", "status": "completed" }, "tags": [] }, "source": [ "このソースコードは、「H5キーポイント抽出関数」の一部で、HDF5ファイルから特定のキーポイントデータを安全に抽出することを目的としています。get_keypoint_from_h5という関数は、ファイルポインタfpと、データを特定するための2つのキー(key1とkey2)を受け取ります。この関数の中核は、指定されたキーを用いてファイルからデータをNumPy配列として読み込もうとすることですが、ファイル操作中にエラーが発生する可能性に備えてtry...exceptブロックで処理を囲んでいます。成功した場合は、ステータスコード0と抽出されたキーポイント配列を返しますが、何らかの理由でデータアクセスに失敗した場合は、エラーを示すステータスコード-1とNoneを返し、プログラムの安定性を保ちます。" ] }, { "cell_type": "code", "execution_count": 29, "id": "cd53c770", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.212186Z", "iopub.status.busy": "2026-01-03T14:34:37.211954Z", "iopub.status.idle": "2026-01-03T14:34:37.215717Z", "shell.execute_reply": "2026-01-03T14:34:37.215058Z" }, "papermill": { "duration": 0.02448, "end_time": "2026-01-03T14:34:37.217098", "exception": false, "start_time": "2026-01-03T14:34:37.192618", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_keypoint_from_h5(fp, key1, key2):\n", " rc = -1\n", " try:\n", " kpts = np.array(fp[key1][key2])\n", " rc = 0\n", " return (rc, kpts)\n", " except:\n", " return (rc, None)" ] }, { "cell_type": "markdown", "id": "bc7ee5b2", "metadata": { "papermill": { "duration": 0.017164, "end_time": "2026-01-03T14:34:37.251416", "exception": false, "start_time": "2026-01-03T14:34:37.234252", "status": "completed" }, "tags": [] }, "source": [ "このPython関数 get_keypoint_from_multi_h5 は、複数のファイルパス (fps) からキーポイントの抽出を行うことを目的としています。具体的には、与えられた各ファイルパスと二つの指定されたキー (key1, key2) を使用して、個々のファイルからキーポイントの集合を取得します。抽出されたキーポイントが存在する場合、それらは一時的なリストに追加され、最後に NumPy配列として結合 されます。このプロセスにより、多数のH5ファイルに分散しているキーポイントデータを、一つの便利なデータ構造に集約することが可能になります。" ] }, { "cell_type": "code", "execution_count": 30, "id": "220ebd31", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.286375Z", "iopub.status.busy": "2026-01-03T14:34:37.286129Z", "iopub.status.idle": "2026-01-03T14:34:37.289922Z", "shell.execute_reply": "2026-01-03T14:34:37.289296Z" }, "papermill": { "duration": 0.022422, "end_time": "2026-01-03T14:34:37.291014", "exception": false, "start_time": "2026-01-03T14:34:37.268592", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_keypoint_from_multi_h5(fps, key1, key2):\n", " list_mkpts = []\n", " for fp in fps:\n", " rc, mkpts = get_keypoint_from_h5(fp, key1, key2)\n", " if mkpts is not None:\n", " list_mkpts.append(mkpts)\n", " if len(list_mkpts) > 0:\n", " list_mkpts = np.concatenate(list_mkpts, axis=0)\n", " else:\n", " list_mkpts = None\n", " return list_mkpts" ] }, { "cell_type": "markdown", "id": "bdd67e65", "metadata": { "papermill": { "duration": 0.017288, "end_time": "2026-01-03T14:34:37.325425", "exception": false, "start_time": "2026-01-03T14:34:37.308137", "status": "completed" }, "tags": [] }, "source": [ "このPython関数 matches_merger は、複数の画像ファイル間で検出された特徴点マッチングの結果を統合し、保存することを目的としています。具体的には、与えられた画像ペア(index_pairs)ごとに、HDF5ファイルから対応する特徴点集合(mkpts)を抽出し、最小マッチ数(min_matches)を満たさないペアは除外されます。オプションとして、外れ値の対応点を排除するために基礎行列(Fundamental Matrix)を使用してフィルタリング処理が行われ、最終的に信頼性の高い対応点のみが別のHDF5ファイル(save_file)に保存され、統合されたペアの総数がカウントされます。この処理は、大規模な画像データセットにおける正確な画像間の幾何学的関係を確立するために不可欠です。" ] }, { "cell_type": "code", "execution_count": 31, "id": "98b56801", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.361081Z", "iopub.status.busy": "2026-01-03T14:34:37.360824Z", "iopub.status.idle": "2026-01-03T14:34:37.368690Z", "shell.execute_reply": "2026-01-03T14:34:37.368039Z" }, "papermill": { "duration": 0.027005, "end_time": "2026-01-03T14:34:37.369785", "exception": false, "start_time": "2026-01-03T14:34:37.342780", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def matches_merger(\n", " img_fnames,\n", " index_pairs,\n", " files_keypoints,\n", " save_file,\n", " feature_dir = 'featureout',\n", " filter_FundamentalMatrix = False,\n", " filter_iterations = 10,\n", " filter_threshold = 8,\n", " min_matches=15,\n", "):\n", " print( files_keypoints )\n", " # open h5 files\n", " fps = [ h5py.File(file, mode=\"r\") for file in files_keypoints ]\n", " \n", " with h5py.File(save_file, mode='w') as f_match:\n", " counter = 0\n", " for pair_idx in progress_bar(index_pairs):\n", " idx1, idx2 = pair_idx\n", " fname1, fname2 = img_fnames[idx1], img_fnames[idx2]\n", " key1, key2 = fname1.split('/')[-1], fname2.split('/')[-1]\n", "\n", " # extract keypoints\n", " mkpts = get_keypoint_from_multi_h5(fps, key1, key2)\n", " if mkpts is None:\n", " print(f\"skipped key1={key1}, key2={key2}\")\n", " continue\n", "\n", " ori_size = mkpts.shape[0]\n", " if mkpts.shape[0] < min_matches:\n", " continue\n", " \n", " if filter_FundamentalMatrix:\n", " store_inliers = { idx:0 for idx in range(mkpts.shape[0]) }\n", " idxs = np.array(range(mkpts.shape[0]))\n", " for iter in range(filter_iterations):\n", " try:\n", " Fm, inliers = cv2.findFundamentalMat(\n", " mkpts[:,:2], mkpts[:,2:4], cv2.USAC_MAGSAC, 0.15, 0.9999, 20000)\n", " if Fm is not None:\n", " inliers = inliers > 0\n", " inlier_idxs = idxs[inliers[:, 0]]\n", " for idx in inlier_idxs:\n", " store_inliers[idx] += 1\n", " except:\n", " print(f\"Failed to cv2.findFundamentalMat. mkpts.shape={mkpts.shape}\")\n", " inliers = np.array([ count for (idx, count) in store_inliers.items() ]) >= filter_threshold\n", " mkpts = mkpts[inliers]\n", " if mkpts.shape[0] < 15:\n", " print(f\"skipped key1={key1}, key2={key2}: mkpts.shape={mkpts.shape} after filtered.\")\n", " continue\n", " \n", " print (f'{key1}-{key2}: {ori_size} --> {mkpts.shape[0]} matches') \n", " # regist tmp file\n", " group = f_match.require_group(key1)\n", " group.create_dataset(key2, data=mkpts[:, :4])\n", " counter += 1\n", " print( f\"Ensembled pairs : {counter} pairs\" )\n", " for fp in fps:\n", " fp.close()" ] }, { "cell_type": "markdown", "id": "5d078ec6", "metadata": { "papermill": { "duration": 0.017069, "end_time": "2026-01-03T14:34:37.404113", "exception": false, "start_time": "2026-01-03T14:34:37.387044", "status": "completed" }, "tags": [] }, "source": [ "このPythonのコードスニペットは、グラフ理論における特定のノードに隣接するエッジとそれらの重みを取得するための関数を定義しています。具体的には、指定されたグラフ $G$ とノードを受け取り、そのノードに接続しているすべて隣接ノードと対応するエッジの重みをペアとしてリスト化します。最後に、このリストをエッジの重みが大きい順に並べ替えて返すことが、この関数の主な目的です。" ] }, { "cell_type": "code", "execution_count": 32, "id": "4e325130", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.438731Z", "iopub.status.busy": "2026-01-03T14:34:37.438526Z", "iopub.status.idle": "2026-01-03T14:34:37.442172Z", "shell.execute_reply": "2026-01-03T14:34:37.441454Z" }, "papermill": { "duration": 0.022648, "end_time": "2026-01-03T14:34:37.443447", "exception": false, "start_time": "2026-01-03T14:34:37.420799", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_adjacent_edges_with_weights(G, node):\n", " \"\"\"\n", " Function that returns edges adjacent to a specified node and their weights as a list\n", " \"\"\"\n", " adjacent_edges = [(neighbor, G[node][neighbor]['weight']) for neighbor in G.neighbors(node)]\n", " return sorted(adjacent_edges, key=lambda x: x[1], reverse=True)" ] }, { "cell_type": "markdown", "id": "d9d2269e", "metadata": { "papermill": { "duration": 0.016826, "end_time": "2026-01-03T14:34:37.477532", "exception": false, "start_time": "2026-01-03T14:34:37.460706", "status": "completed" }, "tags": [] }, "source": [ "このPython関数 filter_mkpts は、特徴点ペアのフィルタリングを目的としており、特定の基準に基づいて関連性の高いペアのみを保存します。まず、HDF5ファイルから特徴点の情報を読み込み、ペア間の接続と重み(特徴点の数)を持つグラフ(nx.Graph)を構築します。その後、各ペアについて、グラフ上で定義された隣接ノードの数を制限する閾値(th_num_pairs)に基づき、フィルタリングロジックを適用します。具体的には、あるペアのノードがお互いの最も強い接続を持つ隣接ノードのリストに含まれている場合、そのペアは重要なものと見なされ、結果として新しいHDF5ファイルにデータセットとして保存されます。" ] }, { "cell_type": "code", "execution_count": 33, "id": "947ccae2", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.513146Z", "iopub.status.busy": "2026-01-03T14:34:37.512907Z", "iopub.status.idle": "2026-01-03T14:34:37.518049Z", "shell.execute_reply": "2026-01-03T14:34:37.517262Z" }, "papermill": { "duration": 0.02409, "end_time": "2026-01-03T14:34:37.519390", "exception": false, "start_time": "2026-01-03T14:34:37.495300", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def filter_mkpts(\n", " file_mkpts, \n", " save_file,\n", " th_num_pairs,\n", "):\n", " sleep(10)\n", " G = nx.Graph()\n", " pairs = []\n", " with h5py.File(save_file, mode='w') as f_match, h5py.File(file_mkpts, \"r\") as fp:\n", " for key1 in fp.keys():\n", " for key2 in fp[key1].keys():\n", " mkpts = fp[key1][key2]\n", " G.add_edge(key1, key2, weight=mkpts.shape[0])\n", " pairs.append([key1, key2, mkpts])\n", "\n", " for (key1, key2, mkpts) in pairs:\n", " neibors1 = get_adjacent_edges_with_weights(G, key1)\n", " neibors2 = get_adjacent_edges_with_weights(G, key2)\n", " if (key2 in [ val[0] for val in neibors1[:th_num_pairs] ]) or (key1 in [ val[0] for val in neibors2[:th_num_pairs] ]):\n", " group = f_match.require_group(key1)\n", " group.create_dataset(key2, data=mkpts)" ] }, { "cell_type": "markdown", "id": "6a4d6ef9", "metadata": { "papermill": { "duration": 0.017636, "end_time": "2026-01-03T14:34:37.554197", "exception": false, "start_time": "2026-01-03T14:34:37.536561", "status": "completed" }, "tags": [] }, "source": [ "\n", "このソースコードは、複数の画像ファイルから検出されたキーポイントを統合処理し、それらの一致(マッチ)情報を整理する機能を提供します。まず、matches_merger関数を用いて画像ペア間の初期のマッチングを行い、その後filter_mkptsによって不十分なペアを除去することでデータを洗練します。処理の核心は、読み込んだ全てのマッチングデータから、冗長性を排除して一意な(ユニークな)キーポイントを特定し、新しいインデックスを割り当てて再構築することにあります。最終的に、処理された一意なキーポイントと、それに対応する洗練されたマッチングインデックスを、それぞれkeypoints.h5とmatches.h5というファイルに保存することで、データセットの標準化された表現を生成します。" ] }, { "cell_type": "code", "execution_count": 34, "id": "9e9dde7d", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.590364Z", "iopub.status.busy": "2026-01-03T14:34:37.590140Z", "iopub.status.idle": "2026-01-03T14:34:37.609845Z", "shell.execute_reply": "2026-01-03T14:34:37.609292Z" }, "papermill": { "duration": 0.03891, "end_time": "2026-01-03T14:34:37.611175", "exception": false, "start_time": "2026-01-03T14:34:37.572265", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def keypoints_merger(\n", " img_fnames,\n", " index_pairs,\n", " files_keypoints,\n", " feature_dir = 'featureout',\n", " filter_FundamentalMatrix = False,\n", " filter_iterations = 10,\n", " filter_threshold = 8,\n", "):\n", " print(f\"files_keypoints = {files_keypoints}\")\n", " save_file0 = f'{feature_dir}/merge_tmp0.h5'\n", " !rm -rf {save_file0}\n", " matches_merger(\n", " img_fnames,\n", " index_pairs,\n", " files_keypoints,\n", " save_file0,\n", " feature_dir = feature_dir,\n", " filter_FundamentalMatrix = filter_FundamentalMatrix,\n", " filter_iterations = filter_iterations,\n", " filter_threshold = filter_threshold,\n", " )\n", "\n", " th_num_pairs = 6\n", " save_file = f'{feature_dir}/merge_tmp.h5'\n", " !rm -rf {save_file}\n", " filter_mkpts(\n", " save_file0, \n", " save_file,\n", " th_num_pairs,\n", " )\n", " \n", " # Let's find unique loftr pixels and group them together.\n", " kpts = defaultdict(list)\n", " match_indexes = defaultdict(dict)\n", " total_kpts=defaultdict(int)\n", " with h5py.File(save_file, mode='r') as f_match:\n", " for k1 in f_match.keys():\n", " group = f_match[k1]\n", " for k2 in group.keys():\n", " matches = group[k2][...]\n", " total_kpts[k1]\n", " kpts[k1].append(matches[:, :2])\n", " kpts[k2].append(matches[:, 2:])\n", " current_match = torch.arange(len(matches)).reshape(-1, 1).repeat(1, 2)\n", " current_match[:, 0]+=total_kpts[k1]\n", " current_match[:, 1]+=total_kpts[k2]\n", " total_kpts[k1]+=len(matches)\n", " total_kpts[k2]+=len(matches)\n", " match_indexes[k1][k2]=current_match\n", "\n", " for k in kpts.keys():\n", " kpts[k] = np.round(np.concatenate(kpts[k], axis=0))\n", " unique_kpts = {}\n", " unique_match_idxs = {}\n", " out_match = defaultdict(dict)\n", " for k in kpts.keys():\n", " uniq_kps, uniq_reverse_idxs = torch.unique(torch.from_numpy(kpts[k]),dim=0, return_inverse=True)\n", " unique_match_idxs[k] = uniq_reverse_idxs\n", " unique_kpts[k] = uniq_kps.numpy()\n", " for k1, group in match_indexes.items():\n", " for k2, m in group.items():\n", " m2 = deepcopy(m)\n", " m2[:,0] = unique_match_idxs[k1][m2[:,0]]\n", " m2[:,1] = unique_match_idxs[k2][m2[:,1]]\n", " mkpts = np.concatenate([unique_kpts[k1][ m2[:,0]],\n", " unique_kpts[k2][ m2[:,1]],\n", " ],\n", " axis=1)\n", " unique_idxs_current = get_unique_idxs(torch.from_numpy(mkpts), dim=0)\n", " m2_semiclean = m2[unique_idxs_current]\n", " unique_idxs_current1 = get_unique_idxs(m2_semiclean[:, 0], dim=0)\n", " m2_semiclean = m2_semiclean[unique_idxs_current1]\n", " unique_idxs_current2 = get_unique_idxs(m2_semiclean[:, 1], dim=0)\n", " m2_semiclean2 = m2_semiclean[unique_idxs_current2]\n", " out_match[k1][k2] = m2_semiclean2.numpy()\n", " with h5py.File(f'{feature_dir}/keypoints.h5', mode='w') as f_kp:\n", " for k, kpts1 in unique_kpts.items():\n", " f_kp[k] = kpts1\n", " \n", " with h5py.File(f'{feature_dir}/matches.h5', mode='w') as f_match:\n", " for k1, gr in out_match.items():\n", " group = f_match.require_group(k1)\n", " for k2, match in gr.items():\n", " group[k2] = match\n", " return" ] }, { "cell_type": "markdown", "id": "4fbbeab5", "metadata": { "papermill": { "duration": 0.017151, "end_time": "2026-01-03T14:34:37.645352", "exception": false, "start_time": "2026-01-03T14:34:37.628201", "status": "completed" }, "tags": [] }, "source": [ "このコードスニペットは、画像データセットに対する特徴抽出とマッチングのプロセスを実行する関数を定義しています。まず、get_image_pairs_shortlistを用いて、処理対象となる画像のペアを効率的に絞り込む作業が行われます。次に、複数の設定パラメータと回転角度を用いて、Alike-LightGlueという手法に基づいたキーポイントの特徴マッチングが実行され、そのマッチング品質が評価されます。最終段階では、抽出されたキーポイントとマッチング結果が統合され、最終的なマッチング結果の品質評価が行われることで、一連の画像処理パイプラインが完了します。" ] }, { "cell_type": "code", "execution_count": 35, "id": "40d9a05b", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.680574Z", "iopub.status.busy": "2026-01-03T14:34:37.680335Z", "iopub.status.idle": "2026-01-03T14:34:37.687011Z", "shell.execute_reply": "2026-01-03T14:34:37.686200Z" }, "papermill": { "duration": 0.025815, "end_time": "2026-01-03T14:34:37.688355", "exception": false, "start_time": "2026-01-03T14:34:37.662540", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def exec_feature_extraction(params):\n", " images = params.images\n", " feature_dir = params.feature_dir\n", " device = params.device\n", " \n", " t = time()\n", " index_pairs = get_image_pairs_shortlist(\n", " images,\n", " sim_th = CONFIG.sim_th,\n", " min_pairs = CONFIG.min_pairs,\n", " exhaustive_if_less = CONFIG.exhaustive_if_less,\n", " device=device\n", " )\n", " params.laptime_image_pairs = time() - t\n", " params.image_pairs = index_pairs\n", " print (f'Shortlisting. Number of pairs to match: {len(index_pairs)}. Done in {params.laptime_image_pairs:.4f} sec')\n", " \n", " # ✅ CV評価: 初期ペア選択\n", " params.cv_metrics_before = analyze_initial_pairs(index_pairs, len(images))\n", " print_cv_metrics(params.cv_metrics_before, \"Initial Pair Selection\")\n", " \n", " gc.collect()\n", "\n", " t = time()\n", " files_keypoints = []\n", " for i_param, imc_param in enumerate(CONFIG.params_alikedlg): \n", " for rot in range(1):\n", " file_keypoints = f'{feature_dir}/aliked_lightglue_param{i_param}_rot{rot}_mkpts.h5'\n", " max_num_keypoints = imc_param.max_num_keypoints\n", " resize_to = imc_param.image_size\n", " min_matches = imc_param.min_matches\n", " matching_aliked_lightglue_rot(\n", " images,\n", " index_pairs,\n", " rot,\n", " file_keypoints,\n", " feature_dir, \n", " max_num_keypoints, \n", " resize_to=resize_to,\n", " device=device,\n", " min_matches=min_matches,\n", " verbose=True,\n", " )\n", " files_keypoints.append( file_keypoints )\n", " gc.collect()\n", " params.laptime_lightglue_4rots = time() - t\n", " print(f'Features matched in {params.laptime_lightglue_4rots:.4f} sec')\n", "\n", " # ✅ CV評価: マッチング品質\n", " params.cv_metrics_after_matching = evaluate_matching_quality(files_keypoints, images, index_pairs)\n", " print_cv_metrics(params.cv_metrics_after_matching, \"After Feature Matching\")\n", " \n", " # Merge mkpts and create keypoints/matches\n", " sleep(10)\n", " keypoints_merger(\n", " images,\n", " index_pairs,\n", " files_keypoints,\n", " feature_dir,\n", " filter_FundamentalMatrix = False,\n", " filter_iterations = 10,\n", " filter_threshold = 8,\n", " )\n", " \n", " # ✅ CV評価: 最終マッチング結果\n", " params.cv_metrics_final = evaluate_final_matches(feature_dir, images)\n", " print_cv_metrics(params.cv_metrics_final, \"Final Matches\")\n", " \n", " gc.collect()\n", " return params" ] }, { "cell_type": "markdown", "id": "112da9a6", "metadata": { "papermill": { "duration": 0.017502, "end_time": "2026-01-03T14:34:37.724232", "exception": false, "start_time": "2026-01-03T14:34:37.706730", "status": "completed" }, "tags": [] }, "source": [ "\n", " # Read Image Names from COLMAP Model\n", " # Build Overlap Graph Between Models\n", " # Run Subprocess Command\n", " # COLMAP Model Merger Wrapper\n", " # COLMAP Bundle Adjuster Wrapper\n" ] }, { "cell_type": "code", "execution_count": 36, "id": "f8e232c9", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.761593Z", "iopub.status.busy": "2026-01-03T14:34:37.761378Z", "iopub.status.idle": "2026-01-03T14:34:37.765121Z", "shell.execute_reply": "2026-01-03T14:34:37.764418Z" }, "papermill": { "duration": 0.024546, "end_time": "2026-01-03T14:34:37.766226", "exception": false, "start_time": "2026-01-03T14:34:37.741680", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# Merge maps of colmap\n", "import argparse, shutil, subprocess, tempfile, sys\n", "from pathlib import Path\n", "import networkx as nx\n", "import pycolmap\n", "\n", "def read_image_names(model_dir: Path):\n", " rec = pycolmap.Reconstruction(str(model_dir))\n", " return {img.name for img in rec.images.values()}" ] }, { "cell_type": "code", "execution_count": 37, "id": "e7cb1511", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.801220Z", "iopub.status.busy": "2026-01-03T14:34:37.801017Z", "iopub.status.idle": "2026-01-03T14:34:37.804796Z", "shell.execute_reply": "2026-01-03T14:34:37.804114Z" }, "papermill": { "duration": 0.022607, "end_time": "2026-01-03T14:34:37.806200", "exception": false, "start_time": "2026-01-03T14:34:37.783593", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def build_overlap_graph(image_sets, min_common):\n", " G = nx.Graph()\n", " G.add_nodes_from(range(len(image_sets)))\n", " for i in range(len(image_sets)):\n", " for j in range(i + 1, len(image_sets)):\n", " if len(image_sets[i] & image_sets[j]) >= min_common:\n", " G.add_edge(i, j)\n", " return G" ] }, { "cell_type": "code", "execution_count": 38, "id": "ee2e429d", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.841477Z", "iopub.status.busy": "2026-01-03T14:34:37.841245Z", "iopub.status.idle": "2026-01-03T14:34:37.845120Z", "shell.execute_reply": "2026-01-03T14:34:37.844435Z" }, "papermill": { "duration": 0.022541, "end_time": "2026-01-03T14:34:37.846275", "exception": false, "start_time": "2026-01-03T14:34:37.823734", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def run_cmd(cmd):\n", " proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)\n", " for line in proc.stdout:\n", " print(line, end=\"\")\n", " proc.wait()\n", " if proc.returncode != 0:\n", " raise subprocess.CalledProcessError(proc.returncode, cmd)" ] }, { "cell_type": "code", "execution_count": 39, "id": "d1378384", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.882256Z", "iopub.status.busy": "2026-01-03T14:34:37.882053Z", "iopub.status.idle": "2026-01-03T14:34:37.885627Z", "shell.execute_reply": "2026-01-03T14:34:37.885024Z" }, "papermill": { "duration": 0.022549, "end_time": "2026-01-03T14:34:37.886738", "exception": false, "start_time": "2026-01-03T14:34:37.864189", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# ---------- COLMAP wrappers ------------------------------------------------------\n", "def merge_two_models(colmap_bin, ref_model, src_model, out_dir):\n", " cmd = [\n", " colmap_bin, \"model_merger\",\n", " \"--input_path1\", str(ref_model),\n", " \"--input_path2\", str(src_model),\n", " \"--output_path\", str(out_dir),\n", " ]\n", " try:\n", " run_cmd(cmd)\n", " return True\n", " except subprocess.CalledProcessError:\n", " return False" ] }, { "cell_type": "code", "execution_count": 40, "id": "3a97104c", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.922391Z", "iopub.status.busy": "2026-01-03T14:34:37.922194Z", "iopub.status.idle": "2026-01-03T14:34:37.926000Z", "shell.execute_reply": "2026-01-03T14:34:37.925360Z" }, "papermill": { "duration": 0.022532, "end_time": "2026-01-03T14:34:37.927177", "exception": false, "start_time": "2026-01-03T14:34:37.904645", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def run_bundle_adjuster(colmap_bin, model_dir, num_threads=-1):\n", " cmd = [\n", " colmap_bin, \"bundle_adjuster\",\n", " \"--input_path\", str(model_dir),\n", " \"--output_path\", str(model_dir),\n", " \"--BundleAdjustment.refine_focal_length\", \"1\",\n", " \"--BundleAdjustment.refine_principal_point\", \"1\",\n", " \"--BundleAdjustment.refine_extra_params\", \"1\",\n", " ]\n", " if num_threads > 0:\n", " cmd += [\"--Mapper.num_threads\", str(num_threads)]\n", " run_cmd(cmd)" ] }, { "cell_type": "markdown", "id": "81867b43", "metadata": { "papermill": { "duration": 0.016797, "end_time": "2026-01-03T14:34:37.960970", "exception": false, "start_time": "2026-01-03T14:34:37.944173", "status": "completed" }, "tags": [] }, "source": [ " # cluster_and_merge\n", " # update_prediction" ] }, { "cell_type": "code", "execution_count": 41, "id": "329a847c", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:37.995946Z", "iopub.status.busy": "2026-01-03T14:34:37.995690Z", "iopub.status.idle": "2026-01-03T14:34:38.002583Z", "shell.execute_reply": "2026-01-03T14:34:38.002015Z" }, "papermill": { "duration": 0.025554, "end_time": "2026-01-03T14:34:38.003723", "exception": false, "start_time": "2026-01-03T14:34:37.978169", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# ---------- main logic -----------------------------------------------------------\n", "def cluster_and_merge(\n", " model_dirs,\n", " out_root,\n", " colmap_bin=\"colmap\",\n", " min_common=10,\n", " run_bundle_adjustment=True,\n", " keep_tmp=False,\n", "):\n", " out_root = Path(out_root)\n", " out_root.mkdir(parents=True, exist_ok=True)\n", "\n", " # 1) Image sets\n", " image_sets = [read_image_names(Path(m)) for m in model_dirs]\n", "\n", " # 2) Overlap graph → connected components\n", " clusters = list(nx.connected_components(build_overlap_graph(image_sets, min_common)))\n", " print(f\"num of clusters = {len(clusters)}\")\n", " \n", " merged_paths = []\n", " for cidx, comp in enumerate(clusters):\n", " comp = list(comp)\n", " if len(comp) == 1:\n", " src = Path(model_dirs[comp[0]])\n", " dst = out_root / f\"scene_{cidx:03d}\"\n", " shutil.copytree(src, dst, dirs_exist_ok=True)\n", " merged_paths.append(dst)\n", " if run_bundle_adjustment:\n", " run_bundle_adjuster(colmap_bin, dst)\n", " continue\n", "\n", " # 3) Sort by number of images (descending)\n", " comp_sorted = sorted(comp, key=lambda i: len(image_sets[i]), reverse=True)\n", " work_dir = Path(model_dirs[comp_sorted[0]])\n", "\n", " # 4) Sequential merge\n", " failed_sources = []\n", " for midx in comp_sorted[1:]:\n", " tmp_dir = Path(tempfile.mkdtemp(prefix=f\"merge_s{cidx}_\"))\n", " ok = merge_two_models(colmap_bin, work_dir, Path(model_dirs[midx]), tmp_dir)\n", " if ok:\n", " work_dir = tmp_dir\n", " else:\n", " failed_sources.append(midx)\n", "\n", " # 5) Output & BA\n", " final_dir = out_root / f\"scene_{cidx:03d}\"\n", " shutil.move(str(work_dir), final_dir)\n", " merged_paths.append(final_dir)\n", "\n", " if run_bundle_adjustment:\n", " run_bundle_adjuster(colmap_bin, final_dir)\n", "\n", " # 6) Copy failed merge sources as separate scenes\n", " for fidx in failed_sources:\n", " dst = out_root / f\"scene_{cidx}_{fidx}\"\n", " shutil.copytree(model_dirs[fidx], dst, dirs_exist_ok=True)\n", " merged_paths.append(dst)\n", " if run_bundle_adjustment:\n", " run_bundle_adjuster(colmap_bin, dst)\n", "\n", " return merged_paths" ] }, { "cell_type": "code", "execution_count": 42, "id": "b3cca41c", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.039014Z", "iopub.status.busy": "2026-01-03T14:34:38.038731Z", "iopub.status.idle": "2026-01-03T14:34:38.045281Z", "shell.execute_reply": "2026-01-03T14:34:38.044631Z" }, "papermill": { "duration": 0.025339, "end_time": "2026-01-03T14:34:38.046477", "exception": false, "start_time": "2026-01-03T14:34:38.021138", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def update_prediction(params, result_map_dirs, retry):\n", " feature_dir = params.feature_dir\n", " images_dir = params.images_dir\n", " filename_to_index = params.filename_to_index\n", " predictions = params.predictions\n", " dataset = params.dataset\n", "\n", " maps = {}\n", " for idx, result_map_dir in enumerate(result_map_dirs):\n", " maps[idx] = pycolmap.Reconstruction(result_map_dir)\n", " \n", " print (\"Counting map size...\")\n", " list_num_images = []\n", " if isinstance(maps, dict):\n", " for idx1, rec in maps.items():\n", " list_num_images.append( len(rec.images) )\n", " list_num_images = np.array(list_num_images)\n", " print(f\"list_num_images = {list_num_images}\")\n", " if params.list_model_size is None:\n", " params.list_model_size = [list_num_images]\n", " else:\n", " params.list_model_size.append( list_num_images )\n", " sort_idx = np.argsort( np.array(list_num_images) )\n", " \n", " registered = 0\n", " for map_index, cur_idx in enumerate(sort_idx):\n", " cur_map = maps[cur_idx]\n", " cur_map_size = list_num_images[cur_idx]\n", " if cur_map_size < 4:\n", " continue\n", " for index, image in cur_map.images.items():\n", " prediction_index = filename_to_index[image.name]\n", " if (cur_map_size > predictions[prediction_index].map_size) and (cur_map_size > 5):\n", " predictions[prediction_index].map_size = cur_map_size\n", " predictions[prediction_index].cluster_index = map_index\n", " predictions[prediction_index].retry_index = retry\n", " predictions[prediction_index].rotation = deepcopy(image.cam_from_world.rotation.matrix())\n", " predictions[prediction_index].translation = deepcopy(image.cam_from_world.translation)\n", " registered += 1\n", " del maps\n", " gc.collect()\n", " return params" ] }, { "cell_type": "markdown", "id": "023f27b0", "metadata": { "papermill": { "duration": 0.016916, "end_time": "2026-01-03T14:34:38.081037", "exception": false, "start_time": "2026-01-03T14:34:38.064121", "status": "completed" }, "tags": [] }, "source": [ " # Graph and Clustering Processing\n", " # SfM Execution\n", " # Data Structures\n", " # GPU / Parallel Processing\n", " # Result Output" ] }, { "cell_type": "code", "execution_count": 43, "id": "8aa47590", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.116956Z", "iopub.status.busy": "2026-01-03T14:34:38.116708Z", "iopub.status.idle": "2026-01-03T14:34:38.612057Z", "shell.execute_reply": "2026-01-03T14:34:38.611349Z" }, "papermill": { "duration": 0.515274, "end_time": "2026-01-03T14:34:38.613486", "exception": false, "start_time": "2026-01-03T14:34:38.098212", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import networkx as nx\n", "from networkx.algorithms.community import louvain_communities\n", "from sklearn.cluster import SpectralClustering\n", "from sklearn.cluster import AgglomerativeClustering\n", "from typing import List, Tuple, Iterable\n", "\n", "def get_network_from_matches_h5( file, images, num_max_keypoints = 8192, th_matches=150):\n", " image_to_index = {file:i for i,file in enumerate(images)}\n", " index_to_image = {i:file for i,file in enumerate(images)}\n", "\n", " edges = []\n", " with h5py.File(file, \"r\") as f_mat:\n", " for key1 in f_mat.keys():\n", " for key2 in f_mat[key1].keys():\n", " if f_mat[ key1 ][ key2 ].shape[0] >=th_matches:\n", " edges.append( (key1, key2, f_mat[key1][key2].shape[0] / num_max_keypoints) )\n", " G = nx.Graph()\n", " G.add_weighted_edges_from(edges, weight=\"weight\")\n", " return G, image_to_index, index_to_image" ] }, { "cell_type": "code", "execution_count": 44, "id": "3a52b788", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.651256Z", "iopub.status.busy": "2026-01-03T14:34:38.651012Z", "iopub.status.idle": "2026-01-03T14:34:38.655672Z", "shell.execute_reply": "2026-01-03T14:34:38.655030Z" }, "papermill": { "duration": 0.02516, "end_time": "2026-01-03T14:34:38.657042", "exception": false, "start_time": "2026-01-03T14:34:38.631882", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_components(\n", " G: nx.Graph | nx.DiGraph,\n", " *,\n", " directed_mode: str = \"auto\"\n", ") -> Tuple[int, List[List]]:\n", " if not G.is_directed():\n", " comp_iter: Iterable[set] = nx.connected_components(G)\n", " else:\n", " if directed_mode == \"strong\":\n", " comp_iter = nx.strongly_connected_components(G)\n", " elif directed_mode in {\"weak\", \"auto\"}:\n", " comp_iter = nx.weakly_connected_components(G)\n", " else:\n", " raise ValueError(\"directed_mode must be 'auto', 'weak', or 'strong'\")\n", "\n", " components = [sorted(list(c)) for c in comp_iter]\n", " n_components = len(components)\n", " return n_components, components" ] }, { "cell_type": "code", "execution_count": 45, "id": "54524c48", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.692487Z", "iopub.status.busy": "2026-01-03T14:34:38.692277Z", "iopub.status.idle": "2026-01-03T14:34:38.696288Z", "shell.execute_reply": "2026-01-03T14:34:38.695683Z" }, "papermill": { "duration": 0.023134, "end_time": "2026-01-03T14:34:38.697517", "exception": false, "start_time": "2026-01-03T14:34:38.674383", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def get_scenes_from_graph(G, random_state=42, th=0.2):\n", " communities = louvain_communities(\n", " G,\n", " weight=\"weight\",\n", " resolution=th,\n", " seed=random_state\n", " )\n", " \n", " scenes = []\n", " print(f\"#clusters = {len(communities)}\")\n", " for cid, members in enumerate(communities):\n", " scene = set(members)\n", " print(f\"Cluster {cid}: {len(members)} | {sorted(members)}\")\n", " if len(scene) >= 5:\n", " scenes.append( scene )\n", " print(\"=\"*50)\n", " return scenes" ] }, { "cell_type": "code", "execution_count": 46, "id": "779c7975", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.733494Z", "iopub.status.busy": "2026-01-03T14:34:38.733283Z", "iopub.status.idle": "2026-01-03T14:34:38.739777Z", "shell.execute_reply": "2026-01-03T14:34:38.739174Z" }, "papermill": { "duration": 0.0258, "end_time": "2026-01-03T14:34:38.741004", "exception": false, "start_time": "2026-01-03T14:34:38.715204", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def exec_reconstruction(params):\n", " feature_dir = params.feature_dir\n", " params.laptime_calc_fmat = []\n", " params.laptime_sfm = []\n", "\n", " # ✅ CV評価: SfM前の連結性分析\n", " fnames = [ p.filename for p in params.predictions ]\n", " matches_file = f'{feature_dir}/matches.h5'\n", " \n", " params.cv_metrics_before_sfm = analyze_connectivity_before_sfm(matches_file, fnames)\n", " print_cv_metrics(params.cv_metrics_before_sfm, \"Before SfM Connectivity\")\n", "\n", " # Clustering\n", " scenes = []\n", " num_retry = 4\n", " for _ in range(num_retry):\n", " G, images_to_index, index_to_image = get_network_from_matches_h5( \n", " matches_file, fnames, num_max_keypoints = 8192, th_matches=150,\n", " )\n", " n_components, components = get_components(G)\n", " for component in components:\n", " if len(component) > 4:\n", " scenes.append( set(component) )\n", "\n", " # ✅ CV評価: クラスタリング品質\n", " params.cv_metrics_clustering = evaluate_clustering_quality(scenes, len(fnames))\n", " print_cv_metrics(params.cv_metrics_clustering, \"Clustering Quality\")\n", "\n", " # SfM for each scene cluster\n", " for retry, scene in enumerate(scenes):\n", " params = reconstruction_single(params, scene, retry, 2)\n", "\n", " # merge models\n", " input_map_dirs = sorted( glob.glob( f\"{feature_dir}/colmap_rec_*/*/cameras.bin\"))\n", " input_map_dirs = [ \n", " os.path.dirname(x)\n", " for x in input_map_dirs\n", " if len(pycolmap.Reconstruction( os.path.dirname(x) ).images) > 8\n", " ]\n", " input_map_dirs = [ \n", " x \n", " for x in input_map_dirs\n", " if pycolmap.Reconstruction(x).compute_mean_reprojection_error() < 2.0\n", " ]\n", "\n", " if len(input_map_dirs) > 1:\n", " output_dir = f\"{feature_dir}/colmap_rec_merged/\"\n", " COLMAP_BIN = \"/usr/bin/colmap\"\n", " MERGE_MIN_COMMON = 6\n", " MERGE_RUN_BA = True\n", " result_map_dirs = cluster_and_merge(\n", " input_map_dirs,\n", " output_dir,\n", " colmap_bin=COLMAP_BIN,\n", " min_common=MERGE_MIN_COMMON,\n", " run_bundle_adjustment=MERGE_RUN_BA,\n", " keep_tmp=False,\n", " )\n", " \n", " # update motion info\n", " update_prediction(params, result_map_dirs, len(scenes) )\n", " clear_output(wait=False)\n", " return params" ] }, { "cell_type": "code", "execution_count": 47, "id": "5688ed14", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.778431Z", "iopub.status.busy": "2026-01-03T14:34:38.778211Z", "iopub.status.idle": "2026-01-03T14:34:38.786642Z", "shell.execute_reply": "2026-01-03T14:34:38.786033Z" }, "papermill": { "duration": 0.027846, "end_time": "2026-01-03T14:34:38.787759", "exception": false, "start_time": "2026-01-03T14:34:38.759913", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def reconstruction_single(params, scene, retry, min_model_size):\n", " feature_dir = params.feature_dir\n", " images_dir = params.images_dir\n", " filename_to_index = params.filename_to_index\n", " predictions = params.predictions\n", "\n", " # Execute process\n", " database_path = os.path.join(feature_dir, f'colmap_{retry}.db')\n", " if os.path.isfile(database_path):\n", " os.remove(database_path)\n", " gc.collect()\n", " sleep(1)\n", " import_into_colmap_with_scene(images_dir, scene, feature_dir=feature_dir, database_path=database_path)\n", " output_path = f'{feature_dir}/colmap_rec_{retry}'\n", " \n", " t = time()\n", " pycolmap.match_exhaustive(database_path)\n", " params.laptime_calc_fmat = time() - t\n", " print(f'Ran RANSAC in {params.laptime_calc_fmat:.4f} sec')\n", " \n", " mapper_options = pycolmap.IncrementalPipelineOptions()\n", " mapper_options.min_model_size = min_model_size\n", " mapper_options.max_num_models = 15\n", " mapper_options.init_num_trials = 1000\n", " \n", " os.makedirs(output_path, exist_ok=True)\n", " t = time()\n", " maps = pycolmap.incremental_mapping(\n", " database_path=database_path, \n", " image_path=images_dir,\n", " output_path=output_path,\n", " options=mapper_options)\n", " sleep(1)\n", " params.laptime_sfm = time() - t\n", " print(f'Reconstruction done in {params.laptime_sfm:.4f} sec')\n", " print(maps)\n", "\n", " clear_output(wait=False)\n", "\n", " print (\"Counting map size...\")\n", " list_num_images = []\n", " if isinstance(maps, dict):\n", " for idx1, rec in maps.items():\n", " list_num_images.append( len(rec.images) )\n", " list_num_images = np.array(list_num_images)\n", " print(f\"list_num_images = {list_num_images}\")\n", " if params.list_model_size is None:\n", " params.list_model_size = [list_num_images]\n", " else:\n", " params.list_model_size.append( list_num_images )\n", " sort_idx = np.argsort( np.array(list_num_images) )\n", "\n", " registered = 0\n", " for map_index, cur_idx in enumerate(sort_idx):\n", " cur_map = maps[cur_idx]\n", " cur_map_size = list_num_images[cur_idx]\n", " for index, image in cur_map.images.items():\n", " prediction_index = filename_to_index[image.name]\n", " if (cur_map_size > predictions[prediction_index].map_size) and (cur_map_size > 5):\n", " predictions[prediction_index].map_size = cur_map_size\n", " predictions[prediction_index].cluster_index = map_index\n", " predictions[prediction_index].retry_index = retry\n", " predictions[prediction_index].rotation = deepcopy(image.cam_from_world.rotation.matrix())\n", " predictions[prediction_index].translation = deepcopy(image.cam_from_world.translation)\n", " registered += 1\n", " gc.collect()\n", "\n", " return params" ] }, { "cell_type": "code", "execution_count": 48, "id": "08ee5a19", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.824681Z", "iopub.status.busy": "2026-01-03T14:34:38.824472Z", "iopub.status.idle": "2026-01-03T14:34:38.828506Z", "shell.execute_reply": "2026-01-03T14:34:38.827921Z" }, "papermill": { "duration": 0.023725, "end_time": "2026-01-03T14:34:38.829652", "exception": false, "start_time": "2026-01-03T14:34:38.805927", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# Collect vital info from the dataset\n", "@dataclasses.dataclass\n", "class Prediction:\n", " image_id: str | None\n", " dataset: str\n", " filename: str\n", " map_size: int = -1\n", " cluster_index: int | None = None\n", " retry_index: int = -1\n", " rotation: np.ndarray | None = None\n", " translation: np.ndarray | None = None" ] }, { "cell_type": "code", "execution_count": 49, "id": "d26a46ed", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.866018Z", "iopub.status.busy": "2026-01-03T14:34:38.865768Z", "iopub.status.idle": "2026-01-03T14:34:38.872413Z", "shell.execute_reply": "2026-01-03T14:34:38.871786Z" }, "papermill": { "duration": 0.026257, "end_time": "2026-01-03T14:34:38.873580", "exception": false, "start_time": "2026-01-03T14:34:38.847323", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "@dataclasses.dataclass\n", "class DatasetParams:\n", " dataset: str\n", " feature_dir: str | None = None\n", " images_dir: str | None = None\n", " filename_to_index: dict | None = None\n", " predictions: list | None = None\n", " images: list | None = None\n", " device: str | None = None\n", " laptime_image_pairs: float = -1.0\n", " laptime_lightglue_4rots: float = -1.0\n", " laptime_roma: float = -1.0\n", " laptime_calc_fmat: float = -1.0\n", " laptime_sfm: float = -1.0\n", " image_pairs: list | None = None\n", " list_model_size: list | None = None\n", " \n", " # ✅ CVメトリクスを追加\n", " cv_metrics_before: dict | None = None\n", " cv_metrics_after_matching: dict | None = None\n", " cv_metrics_final: dict | None = None\n", " cv_metrics_before_sfm: dict | None = None\n", " cv_metrics_clustering: dict | None = None\n", "\n", " def summary(self):\n", " print(\"[Summary]\")\n", " print(f\"- Dataset : {self.dataset}\")\n", " if self.images is not None:\n", " print(f\"- images : {len(self.images)}\")\n", " if self.image_pairs is not None:\n", " print(f\"- pairs : {len(self.image_pairs)}\")\n", " print(f\"- laptime_image_pairs : {self.laptime_image_pairs:.2f}\")\n", " print(f\"- laptime_lightglue_4rots : {self.laptime_lightglue_4rots:.2f}\")\n", " \n", " # ✅ CVメトリクスをサマリーに追加\n", " if self.cv_metrics_final:\n", " print(f\"- CV Avg Matches : {self.cv_metrics_final.get('final_avg_matches', 'N/A'):.1f}\")\n", " print(f\"- CV Total Pairs : {self.cv_metrics_final.get('final_total_pairs', 'N/A')}\")\n", " print(f\"- CV Coverage : {self.cv_metrics_final.get('final_coverage', 'N/A'):.1f}%\")\n", " if self.cv_metrics_before_sfm:\n", " print(f\"- CV Largest Component : {self.cv_metrics_before_sfm.get('largest_component', 'N/A')}\")\n", " print(f\"- CV Connectivity Score : {self.cv_metrics_before_sfm.get('connectivity_score', 'N/A'):.2f}\")" ] }, { "cell_type": "code", "execution_count": 50, "id": "e4e1ae5c", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:34:38.909353Z", "iopub.status.busy": "2026-01-03T14:34:38.909144Z", "iopub.status.idle": "2026-01-03T14:48:16.213862Z", "shell.execute_reply": "2026-01-03T14:48:16.212798Z" }, "papermill": { "duration": 817.324373, "end_time": "2026-01-03T14:48:16.215343", "exception": false, "start_time": "2026-01-03T14:34:38.890970", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# 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).\n", "is_train = False\n", "data_dir = '/kaggle/input/image-matching-challenge-2025'\n", "workdir = '/tmp/kaggle/working/result/'\n", "\n", "if is_train:\n", " sample_submission_csv = os.path.join(data_dir, 'train_labels.csv')\n", "else:\n", " sample_submission_csv = os.path.join(data_dir, 'sample_submission.csv')\n", "\n", "samples = {}\n", "dataset_logs = []\n", "competition_data = pd.read_csv(sample_submission_csv)\n", "if (not is_train) and (competition_data.shape[0] == 1945):\n", " competition_data = competition_data[ competition_data[\"dataset\"].isin([\"ETs\", \"stairs\"]) ]\n", " workdir = '/kaggle/working/result/'\n", "\n", "os.makedirs(workdir, exist_ok=True)\n", "\n", "for _, row in competition_data.iterrows():\n", " if row.dataset not in samples:\n", " samples[row.dataset] = []\n", " prediction = Prediction(\n", " image_id=None if is_train else row.image_id,\n", " dataset=row.dataset,\n", " filename=row.image\n", " )\n", " samples[row.dataset].append( prediction )\n", "\n", "for dataset in samples:\n", " print(f'Dataset \"{dataset}\" -> num_images={len(samples[dataset])}')\n", "gc.collect()\n", "\n", "max_images = None\n", "datasets_to_process = None\n", "\n", "if is_train:\n", " datasets_to_process = [\n", " 'ETs',\n", " 'stairs',\n", " 'imc2023_haiper',\n", " ]\n", "\n", "mapping_result_strs = []\n", "\n", "# Enqeue feature extraction processing\n", "futures_gpu0 = {}\n", "futures_gpu1 = {}\n", "device = None\n", "device_index = None\n", "with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executors_gpu0, \\\n", " concurrent.futures.ThreadPoolExecutor(max_workers=1) as executors_gpu1:\n", "\n", " executors_gpus = [executors_gpu0, executors_gpu1]\n", " futures_gpus = [futures_gpu0, futures_gpu1]\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", " \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", " if max_images is not None:\n", " images = images[:max_images]\n", " \n", " print(f'\\nProcessing dataset \"{dataset}\": {len(images)} images')\n", " \n", " filename_to_index = {p.filename: idx for idx, p in enumerate(predictions)}\n", " \n", " feature_dir = os.path.join(workdir, 'featureout', dataset)\n", " os.makedirs(feature_dir, exist_ok=True)\n", "\n", " # Switch device\n", " device, device_index = switch_gpu(device, device_index)\n", " \n", " # Dataset parameter\n", " dataset_params = DatasetParams(\n", " dataset = dataset,\n", " feature_dir = feature_dir,\n", " images_dir = images_dir,\n", " predictions = predictions,\n", " filename_to_index = filename_to_index,\n", " images = images,\n", " device = device,\n", " )\n", "\n", " # Enqueue feature extraction\n", " futures_gpus[device_index][dataset] = executors_gpus[device_index].submit(\n", " exec_feature_extraction, dataset_params,\n", " )\n", "\n", " # Enqeue reconstruction processing\n", " futures_cpu = {}\n", " with concurrent.futures.ThreadPoolExecutor(max_workers=CONFIG.num_pallalel_sfm) as executors:\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", " \n", " if dataset in futures_gpu0.keys():\n", " future = futures_gpu0[dataset]\n", " else:\n", " future = futures_gpu1[dataset]\n", " \n", " # Wait for feature extraction\n", " print(f\"waiting feature extraction at dataset = {dataset}\")\n", " dataset_params = future.result()\n", " \n", " # if feature extraction is failed:\n", " if dataset_params is None:\n", " continue\n", " \n", " # Enqueue reconstruction\n", " gc.collect()\n", " futures_cpu[dataset] = executors.submit(\n", " exec_reconstruction, dataset_params,\n", " )\n", "\n", " # Wait to reconstruction\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", " gc.collect()\n", " dataset_params = futures_cpu[dataset].result()\n", " samples[dataset] = dataset_params.predictions\n", " dataset_logs.append( dataset_params )\n", " gc.collect()" ] }, { "cell_type": "code", "execution_count": 51, "id": "2a1ce59a", "metadata": { "_kg_hide-output": false, "execution": { "iopub.execute_input": "2026-01-03T14:48:16.252355Z", "iopub.status.busy": "2026-01-03T14:48:16.252093Z", "iopub.status.idle": "2026-01-03T14:48:16.441049Z", "shell.execute_reply": "2026-01-03T14:48:16.439940Z" }, "papermill": { "duration": 0.208781, "end_time": "2026-01-03T14:48:16.442383", "exception": false, "start_time": "2026-01-03T14:48:16.233602", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "image_id,dataset,scene,image,rotation_matrix,translation_vector\r\n", "ETs_another_et_another_et001.png_public,ETs,retry0cluster0,another_et_another_et001.png,0.999835493;-0.007785605;-0.016382036;0.008110604;0.999769739;0.019866744;0.016223589;-0.019996344;0.999668416,-2.785685811;-1.937781687;2.706718343\r\n", "ETs_another_et_another_et002.png_public,ETs,retry0cluster0,another_et_another_et002.png,0.999474679;-0.006016134;-0.031846055;0.005822011;0.999963925;-0.006184882;0.031882115;0.005996225;0.999473649,-2.630782082;-1.165544018;1.152143393\r\n", "ETs_another_et_another_et003.png_public,ETs,retry0cluster0,another_et_another_et003.png,0.998798941;-0.044963607;0.019466631;0.046239088;0.996406185;-0.070969439;-0.016205630;0.071784319;0.997288518,-2.836579362;0.335923573;-0.629379383\r\n", "ETs_another_et_another_et004.png_public,ETs,retry0cluster0,another_et_another_et004.png,0.999874847;-0.015001263;0.005025221;0.014249638;0.991943665;0.125875784;-0.006873032;-0.125788423;0.992033283,-2.744881245;-1.435499450;-0.168102760\r\n", "ETs_another_et_another_et005.png_public,ETs,retry0cluster0,another_et_another_et005.png,0.997821071;-0.001167554;0.065967767;-0.003011593;0.997995300;0.063216390;-0.065909330;-0.063277315;0.995817223,-3.269302698;-2.117297166;1.280104422\r\n", "ETs_another_et_another_et006.png_public,ETs,retry0cluster0,another_et_another_et006.png,0.909412177;0.188802321;-0.370571419;-0.217035177;0.975514142;-0.035607439;0.354774893;0.112808872;0.928121185,-0.561088859;-0.731866269;1.035371538\r\n", "ETs_another_et_another_et007.png_public,ETs,retry0cluster0,another_et_another_et007.png,0.761206641;0.259244632;-0.594438114;-0.307917750;0.951191508;0.020527378;0.570746099;0.167412470;0.803879317,1.140694571;-0.438559212;0.568582573\r\n", "ETs_another_et_another_et008.png_public,ETs,retry0cluster0,another_et_another_et008.png,0.540394551;0.305338861;-0.784054787;-0.388221970;0.917198348;0.089615246;0.746496773;0.255959703;0.614188243,2.824523246;-0.759641342;1.384132415\r\n", "ETs_another_et_another_et009.png_public,ETs,retry0cluster0,another_et_another_et009.png,0.285761926;0.338999318;-0.896336758;-0.481590348;0.859449981;0.171512292;0.828499160;0.382655448;0.408856882,4.454194213;-1.079959736;2.036306108\r\n", "====================================================================================================\n", "[Summary]\n", "- Dataset : ETs\n", "- images : 22\n", "- pairs : 231\n", "- laptime_image_pairs : 15.02\n", "- laptime_lightglue_4rots : 56.04\n", "- CV Avg Matches : 1739.2\n", "- CV Total Pairs : 60\n", "- CV Coverage : 26.0%\n", "- CV Largest Component : 10\n", "- CV Connectivity Score : 0.45\n", "====================================================================================================\n", "[Summary]\n", "- Dataset : stairs\n", "- images : 51\n", "- pairs : 1275\n", "- laptime_image_pairs : 29.23\n", "- laptime_lightglue_4rots : 406.51\n", "- CV Avg Matches : 336.7\n", "- CV Total Pairs : 138\n", "- CV Coverage : 10.8%\n", "- CV Largest Component : 34\n", "- CV Connectivity Score : 0.67\n" ] } ], "source": [ "# Must Create a submission file.\n", "array_to_str = lambda array: ';'.join([f\"{x:.09f}\" for x in array])\n", "none_to_str = lambda n: ';'.join(['nan'] * n)\n", "\n", "submission_file = '/kaggle/working/submission.csv'\n", "with open(submission_file, 'w') as f:\n", " if is_train:\n", " f.write('dataset,scene,image,rotation_matrix,translation_vector\\n')\n", " for dataset in samples:\n", " for prediction in samples[dataset]:\n", " cluster_name = 'outliers' if prediction.cluster_index is None else f'retry{prediction.retry_index}cluster{prediction.cluster_index}'\n", " rotation = none_to_str(9) if prediction.rotation is None else array_to_str(prediction.rotation.flatten())\n", " translation = none_to_str(3) if prediction.translation is None else array_to_str(prediction.translation)\n", " f.write(f'{prediction.dataset},{cluster_name},{prediction.filename},{rotation},{translation}\\n')\n", " else:\n", " f.write('image_id,dataset,scene,image,rotation_matrix,translation_vector\\n')\n", " for dataset in samples:\n", " for prediction in samples[dataset]:\n", " cluster_name = 'outliers' if prediction.cluster_index is None else f'retry{prediction.retry_index}cluster{prediction.cluster_index}'\n", " rotation = none_to_str(9) if prediction.rotation is None else array_to_str(prediction.rotation.flatten())\n", " translation = none_to_str(3) if prediction.translation is None else array_to_str(prediction.translation)\n", " f.write(f'{prediction.image_id},{prediction.dataset},{cluster_name},{prediction.filename},{rotation},{translation}\\n')\n", "\n", "!head {submission_file}\n", "\n", "for dataset_params in dataset_logs:\n", " print(\"=\" * 100)\n", " dataset_params.summary()\n", "\n", "# Definitely Compute results if running on the training set.\n", "if 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.')" ] }, { "cell_type": "code", "execution_count": null, "id": "8ee5d9bb", "metadata": { "papermill": { "duration": 0.018379, "end_time": "2026-01-03T14:48:16.479282", "exception": false, "start_time": "2026-01-03T14:48:16.460903", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "b167f06c", "metadata": { "papermill": { "duration": 0.018449, "end_time": "2026-01-03T14:48:16.516082", "exception": false, "start_time": "2026-01-03T14:48:16.497633", "status": "completed" }, "tags": [] }, "source": [] }, { "cell_type": "markdown", "id": "4a53e6ca", "metadata": { "papermill": { "duration": 0.018306, "end_time": "2026-01-03T14:48:16.552600", "exception": false, "start_time": "2026-01-03T14:48:16.534294", "status": "completed" }, "tags": [] }, "source": [ "この完全なスクリプトには、以下のCV評価機能が組み込まれています:\n", "\n", "1. **初期ペア選択の評価**\n", "2. **マッチング品質の評価** \n", "3. **最終マッチング結果の評価**\n", "4. **SfM前の連結性分析**\n", "5. **クラスタリング品質の評価**\n", "\n", "各段階で詳細なメトリクスが表示され、Configパラメータ調整の効果を追跡できます。" ] }, { "cell_type": "markdown", "id": "c7bd2e7a", "metadata": { "papermill": { "duration": 0.017601, "end_time": "2026-01-03T14:48:16.588085", "exception": false, "start_time": "2026-01-03T14:48:16.570484", "status": "completed" }, "tags": [] }, "source": [] }, { "cell_type": "code", "execution_count": null, "id": "9ccc50b4", "metadata": { "papermill": { "duration": 0.01783, "end_time": "2026-01-03T14:48:16.623674", "exception": false, "start_time": "2026-01-03T14:48:16.605844", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "b1519688", "metadata": { "papermill": { "duration": 0.018489, "end_time": "2026-01-03T14:48:16.661584", "exception": false, "start_time": "2026-01-03T14:48:16.643095", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] } ], "metadata": { "kaggle": { "accelerator": "nvidiaTeslaT4", "dataSources": [ { "databundleVersionId": 11655853, "sourceId": 91498, "sourceType": "competition" }, { "datasetId": 4628051, "sourceId": 7884485, "sourceType": "datasetVersion" }, { "datasetId": 6988459, "sourceId": 11924468, "sourceType": "datasetVersion" }, { "sourceId": 234271505, "sourceType": "kernelVersion" }, { "sourceId": 237741314, "sourceType": "kernelVersion" }, { "modelId": 986, "modelInstanceId": 3326, "sourceId": 4534, "sourceType": "modelInstanceVersion" }, { "modelId": 21716, "modelInstanceId": 14317, "sourceId": 17191, "sourceType": "modelInstanceVersion" }, { "modelId": 22086, "modelInstanceId": 14611, "sourceId": 17555, "sourceType": "modelInstanceVersion" } ], "dockerImageVersionId": 30919, "isGpuEnabled": true, "isInternetEnabled": false, "language": "python", "sourceType": "notebook" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" }, "papermill": { "default_parameters": {}, "duration": 882.733781, "end_time": "2026-01-03T14:48:20.643182", "environment_variables": {}, "exception": null, "input_path": "__notebook__.ipynb", "output_path": "__notebook__.ipynb", "parameters": {}, "start_time": "2026-01-03T14:33:37.909401", "version": "2.6.0" } }, "nbformat": 4, "nbformat_minor": 5 }