{"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":"raw","source":"import torch\n#model_path = \"/kaggle/input/clip-match/clip_H_14_arc_withnewdata_val0.6456693_epoch4_256emb_s30m0.5.pt\"\nmodel_path = \"/kaggle/input/universalv5/BIG_DATA_EPOCH4_no_pool.pt\"\n","metadata":{"execution":{"iopub.status.busy":"2023-06-06T14:07:54.89379Z","iopub.execute_input":"2023-06-06T14:07:54.8941Z","iopub.status.idle":"2023-06-06T14:07:57.938799Z","shell.execute_reply.started":"2023-06-06T14:07:54.894067Z","shell.execute_reply":"2023-06-06T14:07:57.937889Z"}}},{"cell_type":"code","source":"!pip uninstall pycolmap -y","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:04:40.272562Z","iopub.execute_input":"2023-06-12T15:04:40.273490Z","iopub.status.idle":"2023-06-12T15:04:44.741923Z","shell.execute_reply.started":"2023-06-12T15:04:40.273452Z","shell.execute_reply":"2023-06-12T15:04:44.740413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install /kaggle/input/packages-match/pycolmap/pycolmap-0.4.0-cp37-cp37m-manylinux2014_x86_64.whl","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:04:44.745712Z","iopub.execute_input":"2023-06-12T15:04:44.746240Z","iopub.status.idle":"2023-06-12T15:05:19.042809Z","shell.execute_reply.started":"2023-06-12T15:04:44.746172Z","shell.execute_reply":"2023-06-12T15:05:19.041455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n#model_path = \"/kaggle/input/clip-match/clip_H_14_arc_withnewdata_val0.6456693_epoch4_256emb_s30m0.5.pt\"\nmodel_path = \"/kaggle/input/fork-of-multi-descriptors/vit_h_14_open.pt\"\nmodel_path = \"/kaggle/input/universalv5/BIG_DATA_EPOCH4_no_pool.pt\"","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.047376Z","iopub.execute_input":"2023-06-12T15:05:19.047759Z","iopub.status.idle":"2023-06-12T15:05:19.054711Z","shell.execute_reply.started":"2023-06-12T15:05:19.047721Z","shell.execute_reply":"2023-06-12T15:05:19.053317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport os\nimport csv\nimport random\nfrom glob import glob\nfrom tqdm import tqdm\nfrom collections import namedtuple\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport torch\n\nfrom os import listdir\n","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.061075Z","iopub.execute_input":"2023-06-12T15:05:19.061427Z","iopub.status.idle":"2023-06-12T15:05:19.070633Z","shell.execute_reply.started":"2023-06-12T15:05:19.061395Z","shell.execute_reply":"2023-06-12T15:05:19.069258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport cv2\nimport csv\nfrom glob import glob\nimport torch\nimport matplotlib.pyplot as plt\nimport kornia\n# from kornia_moons.feature import *\nimport kornia as K\nimport kornia.feature as KF\nimport gc","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.072645Z","iopub.execute_input":"2023-06-12T15:05:19.073700Z","iopub.status.idle":"2023-06-12T15:05:19.087178Z","shell.execute_reply.started":"2023-06-12T15:05:19.073654Z","shell.execute_reply":"2023-06-12T15:05:19.086058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.089349Z","iopub.execute_input":"2023-06-12T15:05:19.090326Z","iopub.status.idle":"2023-06-12T15:05:19.098830Z","shell.execute_reply.started":"2023-06-12T15:05:19.090254Z","shell.execute_reply":"2023-06-12T15:05:19.097438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-06-12T15:05:19.101193Z","iopub.execute_input":"2023-06-12T15:05:19.102093Z","iopub.status.idle":"2023-06-12T15:05:19.111920Z","shell.execute_reply.started":"2023-06-12T15:05:19.102049Z","shell.execute_reply":"2023-06-12T15:05:19.110730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Kornia version', K.__version__)\nprint('Pycolmap version', pycolmap.__version__)\n\nLOCAL_FEATURE = 'KeyNetAffNetHardNet'\nFLAG_LOFT = 0\ndevice=torch.device('cuda')\n# Can be LoFTR, KeyNetAffNetHardNet, or DISK","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.113963Z","iopub.execute_input":"2023-06-12T15:05:19.114908Z","iopub.status.idle":"2023-06-12T15:05:19.125464Z","shell.execute_reply.started":"2023-06-12T15:05:19.114863Z","shell.execute_reply":"2023-06-12T15:05:19.124060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def FlattenMatrix(M, num_digits=8):\n    '''Convenience function to write CSV files.'''\n    \n    return ' '.join([f'{v:.{num_digits}e}' for v in M.flatten()])\n\n\ndef load_torch_image(fname, device):\n    img = cv2.imread(fname)\n    scale = 840 / max(img.shape[0], img.shape[1]) \n    w = int(img.shape[1] * scale)\n    h = int(img.shape[0] * scale)\n    img = cv2.resize(img, (w, h))\n    img = K.image_to_tensor(img, False).float() /255.\n    img = K.color.bgr_to_rgb(img)\n    return img.to(device)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.127687Z","iopub.execute_input":"2023-06-12T15:05:19.128696Z","iopub.status.idle":"2023-06-12T15:05:19.139599Z","shell.execute_reply.started":"2023-06-12T15:05:19.128593Z","shell.execute_reply":"2023-06-12T15:05:19.138176Z"},"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-06-12T15:05:19.145580Z","iopub.execute_input":"2023-06-12T15:05:19.146444Z","iopub.status.idle":"2023-06-12T15:05:19.153971Z","shell.execute_reply.started":"2023-06-12T15:05:19.146403Z","shell.execute_reply":"2023-06-12T15:05:19.153050Z"},"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            with torch.cuda.amp.autocast():\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\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\n\ndef get_image_pairs_shortlist(fnames,\n                              sim_th = 0.6, # should be strict\n                              min_pairs = 30,\n                              exhaustive_if_less = 30,\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/pytorch/tf-efficientnet-b7/1/tf_efficientnet_b7_ra-6c08e654.pth')\n    #   model = timm.create_model('tf_efficientnet_b0', checkpoint_path='/kaggle/input/tf-efficientnet/pytorch/tf-efficientnet-b0/1/tf_efficientnet_b0_aa-827b6e33.pth')\n#     with open(model_path, 'rb') as opened_file:\n#         model = torch.jit.load(opened_file, map_location=\"cuda\").eval()\n#     model=timm.create_model('swin_large_patch4_window12_384_in22k',checkpoint_path = '/kaggle/input/load-clip/swin_large_patch4_window12_384_22k.pth')\n#     model=timm.create_model('convnext_xlarge_in22k',checkpoint_path='/kaggle/input/fork-of-multi-descriptors/convnext_xlarge_22k_224.pth')\n    #model = timm.create_model('tf_efficientnet_b4', checkpoint_path='/kaggle/input/tf-efficientnet/pytorch/tf-efficientnet-b4/1/tf_efficientnet_b4_aa-818f208c.pth')\n    descs = get_global_desc(fnames, model, device=device)\n    cos_sim = torch.mm(descs, descs.t())\n\n    # Convert cosine similarity to cosine distance\n    dm = 1 - cos_sim\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\n","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.156016Z","iopub.execute_input":"2023-06-12T15:05:19.156886Z","iopub.status.idle":"2023-06-12T15:05:19.181939Z","shell.execute_reply.started":"2023-06-12T15:05:19.156829Z","shell.execute_reply":"2023-06-12T15:05:19.180639Z"},"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  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\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),\n                              qvec=np.array([1.0, 0.0, 0.0, 0.0]),\n                              tvec=np.zeros(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        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,) + matches.shape + (array_to_blob(matches), config,\n                                          array_to_blob(F), array_to_blob(E), array_to_blob(H),\n                                          array_to_blob(qvec), array_to_blob(tvec)))","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.184331Z","iopub.execute_input":"2023-06-12T15:05:19.185301Z","iopub.status.idle":"2023-06-12T15:05:19.229278Z","shell.execute_reply.started":"2023-06-12T15:05:19.185257Z","shell.execute_reply":"2023-06-12T15:05:19.227830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def add_two_view_geometries(db, h5_path, fname_to_id, pp, focal):\n    match_file = h5py.File(os.path.join(h5_path, 'matches.h5'), 'r')\n    keypoints_file = h5py.File(os.path.join(h5_path, 'keypoints.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\n                keypoints1 = keypoints_file[key_1][()]\n                keypoints2 = keypoints_file[key_2][()]\n\n                points1 = keypoints1[matches[:, 0]] #- pp[key_1]) / focal\n                points2 = keypoints2[matches[:, 1]] #- pp[key_2]) / focal\n\n                F, mask = cv2.findFundamentalMat(points1, points2,\n                                            ransacReprojThreshold=3, method=cv2.USAC_MAGSAC,\n                                            confidence=0.9999, maxIters=100000)\n                #F, mask = pydegensac.findFundamentalMatrix(points1, points2, 3)\n\n\n\n\n                E=np.eye(3)\n                #F=np.eye(3)\n                H = np.eye(3)\n                #E, mask = cv2.findEssentialMat(points1, points2,method=cv2.USAC_MAGSAC, prob=0.999, threshold=0.58, maxIters=100000)\n                #H, mask = cv2.findHomography(points1, points2, cv2.USAC_MAGSAC, 4)\n                matches_inliers = np.array(matches)[mask.ravel() == 1]\n                config = 2\n                qvec = np.array([1.0, 0.0, 0.0, 0.0]),\n                tvec = np.zeros(3)\n                db.add_two_view_geometry(id_1, id_2, matches_inliers, F, E, H,qvec,tvec,config)\n\n                added.add(pair_id)\n\n                pbar.update(1)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.231431Z","iopub.execute_input":"2023-06-12T15:05:19.232267Z","iopub.status.idle":"2023-06-12T15:05:19.250641Z","shell.execute_reply.started":"2023-06-12T15:05:19.232110Z","shell.execute_reply":"2023-06-12T15:05:19.249531Z"},"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\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),(width / 2, height / 2),focal\n\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    pp = {}\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            camera_id, pri_point, focal = 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,pp, focal\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)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.252619Z","iopub.execute_input":"2023-06-12T15:05:19.253478Z","iopub.status.idle":"2023-06-12T15:05:19.282938Z","shell.execute_reply.started":"2023-06-12T15:05:19.253433Z","shell.execute_reply":"2023-06-12T15:05:19.281650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import kornia.core as KFC","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.286374Z","iopub.execute_input":"2023-06-12T15:05:19.286802Z","iopub.status.idle":"2023-06-12T15:05:19.298947Z","shell.execute_reply.started":"2023-06-12T15:05:19.286759Z","shell.execute_reply":"2023-06-12T15:05:19.297649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from typing import Optional, Tuple\nfrom kornia.core import Device, Module, Tensor, concatenate\nfrom kornia.feature import LAFAffNetShapeEstimator\nfrom kornia.feature import HardNet\nfrom kornia.feature import KeyNetDetector\nfrom kornia.feature import extract_patches_from_pyramid, get_laf_center, scale_laf\nfrom kornia.feature import LAFOrienter, OriNet, PassLAF\nfrom kornia.feature import BlobDoG, BlobDoGSingle, BlobHessian, CornerGFTT\nfrom kornia.feature.scale_space_detector import (\n    Detector_config,\n    MultiResolutionDetector,\n    ScaleSpaceDetector,\n    get_default_detector_config,\n)\nfrom kornia.geometry.subpix import ConvQuadInterp3d\nfrom kornia.geometry.transform import ScalePyramid\nclass ExtendedLocalFeature(KF.LocalFeature):\n    def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:\n        ori_module =  LAFOrienter(angle_detector=OriNet(False)).eval()\n        weights = torch.load('/kaggle/input/kornia-local-feature-weights/OriNet.pth')['state_dict']\n        ori_module.angle_detector.load_state_dict(weights)\n#         detector_dog = ScaleSpaceDetector(\n#             8000,\n#             resp_module=BlobDoG(),\n#             nms_module=ConvQuadInterp3d(10),\n#             scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),\n#             ori_module=LAFOrienter(19)\n#             scale_space_response=True,\n#             minima_are_also_good=True,\n#             mr_size=6.0,\n#         ).to('cuda')\n        affnet_weights = torch.load('/kaggle/input/kornia-local-feature-weights/AffNet.pth')['state_dict']\n        detector_dog = MultiResolutionDetector(\n            CornerGFTT(),\n            8000,\n            get_default_detector_config(),\n            ori_module=LAFOrienter(19),\n            aff_module=LAFAffNetShapeEstimator(False).eval(),\n        ).to('cuda')\n        detector_dog.aff.load_state_dict(affnet_weights)\n        lafs, responses = self.detector(img, mask)\n        lafs_keynet = scale_laf(lafs, self.scaling_coef)\n        lafs, responses = detector_dog(img, mask)\n        lafs_dog = scale_laf(lafs, self.scaling_coef)\n        lafs_final = torch.cat((lafs_keynet,lafs_dog),1)\n        descs = self.descriptor[0](img, lafs_final)\n        descs2 = self.descriptor[2](img, lafs_final)\n        descs = descs+descs2#torch.cat((descs,descs2),1)#descs+descs2\n        return (lafs_final, responses, descs)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.301141Z","iopub.execute_input":"2023-06-12T15:05:19.301901Z","iopub.status.idle":"2023-06-12T15:05:19.319715Z","shell.execute_reply.started":"2023-06-12T15:05:19.301857Z","shell.execute_reply":"2023-06-12T15:05:19.318465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Making kornia local features loading w/o internet\nclass KeyNetAffNetHardNet(ExtendedLocalFeature):\n    \"\"\"Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor.\n\n    .. image:: _static/img/keynet_affnet.jpg\n    \"\"\"\n\n    def __init__(\n        self,\n        num_features: int = 5000,\n        upright: bool = False,\n        device = torch.device('cpu'),\n        scale_laf: float = 1.0,\n    ):\n        ori_module = KF.PassLAF() if upright else KF.LAFOrienter(angle_detector=KF.OriNet(False)).eval()\n        if not upright:\n            weights = torch.load('/kaggle/input/kornia-local-feature-weights/OriNet.pth')['state_dict']\n            ori_module.angle_detector.load_state_dict(weights)\n        detector = KF.KeyNetDetector(\n            False, num_features=num_features, ori_module=ori_module, aff_module=KF.LAFAffNetShapeEstimator(False).eval()\n        ).to(device)\n        kn_weights = torch.load('/kaggle/input/kornia-local-feature-weights/keynet_pytorch.pth')['state_dict']\n        detector.model.load_state_dict(kn_weights)\n        affnet_weights = torch.load('/kaggle/input/kornia-local-feature-weights/AffNet.pth')['state_dict']\n        detector.aff.load_state_dict(affnet_weights)\n        \n        hardnet = KF.HardNet(False).eval()\n        hn_weights = torch.load('/kaggle/input/kornia-local-feature-weights/HardNetLib.pth')['state_dict']\n        hardnet.load_state_dict(hn_weights)\n        descriptor = KF.LAFDescriptor(hardnet, patch_size=32, grayscale_descriptor=True).to(device)\n        sosnet32 = KF.SOSNet(False).eval()\n        sos_weights = torch.load('/kaggle/input/kornia-local-feature-weights/sosnet_32x32_liberty.pth')\n        sosnet32.load_state_dict(sos_weights)\n        descriptor2=KF.LAFDescriptor(sosnet32, patch_size=32, grayscale_descriptor=True).to(device)\n        descriptor3 = KF.LAFDescriptor(\n            KF.SIFTDescriptor(patch_size=41, rootsift=True), patch_size=41, grayscale_descriptor=True\n        ).to(device)\n        descriptor= [descriptor,descriptor2,descriptor3]\n\n        super().__init__(detector, descriptor, scale_laf)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.322077Z","iopub.execute_input":"2023-06-12T15:05:19.323298Z","iopub.status.idle":"2023-06-12T15:05:19.339733Z","shell.execute_reply.started":"2023-06-12T15:05:19.323209Z","shell.execute_reply":"2023-06-12T15:05:19.338569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def detect_features(img_fnames,\n                    num_feats = 2048,\n                    upright = False,\n                    device=torch.device('cpu'),\n                    feature_dir = '.featureout',\n                    resize_small_edge_to = 600):\n    if LOCAL_FEATURE == 'DISK':\n        # Load DISK from Kaggle models so it can run when the notebook is offline.\n        disk = KF.DISK().to(device)\n        pretrained_dict = torch.load('/kaggle/input/matching/disk_epi.pt', map_location=device)\n        disk.load_state_dict(pretrained_dict['extractor'])\n        disk.eval()\n    if LOCAL_FEATURE == 'KeyNetAffNetHardNet':\n        feature = KeyNetAffNetHardNet(num_feats, upright, device).to(device).eval()\n    if not os.path.isdir(feature_dir):\n        os.makedirs(feature_dir)\n    with h5py.File(f'{feature_dir}/lafs.h5', mode='w') as f_laf, \\\n         h5py.File(f'{feature_dir}/keypoints.h5', mode='w') as f_kp, \\\n         h5py.File(f'{feature_dir}/descriptors.h5', mode='w') as f_desc:\n        for img_path in progress_bar(img_fnames):\n            img_fname = img_path.split('/')[-1]\n            key = img_fname\n            with torch.inference_mode():\n                timg = load_torch_image(img_path, device=device)\n                H, W = timg.shape[2:]\n                if resize_small_edge_to is None:\n                    timg_resized = timg\n                else:\n                    timg_resized = K.geometry.resize(timg, resize_small_edge_to, antialias=True)\n                    print(f'Resized {timg.shape} to {timg_resized.shape} (resize_small_edge_to={resize_small_edge_to})')\n                h, w = timg_resized.shape[2:]\n                if LOCAL_FEATURE == 'DISK':\n                    features = disk(timg_resized, num_feats, pad_if_not_divisible=True)[0]\n                    kps1, descs = features.keypoints, features.descriptors\n                    \n                    lafs = KF.laf_from_center_scale_ori(kps1[None], torch.ones(1, len(kps1), 1, 1, device=device))\n                if LOCAL_FEATURE == 'KeyNetAffNetHardNet':\n                    lafs, resps, descs = feature(K.color.rgb_to_grayscale(timg_resized))\n                lafs[:,:,0,:] *= float(W) / float(w)\n                lafs[:,:,1,:] *= float(H) / float(h)\n                desc_dim = descs.shape[-1]\n                kpts = KF.get_laf_center(lafs).reshape(-1, 2).detach().cpu().numpy()\n                descs = descs.reshape(-1, desc_dim).detach().cpu().numpy()\n                f_laf[key] = lafs.detach().cpu().numpy()\n                f_kp[key] = kpts\n                f_desc[key] = descs\n    return\n\ndef 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\ndef match_features(img_fnames,\n                   index_pairs,\n                   feature_dir = '.featureout',\n                   device=torch.device('cpu'),\n                   min_matches=15, \n                   force_mutual = True,\n                   matching_alg='adalam'\n                  ):\n    assert matching_alg in ['smnn', 'adalam']\n    def preload_images(fnames):\n        imgs = []\n        for fname in fnames:\n            img = cv2.imread(fname)\n            imgs.append(img)\n        return imgs\n    # preload all images\n    imgs = preload_images(img_fnames)\n    with h5py.File(f'{feature_dir}/lafs.h5', mode='r') as f_laf, \\\n         h5py.File(f'{feature_dir}/descriptors.h5', mode='r') as f_desc, \\\n        h5py.File(f'{feature_dir}/matches.h5', mode='w') as f_match:\n\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                    lafs1 = torch.from_numpy(f_laf[key1][...]).to(device)\n                    lafs2 = torch.from_numpy(f_laf[key2][...]).to(device)\n                    desc1 = torch.from_numpy(f_desc[key1][...]).to(device)\n                    desc2 = torch.from_numpy(f_desc[key2][...]).to(device)\n                    if matching_alg == 'adalam':\n                        img1, img2 = imgs[idx1], imgs[idx2]\n                        #img1, img2 = cv2.imread(fname1), cv2.imread(fname2)\n                        hw1, hw2 = img1.shape[:2], img2.shape[:2]\n                        adalam_config = KF.adalam.get_adalam_default_config()\n                        #adalam_config['orientation_difference_threshold'] = None\n                        #adalam_config['scale_rate_threshold'] = None\n                        adalam_config['force_seed_mnn']= False\n                        adalam_config['search_expansion'] = 16\n                        adalam_config['ransac_iters'] = 128\n                        adalam_config['device'] = device\n                        adalam_config['min_confidence'] = 200\n                        dists, idxs = KF.match_adalam(desc1, desc2,\n                                                      lafs1, lafs2, # Adalam takes into account also geometric information\n                                                      hw1=hw1, hw2=hw2,\n                                                      config=adalam_config) # Adalam also benefits from knowing image size\n                    else:\n                        dists, idxs = KF.match_smnn(desc1, desc2, 0.98)\n                    if len(idxs)  == 0:\n                        continue\n                    # Force mutual nearest neighbors\n                    if force_mutual:\n                        first_indices = get_unique_idxs(idxs[:,1])\n                        idxs = idxs[first_indices]\n                        dists = dists[first_indices]\n                    n_matches = len(idxs)\n                    if False:\n                        print (f'{key1}-{key2}: {n_matches} matches')\n                    group  = f_match.require_group(key1)\n                    if n_matches >= min_matches:\n                         group.create_dataset(key2, data=idxs.detach().cpu().numpy().reshape(-1, 2))\n    return\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,pp,focal = 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    add_two_view_geometries(db,feature_dir, fname_to_id,pp,focal)\n\n    db.commit()\n    return","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.341547Z","iopub.execute_input":"2023-06-12T15:05:19.342198Z","iopub.status.idle":"2023-06-12T15:05:19.386301Z","shell.execute_reply.started":"2023-06-12T15:05:19.342154Z","shell.execute_reply":"2023-06-12T15:05:19.385048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"src = '/kaggle/input/image-matching-challenge-2023'","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.388030Z","iopub.execute_input":"2023-06-12T15:05:19.388604Z","iopub.status.idle":"2023-06-12T15:05:19.401668Z","shell.execute_reply.started":"2023-06-12T15:05:19.388561Z","shell.execute_reply":"2023-06-12T15:05:19.400595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Get data from csv.\n\n# data_dict = {}\n# with open(f'{src}/train/train_labels.csv', 'r') as f:\n#     for i, l in enumerate(f):\n#         # Skip header.\n#         if l and i > 0:\n#             dataset, scene,image, _, _ = 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-06-12T15:05:19.403830Z","iopub.execute_input":"2023-06-12T15:05:19.404357Z","iopub.status.idle":"2023-06-12T15:05:19.418317Z","shell.execute_reply.started":"2023-06-12T15:05:19.404315Z","shell.execute_reply":"2023-06-12T15:05:19.417044Z"},"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-06-12T15:05:19.421589Z","iopub.execute_input":"2023-06-12T15:05:19.422452Z","iopub.status.idle":"2023-06-12T15:05:19.427868Z","shell.execute_reply.started":"2023-06-12T15:05:19.422411Z","shell.execute_reply":"2023-06-12T15:05:19.426985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-06-12T15:05:19.429986Z","iopub.execute_input":"2023-06-12T15:05:19.431045Z","iopub.status.idle":"2023-06-12T15:05:19.439680Z","shell.execute_reply.started":"2023-06-12T15:05:19.430999Z","shell.execute_reply":"2023-06-12T15:05:19.438386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"out_results = {}\ntimings = {\"shortlisting\":[],\n           \"feature_detection\": [],\n           \"feature_matching\":[],\n           \"RANSAC\": [],\n           \"Reconstruction\": []}","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.442492Z","iopub.execute_input":"2023-06-12T15:05:19.443513Z","iopub.status.idle":"2023-06-12T15:05:19.450115Z","shell.execute_reply.started":"2023-06-12T15:05:19.443319Z","shell.execute_reply":"2023-06-12T15:05:19.448826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to create a submission file.\n# def 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#                     if len(R)<9:\n#                         R = np.eye(3).reshape(-1)\n#                     if len(T)<3:\n#                         T = np.zeros((3))\n                        \n#                     f.write(f'{image},{dataset},{scene},{arr_to_str(R)},{arr_to_str(T)}\\n')\n\n\n# def create_submission(out_results, data_dict):\n#     # Initialize an empty DataFrame with the required columns\n#     submission = pd.DataFrame(columns=['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#                     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\n#                 if len(R) < 9:\n#                     R = np.eye(3).reshape(-1)\n#                 if len(T) < 3:\n#                     T = np.zeros((3))\n\n#                 # Append a new row to the submission DataFrame\n#                 submission = submission.append({\n#                     'image_path': image,\n#                     'dataset': dataset,\n#                     'scene': scene,\n#                     'rotation_matrix': arr_to_str(R),\n#                     'translation_vector': arr_to_str(T)\n#                 }, ignore_index=True)\n    \n#     # Save the submission DataFrame to a CSV file\n#     submission.to_csv('submission.csv', index=False)\n\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-06-12T15:05:19.452990Z","iopub.execute_input":"2023-06-12T15:05:19.453813Z","iopub.status.idle":"2023-06-12T15:05:19.469471Z","shell.execute_reply.started":"2023-06-12T15:05:19.453772Z","shell.execute_reply":"2023-06-12T15:05:19.468141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dict","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.473092Z","iopub.execute_input":"2023-06-12T15:05:19.473730Z","iopub.status.idle":"2023-06-12T15:05:19.492576Z","shell.execute_reply.started":"2023-06-12T15:05:19.473698Z","shell.execute_reply":"2023-06-12T15:05:19.491467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(2):\n    print(i)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.494714Z","iopub.execute_input":"2023-06-12T15:05:19.495111Z","iopub.status.idle":"2023-06-12T15:05:19.503966Z","shell.execute_reply.started":"2023-06-12T15:05:19.495072Z","shell.execute_reply":"2023-06-12T15:05:19.502520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\nnum_errors=0\nloop = 1\ngc.collect()\ndatasets = []\nfor dataset in data_dict:\n    datasets.append(dataset)\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        loop = 1\n        recs=[]\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\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        if len(data_dict[dataset])<2 and len(img_fnames)<50:\n            loop = 2\n        for i in range(loop):\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.5, # should be strict\n                                  min_pairs = 60, # we select at least min_pairs PER IMAGE with biggest similarity\n                                  exhaustive_if_less = 60,\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            detect_features(img_fnames,\n                                15000,\n                                feature_dir=feature_dir,\n                                upright=False,\n                                device=device,\n                                resize_small_edge_to=1200)\n            gc.collect()\n            t = time() - t\n            timings['feature_detection'].append(t)\n            print(f'Features detected in  {t:.4f} sec')\n            t = time()\n            match_features(img_fnames, index_pairs, feature_dir=feature_dir, device=device)\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    #         ransac_options = pycolmap.SiftMatchingOptions(\n    #             max_num_trials=200000,\n    #         )\n            #pycolmap.match_exhaustive(database_path)#,sift_options=ransac_options)\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    #         if len(img_fnames) < 60:\n    #             mapper_options.ba_global_images_ratio = 1.001\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            recs.append(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        temp_idx = None\n        best_idx = None\n        best_rec_idx = None\n        best_rec = []\n        best_reproj = 100000000\n        temp = 0\n        for count,maps in enumerate(recs):\n            imgs_registered  = 0\n            print (\"Looking for the best reconstruction\")\n            if isinstance(maps, dict):\n                imgs_registered  = 0\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                        temp_idx=idx1\n                best_rec.append(imgs_registered)\n            if best_rec[count] >= temp and maps[temp_idx].compute_mean_reprojection_error()<best_reproj:\n                temp=best_rec[count]\n                best_rec_idx = count\n                best_idx = temp_idx\n                best_reproj = maps[best_idx].compute_mean_reprojection_error()\n        if best_idx is not None:\n            print (recs[best_rec_idx][best_idx].summary())\n            for k, im in recs[best_rec_idx][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        gc.collect()\n    #         except:m\n    #             num_errors+=1\n    #             pass\n\n","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:05:19.506580Z","iopub.execute_input":"2023-06-12T15:05:19.507075Z","iopub.status.idle":"2023-06-12T15:09:41.676452Z","shell.execute_reply.started":"2023-06-12T15:05:19.507031Z","shell.execute_reply":"2023-06-12T15:09:41.673584Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:09:41.677782Z","iopub.status.idle":"2023-06-12T15:09:41.679703Z","shell.execute_reply.started":"2023-06-12T15:09:41.679387Z","shell.execute_reply":"2023-06-12T15:09:41.679427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# if num_errors>0:\n#     raise Exception(\"I know Python!\")","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:09:41.681468Z","iopub.status.idle":"2023-06-12T15:09:41.682462Z","shell.execute_reply.started":"2023-06-12T15:09:41.682129Z","shell.execute_reply":"2023-06-12T15:09:41.682161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Function to create a submission file.\n# def 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#             res = {}\n#             for scene in data_dict[dataset]:\n#                 scene_res = {\"R\":{}, \"t\":{}}\n#                 for image in data_dict[dataset][scene]:\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-06-12T15:09:41.684290Z","iopub.status.idle":"2023-06-12T15:09:41.685233Z","shell.execute_reply.started":"2023-06-12T15:09:41.684936Z","shell.execute_reply":"2023-06-12T15:09:41.684977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_submission(out_results, data_dict)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:09:41.689892Z","iopub.status.idle":"2023-06-12T15:09:41.690912Z","shell.execute_reply.started":"2023-06-12T15:09:41.690593Z","shell.execute_reply":"2023-06-12T15:09:41.690623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"recs","metadata":{"execution":{"iopub.status.busy":"2023-06-12T15:09:41.692272Z","iopub.status.idle":"2023-06-12T15:09:41.699372Z","shell.execute_reply.started":"2023-06-12T15:09:41.699004Z","shell.execute_reply":"2023-06-12T15:09:41.699047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}