{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":49349,"databundleVersionId":5447706,"sourceType":"competition"},{"sourceId":12006632,"sourceType":"datasetVersion","datasetId":7553347},{"sourceId":12036742,"sourceType":"datasetVersion","datasetId":7553128},{"sourceId":418199,"sourceType":"modelInstanceVersion","modelInstanceId":341144,"modelId":362398},{"sourceId":418203,"sourceType":"modelInstanceVersion","modelInstanceId":341148,"modelId":362402},{"sourceId":422528,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":344318,"modelId":365592}],"dockerImageVersionId":31041,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install --no-index --find-links=/kaggle/input/imc2023-dependencies /kaggle/input/imc2023-dependencies/*.whl","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-02T12:36:55.067672Z","iopub.execute_input":"2025-06-02T12:36:55.067975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install --no-index --find-links=/kaggle/input/imc2023-dependencies /kaggle/input/imc2023-dependencies/*.whl","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install --no-index --find-links=/kaggle/input/imc2023-dependencies /kaggle/input/imc2023-dependencies/*.whl","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls /kaggle/input/image-matching-challenge-2023/test","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SUBMISSION_FILE_PATH = \"/kaggle/working/submission.csv\"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Copyright (c), ETH Zurich and UNC Chapel Hill.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n#     * Redistributions of source code must retain the above copyright\n#       notice, this list of conditions and the following disclaimer.\n#\n#     * Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of\n#       its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\n# This script is based on an original implementation by True Price.\n\nimport sqlite3\nimport sys\n\nimport numpy as np\n\nIS_PYTHON3 = sys.version_info[0] >= 3\n\nMAX_IMAGE_ID = 2**31 - 1\n\nCREATE_CAMERAS_TABLE = \"\"\"CREATE TABLE IF NOT EXISTS cameras (\n    camera_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n    model INTEGER NOT NULL,\n    width INTEGER NOT NULL,\n    height INTEGER NOT NULL,\n    params BLOB,\n    prior_focal_length INTEGER NOT NULL)\"\"\"\n\nCREATE_DESCRIPTORS_TABLE = \"\"\"CREATE TABLE IF NOT EXISTS descriptors (\n    image_id INTEGER PRIMARY KEY NOT NULL,\n    rows INTEGER NOT NULL,\n    cols INTEGER NOT NULL,\n    data BLOB,\n    FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)\"\"\"\n\nCREATE_IMAGES_TABLE = \"\"\"CREATE TABLE IF NOT EXISTS images (\n    image_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n    name TEXT NOT NULL UNIQUE,\n    camera_id INTEGER NOT NULL,\n    CONSTRAINT image_id_check CHECK(image_id >= 0 and image_id < {}),\n    FOREIGN KEY(camera_id) REFERENCES cameras(camera_id))\n\"\"\".format(\n    MAX_IMAGE_ID\n)\n\nCREATE_POSE_PRIORS_TABLE = \"\"\"CREATE TABLE IF NOT EXISTS pose_priors (\n    image_id INTEGER PRIMARY KEY NOT NULL,\n    position BLOB,\n    coordinate_system INTEGER NOT NULL,\n    position_covariance BLOB,\n    FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)\"\"\"\n\nCREATE_TWO_VIEW_GEOMETRIES_TABLE = \"\"\"\nCREATE TABLE IF NOT EXISTS two_view_geometries (\n    pair_id INTEGER PRIMARY KEY NOT NULL,\n    rows INTEGER NOT NULL,\n    cols INTEGER NOT NULL,\n    data BLOB,\n    config INTEGER NOT NULL,\n    F BLOB,\n    E BLOB,\n    H BLOB,\n    qvec BLOB,\n    tvec BLOB)\n\"\"\"\n\nCREATE_KEYPOINTS_TABLE = \"\"\"CREATE TABLE IF NOT EXISTS keypoints (\n    image_id INTEGER PRIMARY KEY NOT NULL,\n    rows INTEGER NOT NULL,\n    cols INTEGER NOT NULL,\n    data BLOB,\n    FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)\n\"\"\"\n\nCREATE_MATCHES_TABLE = \"\"\"CREATE TABLE IF NOT EXISTS matches (\n    pair_id INTEGER PRIMARY KEY NOT NULL,\n    rows INTEGER NOT NULL,\n    cols INTEGER NOT NULL,\n    data BLOB)\"\"\"\n\nCREATE_NAME_INDEX = (\n    \"CREATE UNIQUE INDEX IF NOT EXISTS index_name ON images(name)\"\n)\n\nCREATE_ALL = \"; \".join(\n    [\n        CREATE_CAMERAS_TABLE,\n        CREATE_IMAGES_TABLE,\n        CREATE_POSE_PRIORS_TABLE,\n        CREATE_KEYPOINTS_TABLE,\n        CREATE_DESCRIPTORS_TABLE,\n        CREATE_MATCHES_TABLE,\n        CREATE_TWO_VIEW_GEOMETRIES_TABLE,\n        CREATE_NAME_INDEX,\n    ]\n)\n\n\ndef image_ids_to_pair_id(image_id1, image_id2):\n    if image_id1 > image_id2:\n        image_id1, image_id2 = image_id2, image_id1\n    return image_id1 * MAX_IMAGE_ID + image_id2\n\n\ndef pair_id_to_image_ids(pair_id):\n    image_id2 = pair_id % MAX_IMAGE_ID\n    image_id1 = (pair_id - image_id2) / MAX_IMAGE_ID\n    return image_id1, image_id2\n\n\ndef array_to_blob(array):\n    if IS_PYTHON3:\n        return array.tostring()\n    else:\n        return np.getbuffer(array)\n\n\ndef blob_to_array(blob, dtype, shape=(-1,)):\n    if IS_PYTHON3:\n        return np.fromstring(blob, dtype=dtype).reshape(*shape)\n    else:\n        return np.frombuffer(blob, dtype=dtype).reshape(*shape)\n\n\nclass COLMAPDatabase(sqlite3.Connection):\n    @staticmethod\n    def connect(database_path):\n        return sqlite3.connect(database_path, factory=COLMAPDatabase)\n\n    def __init__(self, *args, **kwargs):\n        super(COLMAPDatabase, self).__init__(*args, **kwargs)\n\n        self.create_tables = lambda: self.executescript(CREATE_ALL)\n        self.create_cameras_table = lambda: self.executescript(\n            CREATE_CAMERAS_TABLE\n        )\n        self.create_descriptors_table = lambda: self.executescript(\n            CREATE_DESCRIPTORS_TABLE\n        )\n        self.create_images_table = lambda: self.executescript(\n            CREATE_IMAGES_TABLE\n        )\n        self.create_pose_priors_table = lambda: self.executescript(\n            CREATE_POSE_PRIORS_TABLE\n        )\n        self.create_two_view_geometries_table = lambda: self.executescript(\n            CREATE_TWO_VIEW_GEOMETRIES_TABLE\n        )\n        self.create_keypoints_table = lambda: self.executescript(\n            CREATE_KEYPOINTS_TABLE\n        )\n        self.create_matches_table = lambda: self.executescript(\n            CREATE_MATCHES_TABLE\n        )\n        self.create_name_index = lambda: self.executescript(CREATE_NAME_INDEX)\n\n    def add_camera(\n        self,\n        model,\n        width,\n        height,\n        params,\n        prior_focal_length=False,\n        camera_id=None,\n    ):\n        params = np.asarray(params, np.float64)\n        cursor = self.execute(\n            \"INSERT INTO cameras VALUES (?, ?, ?, ?, ?, ?)\",\n            (\n                camera_id,\n                model,\n                width,\n                height,\n                array_to_blob(params),\n                prior_focal_length,\n            ),\n        )\n        return cursor.lastrowid\n\n    def add_image(\n        self,\n        name,\n        camera_id,\n        image_id=None,\n    ):\n        cursor = self.execute(\n            \"INSERT INTO images VALUES (?, ?, ?)\", (image_id, name, camera_id)\n        )\n        return cursor.lastrowid\n\n    def add_pose_prior(\n        self,\n        image_id,\n        position,\n        coordinate_system=-1,\n        position_covariance=None,\n    ):\n        position = np.asarray(position, dtype=np.float64)\n        if position_covariance is None:\n            position_covariance = np.full((3, 3), np.nan, dtype=np.float64)\n        self.execute(\n            \"INSERT INTO pose_priors VALUES (?, ?, ?, ?)\",\n            (\n                image_id,\n                array_to_blob(position),\n                coordinate_system,\n                array_to_blob(position_covariance),\n            ),\n        )\n\n    def add_keypoints(self, image_id, keypoints):\n        assert len(keypoints.shape) == 2\n        assert keypoints.shape[1] in [2, 4, 6]\n\n        keypoints = np.asarray(keypoints, np.float32)\n        self.execute(\n            \"INSERT INTO keypoints VALUES (?, ?, ?, ?)\",\n            (image_id,) + keypoints.shape + (array_to_blob(keypoints),),\n        )\n\n    def add_descriptors(self, image_id, descriptors):\n        descriptors = np.ascontiguousarray(descriptors, np.uint8)\n        self.execute(\n            \"INSERT INTO descriptors VALUES (?, ?, ?, ?)\",\n            (image_id,) + descriptors.shape + (array_to_blob(descriptors),),\n        )\n\n    def add_matches(self, image_id1, image_id2, matches):\n        assert len(matches.shape) == 2\n        assert matches.shape[1] == 2\n\n        if image_id1 > image_id2:\n            matches = matches[:, ::-1]\n\n        pair_id = image_ids_to_pair_id(image_id1, image_id2)\n        matches = np.asarray(matches, np.uint32)\n        self.execute(\n            \"INSERT INTO matches VALUES (?, ?, ?, ?)\",\n            (pair_id,) + matches.shape + (array_to_blob(matches),),\n        )\n\n    def add_two_view_geometry(\n        self,\n        image_id1,\n        image_id2,\n        matches,\n        F=np.eye(3),\n        E=np.eye(3),\n        H=np.eye(3),\n        qvec=np.array([1.0, 0.0, 0.0, 0.0]),\n        tvec=np.zeros(3),\n        config=2,\n    ):\n        assert len(matches.shape) == 2\n        assert matches.shape[1] == 2\n\n        if image_id1 > image_id2:\n            matches = matches[:, ::-1]\n\n        pair_id = image_ids_to_pair_id(image_id1, image_id2)\n        matches = np.asarray(matches, np.uint32)\n        F = np.asarray(F, dtype=np.float64)\n        E = np.asarray(E, dtype=np.float64)\n        H = np.asarray(H, dtype=np.float64)\n        qvec = np.asarray(qvec, dtype=np.float64)\n        tvec = np.asarray(tvec, dtype=np.float64)\n        self.execute(\n            \"INSERT INTO two_view_geometries VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n            (pair_id,)\n            + matches.shape\n            + (\n                array_to_blob(matches),\n                config,\n                array_to_blob(F),\n                array_to_blob(E),\n                array_to_blob(H),\n                array_to_blob(qvec),\n                array_to_blob(tvec),\n            ),\n        )\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pycolmap","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nsys.path.append(\"/kaggle/input/lightglue\")\n\nfrom lightglue import ALIKED, DISK, SIFT, DoGHardNet, LightGlue, SuperPoint\nfrom lightglue.utils import load_image, rbd, read_image\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import csv\nimport logging\nimport pathlib\nimport pprint\nimport sys\nimport time\nfrom collections import Counter, defaultdict\nimport csv\nimport pathlib\nimport sys\nfrom collections import Counter, defaultdict\n\n\n\nimport numpy as np\nimport pycolmap\nimport torch\nfrom loguru import logger\nfrom sklearn.cluster import DBSCAN\nfrom tqdm import tqdm\n\nimport cv2\nimport numpy as np\nimport pycolmap\nimport torch\nfrom loguru import logger\nfrom PIL import ExifTags, Image\nfrom tqdm import tqdm","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!mkdir -p /root/.cache/torch/hub/checkpoints/\n\n!cp /kaggle/input/imc2023-models/pytorch/default/1/aliked-n16rot.pth /root/.cache/torch/hub/checkpoints/aliked-n16rot.pth\n!cp /kaggle/input/imc2023-models/pytorch/default/1/aliked_lightglue_v0-1_arxiv.pth /root/.cache/torch/hub/checkpoints/aliked_lightglue_v0-1_arxiv.pth\n!cp /kaggle/input/imc2023-models/pytorch/default/1/depth-save.pth /root/.cache/torch/hub/checkpoints/depth-save.pth\n!cp /kaggle/input/imc2023-models/pytorch/default/1/disk_lightglue_v0-1_arxiv.pth /root/.cache/torch/hub/checkpoints/disk_lightglue_v0-1_arxiv.pth\n!cp /kaggle/input/imc2023-models/pytorch/default/1/superpoint_lightglue_v0-1_arxiv.pth /root/.cache/torch/hub/checkpoints/superpoint_lightglue_v0-1_arxiv.pth\n!cp /kaggle/input/imc2023-models/pytorch/default/1/superpoint_v1.pth /root/.cache/torch/hub/checkpoints/superpoint_v1.pth\n# !cp /kaggle/input/aliked-n16rot/pytorch/default/1/aliked-n16rot.pth /root/.cache/torch/hub/checkpoints/aliked-n16rot.pth\n# !cp /kaggle/input/aliked_lightglue_v0-1_arxiv/pytorch/default/1/aliked_lightglue_v0-1_arxiv.pth /root/.cache/torch/hub/checkpoints/aliked_lightglue_v0-1_arxiv.pth","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"extractors = {\n    \"aliked\": ALIKED(\n        model_name=\"aliked-n16rot\",\n        device=\"cuda\",\n        top_k=-1,\n        scores_th=0.2,\n        n_limit=5000,\n        nms_radius=2,\n    )\n    .eval()\n    .cuda(),\n    \"disk\": DISK(device=\"cuda\").eval().cuda(),\n    \"superpoint\": SuperPoint(device=\"cuda\").eval().cuda(),\n}\n\nmatchers = {\n    \"aliked\": LightGlue(features=\"aliked\", filter_threshold=0.1).eval().cuda(),\n    \"disk\": LightGlue(features=\"disk\", filter_threshold=0.1).eval().cuda(),\n    \"superpoint\": LightGlue(features=\"superpoint\", filter_threshold=0.1)\n    .eval()\n    .cuda(),\n}\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"CAMERA_MODEL_MAP = {\n    \"SIMPLE_RADIAL\": 2,\n    \"OPENCV\": 4,\n}","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_DIR_PATH = pathlib.Path(\"/kaggle/input/image-matching-challenge-2023/test\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"scene_set = set()\nfor path in DATA_DIR_PATH.iterdir():\n    if path.is_dir():  # dataset\n        for path_ in path.iterdir():  # scene\n            if path_.is_dir():\n                scene_set.add((path.stem, path_.stem))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open(SUBMISSION_FILE_PATH, \"w\", newline=\"\") as f:\n    writer = csv.writer(f)\n    writer.writerow(\n        [\n            \"image_path\",\n            \"dataset\",\n            \"scene\",\n            \"rotation_matrix\",\n            \"translation_vector\",\n        ]\n    )","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for dataset_name, scene_name in scene_set:\n    logger.debug(f\"{dataset_name=}, {scene_name=}\")\n    image_dir = DATA_DIR_PATH / dataset_name / scene_name / \"images\"\n\n    image_paths = []\n    for ext in (\"*.jpg\", \"*.JPG\", \"*.jpeg\", \"*.png\", \"*.PNG\"):\n        image_paths.extend(image_dir.rglob(ext))\n\n    feature_dir = pathlib.Path(\"feature\") / f\"{dataset_name}_{scene_name}\"\n    feature_dir.mkdir(parents=True, exist_ok=True)\n\n    database_path = feature_dir / \"colmap.db\"\n    db = COLMAPDatabase.connect(database_path)\n    db.create_tables()\n\n    output_dir = feature_dir / \"sfm\"\n    output_dir.mkdir(parents=True, exist_ok=True)\n\n    image_id_map = {}\n    for image_path in tqdm(image_paths, desc=\"Add cameras and images\"):\n        image = read_image(image_path)\n        h, w, c = image.shape\n        focal = 1.2 * max(w, h)\n        camera_id = db.add_camera(\n            CAMERA_MODEL_MAP[\"SIMPLE_RADIAL\"],\n            width=w,\n            height=h,\n            params=np.array([focal, w / 2, h / 2, 0.1]),\n            prior_focal_length=False,\n        )\n        image_id = db.add_image(image_path.name, camera_id)\n        image_id_map[str(image_path)] = image_id\n\n    feature_map_all = {k: {} for k in extractors}\n    keypoint_freq_map_all = {k: {} for k in extractors}\n\n    for image_path in tqdm(image_paths, desc=\"Extracting features (no crop)\"):\n        image_tensor = load_image(image_path).cuda()\n        for name, extractor in extractors.items():\n            features = extractor.extract(image_tensor)\n            feature_map_all[name][image_path] = features\n            keypoint_freq_map_all[name][image_path] = Counter()\n\n    pool = []\n    for i, p0 in enumerate(image_paths):\n        for j, p1 in enumerate(image_paths):\n            if j <= i:\n                continue\n            for name in extractors:\n                matches = rbd(\n                    matchers[name](\n                        {\n                            \"image0\": feature_map_all[name][p0],\n                            \"image1\": feature_map_all[name][p1],\n                        }\n                    )\n                )\n                matches_arr = matches[\"matches\"].cpu().numpy()\n                for idx0, idx1 in matches_arr:\n                    keypoint_freq_map_all[name][p0][idx0] += 1\n                    keypoint_freq_map_all[name][p1][idx1] += 1\n                pool.append(\n                    {\n                        \"cropped\": False,\n                        \"p0\": p0,\n                        \"p1\": p1,\n                        \"bbox0\": None,\n                        \"bbox1\": None,\n                        \"kps0\": rbd(feature_map_all[name][p0])[\"keypoints\"]\n                        .cpu()\n                        .numpy(),\n                        \"kps1\": rbd(feature_map_all[name][p1])[\"keypoints\"]\n                        .cpu()\n                        .numpy(),\n                        \"matches\": matches_arr,\n                    }\n                )\n\n    cropped_bbox_list_map = {}\n    for image_path in tqdm(image_paths, desc=\"Cropping\"):\n        cropped_bbox_list_map[image_path] = []\n        for name in extractors:\n            freq_counter = keypoint_freq_map_all[name][image_path]\n            if not freq_counter:\n                continue\n            max_count = max(freq_counter.values())\n            high_freq_keypoint_ids = [\n                k for k, v in freq_counter.items() if v / max_count > 0.15\n            ]\n            image_tensor = load_image(image_path)\n            c, h, w = image_tensor.shape\n            features = rbd(feature_map_all[name][image_path])\n            keypoints = (\n                features[\"keypoints\"]\n                .cpu()\n                .numpy()\n                .astype(np.float32)[high_freq_keypoint_ids]\n            )\n            num_keypoints = len(keypoints)\n            normalized_keypoints = keypoints / np.array([w, h])\n            clustering = DBSCAN(eps=0.05, min_samples=16).fit(\n                normalized_keypoints\n            )\n            groups, counts = np.unique(clustering.labels_, return_counts=True)\n            max_group, max_count = None, 0\n            no_crop = False\n            for group, count in zip(groups, counts):\n                if group == -1:\n                    if count / num_keypoints > 0.2:\n                        no_crop = True\n                    continue\n                if count > max_count:\n                    max_count = count\n                    max_group = group\n            if no_crop:\n                continue\n            candidate_groups = set()\n            for group, count in zip(groups, counts):\n                if group == -1:\n                    continue\n                if group == max_group or count / num_keypoints > 0.05:\n                    candidate_groups.add(group)\n            for group in candidate_groups:\n                points = keypoints[clustering.labels_ == group]\n                x_min, y_min = np.min(points, axis=0).astype(int)\n                x_max, y_max = np.max(points, axis=0).astype(int)\n                x_min = max(x_min - 10, 0)\n                y_min = max(y_min - 10, 0)\n                x_max = min(x_max + 10, w)\n                y_max = min(y_max + 10, h)\n                cropped_bbox_list_map[image_path].append(\n                    (x_min, y_min, x_max, y_max)\n                )\n\n    cropped_feature_list_map = {k: defaultdict(list) for k in extractors}\n    for image_path in tqdm(image_paths, desc=\"Extracting features (cropped)\"):\n        image_tensor = load_image(image_path).cuda()\n        for name, extractor in extractors.items():\n            for x_min, y_min, x_max, y_max in cropped_bbox_list_map[\n                image_path\n            ]:\n                cropped_image_tensor = image_tensor[\n                    :, y_min:y_max, x_min:x_max\n                ]\n                cropped_features = extractor.extract(cropped_image_tensor)\n                cropped_feature_list_map[name][image_path].append(\n                    {\n                        \"bbox\": (x_min, y_min, x_max, y_max),\n                        \"features\": cropped_features,\n                    }\n                )\n\n    for i, p0 in enumerate(image_paths):\n        for j, p1 in enumerate(image_paths):\n            if j <= i:\n                continue\n            for name in extractors:\n                for e0 in cropped_feature_list_map[name][p0]:\n                    for e1 in cropped_feature_list_map[name][p1]:\n                        cropped_matches = matchers[name](\n                            {\n                                \"image0\": e0[\"features\"],\n                                \"image1\": e1[\"features\"],\n                            }\n                        )\n                        pool.append(\n                            {\n                                \"cropped\": True,\n                                \"p0\": p0,\n                                \"p1\": p1,\n                                \"bbox0\": e0[\"bbox\"],\n                                \"bbox1\": e1[\"bbox\"],\n                                \"kps0\": rbd(e0[\"features\"])[\"keypoints\"]\n                                .cpu()\n                                .numpy(),\n                                \"kps1\": rbd(e1[\"features\"])[\"keypoints\"]\n                                .cpu()\n                                .numpy(),\n                                \"matches\": rbd(cropped_matches)[\"matches\"]\n                                .cpu()\n                                .numpy(),\n                            }\n                        )\n\n    image_local_to_global = {}\n    global_kp_counter = defaultdict(int)\n    image_kp_map = defaultdict(list)\n    global_matches_map = defaultdict(list)\n\n    for entry in pool:\n        p0, p1 = str(entry[\"p0\"]), str(entry[\"p1\"])\n        kps0, kps1 = entry[\"kps0\"], entry[\"kps1\"]\n        matches = entry[\"matches\"]\n        bbox0, bbox1 = entry[\"bbox0\"], entry[\"bbox1\"]\n        if entry[\"cropped\"]:\n            kps0 += np.array([bbox0[0], bbox0[1]])\n            kps1 += np.array([bbox1[0], bbox1[1]])\n        for local_idx, kp in enumerate(kps0):\n            key = (p0, local_idx)\n            if key not in image_local_to_global:\n                image_local_to_global[key] = global_kp_counter[p0]\n                image_kp_map[p0].append(kp)\n                global_kp_counter[p0] += 1\n        for local_idx, kp in enumerate(kps1):\n            key = (p1, local_idx)\n            if key not in image_local_to_global:\n                image_local_to_global[key] = global_kp_counter[p1]\n                image_kp_map[p1].append(kp)\n                global_kp_counter[p1] += 1\n        for m in matches:\n            gid0 = image_local_to_global[(p0, m[0])]\n            gid1 = image_local_to_global[(p1, m[1])]\n            global_matches_map[(p0, p1)].append((gid0, gid1))\n\n    for image_path, keypoints in image_kp_map.items():\n        db.add_keypoints(\n            image_id_map[image_path], np.array(keypoints, dtype=np.float32)\n        )\n\n    for (p0, p1), matches in global_matches_map.items():\n        db.add_matches(\n            image_id_map[p0],\n            image_id_map[p1],\n            np.array(matches, dtype=np.uint32),\n        )\n\n    db.commit()\n    db.close()\n\n    pycolmap.match_exhaustive(str(database_path))\n    logger.debug(f\"incremental_mapping...\")\n\n    mapper_options = pycolmap.IncrementalPipelineOptions(\n        min_model_size=3,\n        max_num_models=5,\n    )\n\n    recons = pycolmap.incremental_mapping(\n        database_path=str(database_path),\n        image_path=image_dir,\n        output_path=str(output_dir),\n        options=mapper_options,\n    )\n\n    best_recon_num_images = 0\n    best_recon_idx = None\n    for idx, recon in recons.items():\n        num_images = len(recon.images)\n        if num_images > best_recon_num_images:\n            best_recon_num_images = num_images\n            best_recon_idx = idx\n\n    recon_results = defaultdict(lambda: {\"R\": np.eye(3), \"t\": np.zeros(3)})\n    if best_recon_idx is not None:\n        recon = recons[best_recon_idx]\n        for image_id in recon.reg_image_ids():\n            image = recon.images[image_id]\n            cam_from_world = image.cam_from_world.matrix()\n            recon_results[image.name] = {\n                \"R\": cam_from_world[:3, :3],\n                \"t\": cam_from_world[:3, 3],\n            }\n\n    for image_path in tqdm(image_paths, desc=\"Extracting features\"):\n        image_name = image_path.name\n        with open(SUBMISSION_FILE_PATH, \"a\", newline=\"\") as f:\n            writer = csv.writer(f)\n            writer.writerow(\n                [\n                    f\"{dataset_name}/{scene_name}/images/{image_name}\",\n                    dataset_name,\n                    scene_name,\n                    \";\".join(\n                        map(str, recon_results[image_name][\"R\"].flatten())\n                    ),\n                    \";\".join(map(str, recon_results[image_name][\"t\"])),\n                ]\n            )\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}