{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"origin：https://www.kaggle.com/code/eduardtrulls/imc-2023-submission-example?scriptVersionId=129165789","metadata":{}},{"cell_type":"code","source":"# General utilities\nimport os\nfrom tqdm import tqdm\nfrom time import time\nfrom fastprogress import progress_bar\nimport gc\nimport numpy as np\nimport h5py\nfrom IPython.display import clear_output\nfrom collections import defaultdict\nfrom copy import deepcopy\n\n# CV/ML\nimport cv2\nimport torch\nimport torch.nn.functional as F\nimport kornia as K\nimport kornia.feature as KF\nfrom PIL import Image\nimport timm\nfrom timm.data import resolve_data_config\nfrom timm.data.transforms_factory import create_transform\n\n# 3D reconstruction\nimport pycolmap","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-24T01:19:11.891605Z","iopub.execute_input":"2023-05-24T01:19:11.892334Z","iopub.status.idle":"2023-05-24T01:19:11.900381Z","shell.execute_reply.started":"2023-05-24T01:19:11.892291Z","shell.execute_reply":"2023-05-24T01:19:11.899253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Kornia version', K.__version__)\nprint('Pycolmap version', pycolmap.__version__)\n\ndry_run = False\n!pip install /kaggle/input/kornia-loftr/kornia-0.6.4-py2.py3-none-any.whl\n!pip install /kaggle/input/kornia-loftr/kornia_moons-0.1.9-py3-none-any.whl\nLOCAL_FEATURE = 'SuperGlue'\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n# -------------------Importing LOFTR\nimport os\nimport numpy as np\nimport cv2\nimport csv\nfrom glob import glob\nimport torch\nimport matplotlib.pyplot as plt\nimport kornia\nfrom kornia_moons.feature import *\nimport kornia as K\nimport kornia.feature as KF\nimport gc\nmatcher = KF.LoFTR(pretrained=None)\nmatcher.load_state_dict(torch.load(\"/kaggle/input/kornia-loftr/loftr_outdoor.ckpt\")['state_dict'])\nmatcher = matcher.to(device).eval()\n\n# --------------------Importing Super Glue¶\nimport sys\nsys.path.append(\"/kaggle/input/super-glue-pretrained-network\")\nfrom models.matching import Matching\nfrom models.utils import (compute_pose_error, compute_epipolar_error,\n                          estimate_pose, make_matching_plot,\n                          error_colormap, AverageTimer, pose_auc, read_image,\n                          rotate_intrinsics, rotate_pose_inplane,\n                          scale_intrinsics)\n\n\nresize_float = True\n\nconfig = {\n    \"superpoint\": {\n        \"nms_radius\": 3,\n        \"keypoint_threshold\": 0.005,\n        \"max_keypoints\": 2048\n    },\n    \"superglue\": {\n        \"weights\": \"outdoor\",\n        \"sinkhorn_iterations\": 100,\n        \"match_threshold\": 0.4,\n    }\n}\nmatching = Matching(config).eval().to(device)","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:11.902324Z","iopub.execute_input":"2023-05-24T01:19:11.903431Z","iopub.status.idle":"2023-05-24T01:19:11.914418Z","shell.execute_reply.started":"2023-05-24T01:19:11.903389Z","shell.execute_reply":"2023-05-24T01:19:11.913169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def arr_to_str(a):\n    return ';'.join([str(x) for x in a.reshape(-1)])\n\n\ndef load_torch_image(fname, device=torch.device('cpu')):\n    img = K.image_to_tensor(cv2.imread(fname), False).float() / 255.\n    img = K.color.bgr_to_rgb(img.to(device))\n    return img","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:11.917364Z","iopub.execute_input":"2023-05-24T01:19:11.917816Z","iopub.status.idle":"2023-05-24T01:19:11.925294Z","shell.execute_reply.started":"2023-05-24T01:19:11.917778Z","shell.execute_reply":"2023-05-24T01:19:11.924084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# We will use ViT global descriptor to get matching shortlists.\ndef get_global_desc(fnames, model,\n                    device =  torch.device('cpu')):\n    model = model.eval()\n    model= model.to(device)\n    config = resolve_data_config({}, model=model)\n    transform = create_transform(**config)\n    global_descs_convnext=[]\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        img = Image.open(img_fname_full).convert('RGB')\n        timg = transform(img).unsqueeze(0).to(device)\n        with torch.no_grad():\n            desc = model.forward_features(timg.to(device)).mean(dim=(-1,2))#\n            #print (desc.shape)\n            desc = desc.view(1, -1)\n            desc_norm = F.normalize(desc, dim=1, p=2)\n        #print (desc_norm)\n        global_descs_convnext.append(desc_norm.detach().cpu())\n    global_descs_all = torch.cat(global_descs_convnext, dim=0)\n    return global_descs_all\n\n#该函数用于提取图像的全局描述符。它接受一个图像文件名列表fnames，一个模型model，和一个可选的device参数，默认为torch.device('cpu')。\n#首先，将模型设置为评估模式，并将其移动到指定的设备上。然后，使用resolve_data_config函数解析模型配置，\n#并使用create_transform函数创建数据转换。然后，对于每个图像文件名，打开图像文件并将其转换为RGB格式，然后应用数据转换并将图像转换为张量。\n#之后，使用模型提取特征，并计算特征的均值，得到全局描述符。最后，将所有图像的全局描述符拼接成一个张量并返回。\n\ndef 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\n#该函数用于生成图像之间的完全匹配的索引对。它接受一个图像文件名列表img_fnames作为输入。\n#函数通过两层循环遍历所有图像文件名的组合，生成索引对。对于索引i和j，其中i<j，会生成一个索引对(i, j)。最后，返回所有生成的索引对。\n\ndef 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('cpu')):\n    num_imgs = len(fnames)\n\n    if num_imgs <= exhaustive_if_less:\n        return get_img_pairs_exhaustive(fnames)\n\n    model = timm.create_model('tf_efficientnet_b7',\n                              checkpoint_path='/kaggle/input/tf-efficientnet-b7/tf_efficientnet_b7_ra-6c08e654.pth')\n    model.eval()\n    descs = get_global_desc(fnames, model, device=device)\n    dm = torch.cdist(descs, descs, p=2).detach().cpu().numpy()\n    # removing half\n    mask = dm <= sim_th\n    total = 0\n    matching_list = []\n    ar = np.arange(num_imgs)\n    already_there_set = []\n    for st_idx in range(num_imgs-1):\n        mask_idx = mask[st_idx]\n        to_match = ar[mask_idx]\n        if len(to_match) < min_pairs:\n            to_match = np.argsort(dm[st_idx])[:min_pairs]  \n        for idx in to_match:\n            if st_idx == idx:\n                continue\n            if dm[st_idx, idx] < 1000:\n                matching_list.append(tuple(sorted((st_idx, idx.item()))))\n                total+=1\n    matching_list = sorted(list(set(matching_list)))\n    return matching_list","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:11.927382Z","iopub.execute_input":"2023-05-24T01:19:11.927827Z","iopub.status.idle":"2023-05-24T01:19:11.949317Z","shell.execute_reply.started":"2023-05-24T01:19:11.927789Z","shell.execute_reply":"2023-05-24T01:19:11.948304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Code to manipulate a colmap database.\n# Forked from https://github.com/colmap/colmap/blob/dev/scripts/python/database.py\n\n# Copyright (c) 2018, 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# Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)\n\n# This script is based on an original implementation by True Price.\n\nimport sys\nimport sqlite3\nimport numpy as np\n\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    prior_qw REAL,\n    prior_qx REAL,\n    prior_qy REAL,\n    prior_qz REAL,\n    prior_tx REAL,\n    prior_ty REAL,\n    prior_tz REAL,\n    CONSTRAINT image_id_check CHECK(image_id >= 0 and image_id < {}),\n    FOREIGN KEY(camera_id) REFERENCES cameras(camera_id))\n\"\"\".format(MAX_IMAGE_ID)\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\"\"\"\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\nCREATE_ALL = \"; \".join([\n    CREATE_CAMERAS_TABLE,\n    CREATE_IMAGES_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\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\n    @staticmethod\n    def connect(database_path):\n        return sqlite3.connect(database_path, factory=COLMAPDatabase)\n\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 = \\\n            lambda: self.executescript(CREATE_CAMERAS_TABLE)\n        self.create_descriptors_table = \\\n            lambda: self.executescript(CREATE_DESCRIPTORS_TABLE)\n        self.create_images_table = \\\n            lambda: self.executescript(CREATE_IMAGES_TABLE)\n        self.create_two_view_geometries_table = \\\n            lambda: self.executescript(CREATE_TWO_VIEW_GEOMETRIES_TABLE)\n        self.create_keypoints_table = \\\n            lambda: self.executescript(CREATE_KEYPOINTS_TABLE)\n        self.create_matches_table = \\\n            lambda: self.executescript(CREATE_MATCHES_TABLE)\n        self.create_name_index = lambda: self.executescript(CREATE_NAME_INDEX)\n\n    def add_camera(self, model, width, height, params,\n                   prior_focal_length=False, camera_id=None):\n        params = np.asarray(params, np.float64)\n        cursor = self.execute(\n            \"INSERT INTO cameras VALUES (?, ?, ?, ?, ?, ?)\",\n            (camera_id, model, width, height, array_to_blob(params),\n             prior_focal_length))\n        return cursor.lastrowid\n\n    def add_image(self, name, camera_id,\n                  prior_q=np.zeros(4), prior_t=np.zeros(3), image_id=None):\n        cursor = self.execute(\n            \"INSERT INTO images VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n            (image_id, name, camera_id, prior_q[0], prior_q[1], prior_q[2],\n             prior_q[3], prior_t[0], prior_t[1], prior_t[2]))\n        return cursor.lastrowid\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    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    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    def add_two_view_geometry(self, image_id1, image_id2, matches,\n                              F=np.eye(3), E=np.eye(3), H=np.eye(3), config=2):\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        self.execute(\n            \"INSERT INTO two_view_geometries VALUES (?, ?, ?, ?, ?, ?, ?, ?)\",\n            (pair_id,) + matches.shape + (array_to_blob(matches), config,\n             array_to_blob(F), array_to_blob(E), array_to_blob(H)))","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.17936Z","iopub.execute_input":"2023-05-24T01:19:12.179721Z","iopub.status.idle":"2023-05-24T01:19:12.215656Z","shell.execute_reply.started":"2023-05-24T01:19:12.179661Z","shell.execute_reply":"2023-05-24T01:19:12.214525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Code to interface DISK with Colmap.\n# Forked from https://github.com/cvlab-epfl/disk/blob/37f1f7e971cea3055bb5ccfc4cf28bfd643fa339/colmap/h5_to_db.py\n\n#  Copyright [2020] [Michał Tyszkiewicz, Pascal Fua, Eduard Trulls]\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\n\nimport os, argparse, h5py, warnings\nimport numpy as np\nfrom tqdm import tqdm\nfrom PIL import Image, ExifTags\n\n\ndef get_focal(image_path, err_on_default=False):\n    image         = Image.open(image_path)\n    max_size      = max(image.size)\n\n    exif = image.getexif()\n    focal = None\n    if exif is not None:\n        focal_35mm = None\n        # https://github.com/colmap/colmap/blob/d3a29e203ab69e91eda938d6e56e1c7339d62a99/src/util/bitmap.cc#L299\n        for tag, value in exif.items():\n            focal_35mm = None\n            if ExifTags.TAGS.get(tag, None) == 'FocalLengthIn35mmFilm':\n                focal_35mm = float(value)\n                break\n\n        if focal_35mm is not None:\n            focal = focal_35mm / 35. * max_size\n    \n    if focal is None:\n        if err_on_default:\n            raise RuntimeError(\"Failed to find focal length\")\n\n        # failed to find it in exif, use prior\n        FOCAL_PRIOR = 1.2\n        focal = FOCAL_PRIOR * max_size\n\n    return focal\n#get_focal 函数用于从图像文件中获取焦距信息。它接受图像文件路径 image_path 和一个可选的 err_on_default 参数，默认为 False。\n#函数打开图像文件，并获取其尺寸信息。然后，尝试从图像的EXIF数据中获取焦距信息。如果成功获取到焦距，根据相对于35mm胶片的焦距进行换算，\n#得到相对于图像尺寸的焦距。如果无法获取焦距信息，根据默认的先验值计算一个焦距。最后，返回计算得到的焦距。\n\n\ndef create_camera(db, image_path, camera_model):\n    image         = Image.open(image_path)\n    width, height = image.size\n\n    focal = get_focal(image_path)\n\n    if camera_model == 'simple-pinhole':\n        model = 0 # simple pinhole\n        param_arr = np.array([focal, width / 2, height / 2])\n    if camera_model == 'pinhole':\n        model = 1 # pinhole\n        param_arr = np.array([focal, focal, width / 2, height / 2])\n    elif camera_model == 'simple-radial':\n        model = 2 # simple radial\n        param_arr = np.array([focal, width / 2, height / 2, 0.1])\n    elif camera_model == 'opencv':\n        model = 4 # opencv\n        param_arr = np.array([focal, focal, width / 2, height / 2, 0., 0., 0., 0.])\n         \n    return db.add_camera(model, width, height, param_arr)\n#create_camera 函数用于向数据库中添加相机信息。它接受一个数据库对象 db，图像文件路径 image_path 和相机模型 camera_model。\n#函数打开图像文件，并获取图像的宽度和高度。然后，调用 get_focal 函数获取图像的焦距。根据相机模型类型，选择相应的相机模型ID和参数数组。\n#最后，调用数据库的 add_camera 方法添加相机信息，并返回相机ID。\n\ndef add_keypoints(db, 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        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\n\ndef add_matches(db, 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            group = match_file[key_1]\n            for key_2 in group.keys():\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\n                added.add(pair_id)\n\n                pbar.update(1)\n# 这段代码用于将DISK的结果与COLMAP进行接口对接，下面对其进行注释和解释：","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.218424Z","iopub.execute_input":"2023-05-24T01:19:12.219363Z","iopub.status.idle":"2023-05-24T01:19:12.262364Z","shell.execute_reply.started":"2023-05-24T01:19:12.219332Z","shell.execute_reply":"2023-05-24T01:19:12.261329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.263874Z","iopub.execute_input":"2023-05-24T01:19:12.264973Z","iopub.status.idle":"2023-05-24T01:19:12.279596Z","shell.execute_reply.started":"2023-05-24T01:19:12.264897Z","shell.execute_reply":"2023-05-24T01:19:12.278511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_unique_idxs(A, dim=0):\n    # https://stackoverflow.com/questions/72001505/how-to-get-unique-elements-and-their-firstly-appeared-indices-of-a-pytorch-tenso\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\n\n\ndef import_into_colmap(img_dir,\n                       feature_dir ='.featureout',\n                       database_path = 'colmap.db',\n                       img_ext='.jpg'):\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, img_ext, 'simple-radial', single_camera)\n    add_matches(\n        db,\n        feature_dir,\n        fname_to_id,\n    )\n\n    db.commit()\n    return\n\n#-----------------------------------------\ndef load_image1(fname):\n    img = cv2.imread(fname)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    img = K.image_to_tensor(img, False).float() /255.\n    return img.to(device)\n\n\ndef load_resized_image1(img, resize): # function t read an image at a particular scale(when image itself is given)\n    img=img[0,0,:,:]\n    h, w = img.shape\n    img=img.cpu().numpy()\n    scale = resize / max(h, w) \n    w_new = int(w * scale)\n    h_new = int(h * scale)\n    \n    img = cv2.resize(img, (w_new, h_new))\n#     img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    img = torch.from_numpy(img)[None][None]\n    \n    return img.to(device), [h_new/h,w_new/w]\n\ndef get_superglue(img1,img2):\n    pred = matching({\"image0\": img1, \"image1\": img2})\n    pred = {k: v[0].detach().cpu().numpy() for k, v in pred.items()}\n    # nd1 = time.time()\n    kpts1, kpts2 = pred[\"keypoints0\"], pred[\"keypoints1\"]\n    matches, conf = pred[\"matches0\"], pred[\"matching_scores0\"]\n\n    valid = matches > -1\n    a1 = kpts1[valid]\n    a2 = kpts2[matches[valid]]\n    mconf = conf[valid]\n    return a1,a2\n\n\ndef scale_to_resized(mkpts0, mkpts1, scale1,scale2):\n    ### scale to original im size because we used max_image_size\n    # first point\n    mkpts0[:, 0] = mkpts0[:, 0] / scale1[0]\n    mkpts0[:, 1] = mkpts0[:, 1] / scale1[1]    \n    # second point\n    mkpts1[:, 0] = mkpts1[:, 0] / scale2[0]\n    mkpts1[:, 1] = mkpts1[:, 1] / scale2[1]\n    \n    return mkpts0, mkpts1\n\n\ndef match_superglue(img_fnames,\n                   index_pairs,\n                   feature_dir = '.featureout',\n                   device=torch.device('cpu'),\n                   min_matches=15, resize_to_ = (800)):    # (800, 600), (640, 480)\n    with h5py.File(f'{feature_dir}/matches_superglue.h5', mode='w') as f_match_superglue:\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            img11=load_image1(fname1)\n            img22=load_image1(fname2)\n\n            img1,scale1 = load_resized_image1(img11, resize_to_)\n            img2,scale2 = load_resized_image1(img22, resize_to_)\n            mkpts11,mkpts22=get_superglue(img1,img2)# \n            mkpts11,mkpts22=scale_to_resized(mkpts11, mkpts22, scale1,scale2)\n            mkpts1=mkpts11\n            mkpts2=mkpts22\n\n\n            n_matches = len(mkpts1)\n            group_superglue = f_match_superglue.require_group(key1)\n            if n_matches >= min_matches:\n                group_superglue.create_dataset(key2, data=np.concatenate([mkpts1, mkpts2], axis=1))\n            \n    kpts = defaultdict(list)\n    match_indexes = defaultdict(dict)\n    total_kpts=defaultdict(int)\n    with h5py.File(f'{feature_dir}/matches_superglue.h5', 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\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","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.448697Z","iopub.execute_input":"2023-05-24T01:19:12.449036Z","iopub.status.idle":"2023-05-24T01:19:12.511526Z","shell.execute_reply.started":"2023-05-24T01:19:12.449003Z","shell.execute_reply":"2023-05-24T01:19:12.510436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"src = '/kaggle/input/image-matching-challenge-2023'","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.51401Z","iopub.execute_input":"2023-05-24T01:19:12.514405Z","iopub.status.idle":"2023-05-24T01:19:12.524732Z","shell.execute_reply.started":"2023-05-24T01:19:12.514366Z","shell.execute_reply":"2023-05-24T01:19:12.52367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get data from csv.\n\ndata_dict = {}\nwith open(f'{src}/sample_submission.csv', 'r') as f:\n    for i, l in enumerate(f):\n        # Skip header.\n        if l and i > 0:\n            image, dataset, scene, _, _ = l.strip().split(',')\n            if dataset not in data_dict:\n                data_dict[dataset] = {}\n            if scene not in data_dict[dataset]:\n                data_dict[dataset][scene] = []\n            data_dict[dataset][scene].append(image)","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.527294Z","iopub.execute_input":"2023-05-24T01:19:12.528239Z","iopub.status.idle":"2023-05-24T01:19:12.54083Z","shell.execute_reply.started":"2023-05-24T01:19:12.528198Z","shell.execute_reply":"2023-05-24T01:19:12.539725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"这段代码从CSV文件中获取数据，并将其存储在data_dict字典中。","metadata":{}},{"cell_type":"code","source":"for dataset in data_dict:\n    for scene in data_dict[dataset]:\n        print(f'{dataset} / {scene} -> {len(data_dict[dataset][scene])} images')","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.542541Z","iopub.execute_input":"2023-05-24T01:19:12.542932Z","iopub.status.idle":"2023-05-24T01:19:12.549538Z","shell.execute_reply.started":"2023-05-24T01:19:12.542894Z","shell.execute_reply":"2023-05-24T01:19:12.54836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"该代码段用于遍历data_dict字典，打印每个数据集和场景中图像的数量。它会输出每个数据集和场景的名称以及对应的图像数量。这样可以对数据集和场景中的图像数量进行可视化和统计。","metadata":{}},{"cell_type":"code","source":"out_results = {}\ntimings = {\"shortlisting\":[],\n           \"feature_detection\": [],\n           \"feature_matching\":[],\n           \"RANSAC\": [],\n           \"Reconstruction\": []}","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.552808Z","iopub.execute_input":"2023-05-24T01:19:12.5536Z","iopub.status.idle":"2023-05-24T01:19:12.559057Z","shell.execute_reply.started":"2023-05-24T01:19:12.553562Z","shell.execute_reply":"2023-05-24T01:19:12.55775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"out_results是一个空的字典，用于存储输出结果。\n\ntimings是一个包含不同阶段时间统计的字典。它包含以下键：\n\n\"shortlisting\"：用于存储图像筛选阶段的时间。\n\"feature_detection\"：用于存储特征检测阶段的时间。\n\"feature_matching\"：用于存储特征匹配阶段的时间。\n\"RANSAC\"：用于存储RANSAC阶段的时间。\n\"Reconstruction\"：用于存储重建阶段的时间。\n这些键对应的值是空列表，用于存储每个阶段的时间统计。","metadata":{}},{"cell_type":"code","source":"# Function to create a submission file.\ndef create_submission(out_results, data_dict):\n    with open(f'submission.csv', 'w') as f:\n        f.write('image_path,dataset,scene,rotation_matrix,translation_vector\\n')\n        for dataset in data_dict:\n            if dataset in out_results:\n                res = out_results[dataset]\n            else:\n                res = {}\n            for scene in data_dict[dataset]:\n                if scene in res:\n                    scene_res = res[scene]\n                else:\n                    scene_res = {\"R\":{}, \"t\":{}}\n                for image in data_dict[dataset][scene]:\n                    if image in scene_res:\n                        print (image)\n                        R = scene_res[image]['R'].reshape(-1)\n                        T = scene_res[image]['t'].reshape(-1)\n                    else:\n                        R = np.eye(3).reshape(-1)\n                        T = np.zeros((3))\n                    f.write(f'{image},{dataset},{scene},{arr_to_str(R)},{arr_to_str(T)}\\n')","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.560803Z","iopub.execute_input":"2023-05-24T01:19:12.561607Z","iopub.status.idle":"2023-05-24T01:19:12.571869Z","shell.execute_reply.started":"2023-05-24T01:19:12.561569Z","shell.execute_reply":"2023-05-24T01:19:12.570832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()\ndatasets = []\nfor dataset in data_dict:\n    datasets.append(dataset)\n\nfor dataset in datasets:\n    print(dataset)\n    if dataset not in out_results:\n        out_results[dataset] = {}\n    for scene in data_dict[dataset]:\n        print(scene)\n        # Fail gently if the notebook has not been submitted and the test data is not populated.\n        # You may want to run this on the training data in that case?\n        img_dir = f'{src}/test/{dataset}/{scene}/images'\n        if not os.path.exists(img_dir):\n            continue\n        # Wrap the meaty part in a try-except block.\n        # try:\n        out_results[dataset][scene] = {}\n        img_fnames = [f'{src}/test/{x}' for x in data_dict[dataset][scene]]\n        print (f\"Got {len(img_fnames)} images\")\n        feature_dir = f'featureout/{dataset}_{scene}'\n        if not os.path.isdir(feature_dir):\n            os.makedirs(feature_dir, exist_ok=True)\n        t=time()\n        index_pairs = get_image_pairs_shortlist(img_fnames,\n                                sim_th = 0.6, # should be strict\n                                min_pairs =35, # we select at least min_pairs PER IMAGE with biggest similarity\n                                exhaustive_if_less = 20,\n                                device=device)\n        t=time() -t \n        timings['shortlisting'].append(t)\n        print (f'{len(index_pairs)}, pairs to match, {t:.4f} sec')\n        gc.collect()\n        t=time()\n\n        match_superglue(img_fnames, index_pairs, feature_dir=feature_dir, device=device, resize_to_=(920))   # (632, 832)\n        \n        t=time() -t \n        timings['feature_matching'].append(t)\n        print(f'Features matched in  {t:.4f} sec')\n        database_path = f'{feature_dir}/colmap.db'\n        if os.path.isfile(database_path):\n            os.remove(database_path)\n        gc.collect()\n        import_into_colmap(img_dir, feature_dir=feature_dir,database_path=database_path)\n        output_path = f'{feature_dir}/colmap_rec_{LOCAL_FEATURE}'\n\n        t=time()\n        pycolmap.match_exhaustive(database_path)\n        t=time() - t \n        timings['RANSAC'].append(t)\n        print(f'RANSAC in  {t:.4f} sec')\n\n        t=time()\n        # By default colmap does not generate a reconstruction if less than 10 images are registered. Lower it to 3.\n        mapper_options = pycolmap.IncrementalMapperOptions()\n        mapper_options.min_model_size = 3\n        os.makedirs(output_path, exist_ok=True)\n        maps = pycolmap.incremental_mapping(database_path=database_path, image_path=img_dir, output_path=output_path, options=mapper_options)\n        print(maps)\n        #clear_output(wait=False)\n        t=time() - t\n        timings['Reconstruction'].append(t)\n        print(f'Reconstruction done in  {t:.4f} sec')\n        imgs_registered  = 0\n        best_idx = None\n        print (\"Looking for the best reconstruction\")\n        if isinstance(maps, dict):\n            for idx1, rec in maps.items():\n                print (idx1, rec.summary())\n                if len(rec.images) > imgs_registered:\n                    imgs_registered = len(rec.images)\n                    best_idx = idx1\n        if best_idx is not None:\n            print (maps[best_idx].summary())\n            for k, im in maps[best_idx].images.items():\n                key1 = f'{dataset}/{scene}/images/{im.name}'\n                out_results[dataset][scene][key1] = {}\n                out_results[dataset][scene][key1][\"R\"] = deepcopy(im.rotmat())\n                out_results[dataset][scene][key1][\"t\"] = deepcopy(np.array(im.tvec))\n        print(f'Registered: {dataset} / {scene} -> {len(out_results[dataset][scene])} images')\n        print(f'Total: {dataset} / {scene} -> {len(data_dict[dataset][scene])} images')\n        create_submission(out_results, data_dict)\n        gc.collect()\n        # except:\n        #     pass","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.5734Z","iopub.execute_input":"2023-05-24T01:19:12.574122Z","iopub.status.idle":"2023-05-24T01:19:12.754585Z","shell.execute_reply.started":"2023-05-24T01:19:12.574084Z","shell.execute_reply":"2023-05-24T01:19:12.753395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_submission(out_results, data_dict)","metadata":{"execution":{"iopub.status.busy":"2023-05-24T01:19:12.756534Z","iopub.execute_input":"2023-05-24T01:19:12.757204Z","iopub.status.idle":"2023-05-24T01:19:12.764786Z","shell.execute_reply.started":"2023-05-24T01:19:12.757164Z","shell.execute_reply":"2023-05-24T01:19:12.763615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"create_submission函数用于创建提交文件，将out_results中的结果以CSV格式写入到submission.csv文件中。\n\n函数的输入参数包括out_results和data_dict。\n\nout_results是一个字典，包含了每个数据集和场景中的图像的旋转矩阵和平移向量信息。\n\ndata_dict是一个字典，包含了每个数据集和场景中的图像文件路径信息。\n\n函数会遍历data_dict中的每个数据集和场景，并在submission.csv文件中写入每个图像的信息，包括图像路径、数据集、场景、旋转矩阵和平移向量。\n\n函数的输出是一个submission.csv文件，其中包含了所有图像的信息，可以用于提交比赛结果。","metadata":{}}]}