{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":71885,"databundleVersionId":8143495,"sourceType":"competition"},{"sourceId":7884485,"sourceType":"datasetVersion","datasetId":4628051},{"sourceId":7884725,"sourceType":"datasetVersion","datasetId":4628331},{"sourceId":4534,"sourceType":"modelInstanceVersion","modelInstanceId":3326},{"sourceId":17191,"sourceType":"modelInstanceVersion","modelInstanceId":14317},{"sourceId":17555,"sourceType":"modelInstanceVersion","modelInstanceId":14611}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input/imc2024-packages-lightglue-rerun-kornia'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\n\n!pip install --no-index /kaggle/input/imc2024-packages-lightglue-rerun-kornia/* --no-deps\n!mkdir -p /root/.cache/torch/hub/checkpoints\n!cp /kaggle/input/aliked/pytorch/aliked-n16/1/* /root/.cache/torch/hub/checkpoints/\n!cp /kaggle/input/lightglue/pytorch/aliked/1/* /root/.cache/torch/hub/checkpoints/\n!cp /kaggle/input/lightglue/pytorch/aliked/1/aliked_lightglue.pth /root/.cache/torch/hub/checkpoints/aliked_lightglue_v0-1_arxiv-pth\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-08T02:28:19.970209Z","iopub.execute_input":"2024-04-08T02:28:19.970505Z","iopub.status.idle":"2024-04-08T02:28:32.169214Z","shell.execute_reply.started":"2024-04-08T02:28:19.970479Z","shell.execute_reply":"2024-04-08T02:28:32.167807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# General utilities\nimport matplotlib.pyplot as plt\n\nimport os\nfrom tqdm import tqdm\nfrom pathlib import Path  # 提供面向对象的文件系统路径操作\nfrom time import time, sleep\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/MLe\nimport cv2\nimport torch\nimport torch.nn.functional as F\nimport kornia as K\nimport kornia.feature as KF\nfrom PIL import Image\nfrom transformers import AutoImageProcessor, AutoModel\n\n# 3D reconstruction\nimport pycolmap\n\n# Data importing into colmap\nimport sys\nsys.path.append('/kaggle/input/colmap-db-import')\nfrom database import *\nfrom h5_to_db import *\n\n\n\ndef 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.io.load_image(fname, K.io.ImageLoadType.RGB32, device=device)[None, ...]\n    return img\n\ndevice = K.utils.get_cuda_device_if_available(0)\nprint (device)\n#output 0 means no gpu","metadata":{"execution":{"iopub.status.busy":"2024-04-08T03:56:23.179365Z","iopub.execute_input":"2024-04-08T03:56:23.179759Z","iopub.status.idle":"2024-04-08T03:56:23.190791Z","shell.execute_reply.started":"2024-04-08T03:56:23.179733Z","shell.execute_reply":"2024-04-08T03:56:23.189767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Using DINOv2 to Find image pairs","metadata":{}},{"cell_type":"code","source":"# We will use efficientnet global descriptor to get matching shortlists.\ndef get_global_desc(fnames, device = torch.device('cpu')):\n    processor = AutoImageProcessor.from_pretrained('/kaggle/input/dinov2/pytorch/base/1')\n    model = AutoModel.from_pretrained('/kaggle/input/dinov2/pytorch/base/1')\n    model = model.eval()\n    model = model.to(device)\n    global_descs_dinov2 = []\n    for i, img_fname_full in tqdm(enumerate(fnames),total= len(fnames)):\n        key = os.path.splitext(os.path.basename(img_fname_full))[0]\n        timg = load_torch_image(img_fname_full)\n        with torch.inference_mode():\n            inputs = processor(images=timg, return_tensors=\"pt\", do_rescale=False).to(device)\n            outputs = model(**inputs)\n            dino_mac = F.normalize(outputs.last_hidden_state[:,1:].max(dim=1)[0], dim=1, p=2)\n        global_descs_dinov2.append(dino_mac.detach().cpu())\n    global_descs_dinov2 = torch.cat(global_descs_dinov2, dim=0)\n    return global_descs_dinov2\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 = 20,\n                              exhaustive_if_less = 20,\n                              device=torch.device('cpu')):\n    num_imgs = len(fnames)\n    if num_imgs <= exhaustive_if_less:\n        return get_img_pairs_exhaustive(fnames)\n    descs = get_global_desc(fnames, 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":"2024-04-08T02:29:14.549506Z","iopub.execute_input":"2024-04-08T02:29:14.550194Z","iopub.status.idle":"2024-04-08T02:29:14.565939Z","shell.execute_reply.started":"2024-04-08T02:29:14.550147Z","shell.execute_reply":"2024-04-08T02:29:14.564891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 如果DEBUG变量为True，则执行以下代码块。这通常用于开发过程中的测试或调试，\n# 以确保只在DEBUG模式下执行某些代码。\n\nimages_list = list(Path(\"/kaggle/input/image-matching-challenge-2024/test/church/images/\").glob(\"*.png\"))[:10]\n# 使用Path对象从指定目录中获取所有PNG图片文件，并将结果转换为列表。\n# 这里使用了glob模式匹配功能，\"*.png\"表示匹配所有以.png结尾的文件。\n# [:10]表示从匹配到的文件列表中取前10个文件，用于减少处理时间，使调试过程更高效。\n\nindex_pairs = get_image_pairs_shortlist(images_list, \"/kaggle/input/dinov2/pytorch/base/1\")\n# 调用get_image_pairs函数，传入图片列表和模型路径。\n# 这个函数旨在找出相似的图片对。模型路径\"/kaggle/input/dinov2/pytorch/base/1\"用于加载预训练的模型，\n# 以计算图片的嵌入向量并基于这些嵌入向量找出相似的图片对。\n\nprint(index_pairs)\n# 打印找到的相似图片对的索引。这对于验证get_image_pairs函数的正确性和效果是有帮助的，\n# 可以让开发者了解哪些图片被算法识别为相似，从而进行调优或修正。","metadata":{"execution":{"iopub.status.busy":"2024-04-08T03:56:49.210315Z","iopub.execute_input":"2024-04-08T03:56:49.210782Z","iopub.status.idle":"2024-04-08T03:56:49.219069Z","shell.execute_reply.started":"2024-04-08T03:56:49.210754Z","shell.execute_reply":"2024-04-08T03:56:49.218049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Using ALIKED to Computing Keypoints ","metadata":{}},{"cell_type":"code","source":"import torch\nfrom lightglue import match_pair\nfrom lightglue import ALIKED, LightGlue\nfrom lightglue.utils import load_image, rbd\n\n\ndef detect_aliked(img_fnames,\n                  feature_dir = '.featureout',\n                  num_features = 4096,\n                  resize_to = 1024,\n                  device=torch.device('cpu')):\n    dtype = torch.float32 # ALIKED has issues with float16\n    extractor = ALIKED(max_num_keypoints=num_features, detection_threshold=0.01, resize=resize_to).eval().to(device, dtype)\n    if not os.path.isdir(feature_dir):\n        os.makedirs(feature_dir)\n    with 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 tqdm(img_fnames):\n            img_fname = img_path.split('/')[-1]\n            key = img_fname\n            with torch.inference_mode():\n                image0 = load_torch_image(img_path, device=device).to(dtype)\n                feats0 = extractor.extract(image0)  # auto-resize the image, disable with resize=None\n                kpts = feats0['keypoints'].reshape(-1, 2).detach().cpu().numpy()\n                descs = feats0['descriptors'].reshape(len(kpts), -1).detach().cpu().numpy()\n                f_kp[key] = kpts\n                f_desc[key] = descs\n    return\ndef match_with_lightglue(img_fnames,\n                   index_pairs,\n                   feature_dir = '.featureout',\n                   device=torch.device('cpu'),\n                   min_matches=15,verbose=True):\n    lg_matcher = KF.LightGlueMatcher(\"aliked\", {\"width_confidence\": -1,\n                                                \"depth_confidence\": -1,\n                                                 \"mp\": True if 'cuda' in str(device) else False}).eval().to(device)\n    with h5py.File(f'{feature_dir}/keypoints.h5', mode='r') as f_kp, \\\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        for pair_idx in tqdm(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            kp1 = torch.from_numpy(f_kp[key1][...]).to(device)\n            kp2 = torch.from_numpy(f_kp[key2][...]).to(device)\n            desc1 = torch.from_numpy(f_desc[key1][...]).to(device)\n            desc2 = torch.from_numpy(f_desc[key2][...]).to(device)\n            with torch.inference_mode():\n                dists, idxs = lg_matcher(desc1,\n                                         desc2,\n                                         KF.laf_from_center_scale_ori(kp1[None]),\n                                         KF.laf_from_center_scale_ori(kp2[None]))\n            if len(idxs)  == 0:\n                continue\n            n_matches = len(idxs)\n            if verbose:\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\ndef import_into_colmap(img_dir,\n                       feature_dir ='.featureout',\n                       database_path = 'colmap.db'):\n    db = COLMAPDatabase.connect(database_path)\n    db.create_tables()\n    single_camera = False\n    fname_to_id = add_keypoints(db, feature_dir, img_dir, '', 'simple-pinhole', single_camera)\n    add_matches(\n        db,\n        feature_dir,\n        fname_to_id,\n    )\n    db.commit()\n    return","metadata":{"execution":{"iopub.status.busy":"2024-04-08T02:29:17.197686Z","iopub.execute_input":"2024-04-08T02:29:17.198311Z","iopub.status.idle":"2024-04-08T02:29:17.470225Z","shell.execute_reply.started":"2024-04-08T02:29:17.198276Z","shell.execute_reply":"2024-04-08T02:29:17.469420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dtype = torch.float32  # 设置数据类型为float32。ALIKED可能与float16有兼容性问题，因此这里明确使用float32。\n    \nextractor = ALIKED(\n        max_num_keypoints=4096,  # 设置最大关键点数量为4096。\n        detection_threshold=0.01,  # 设置检测阈值为0.01，这个阈值用于关键点检测算法中。\n        resize=1024  # 设置图像大小调整为1024，以统一输入图像的尺寸。\n    ).eval().to(device, dtype)  # 将模型设置为评估模式，并移动到指定的设备和数据类型上。\n\npath = images_list[0]  # 从图片列表中取出第一张图片的路径。\nimage = load_torch_image(path, device=device).to(dtype)  # 加载图片，并转换到指定的设备和数据类型。\nfeatures = extractor.extract(image)  # 使用提取器提取图片的特征。\n\nfig, ax = plt.subplots(1, 2, figsize=(10, 20))  # 创建一个画布和两个子图，设置画布大小为10x20。\nax[0].imshow(image[0, ...].permute(1,2,0).cpu())  # 在第一个子图上显示原图。图片数据需要从CHW格式转换为HWC格式，并移动到CPU上。\nax[1].imshow(image[0, ...].permute(1,2,0).cpu())  # 在第二个子图上也显示原图。\nax[1].scatter(features[\"keypoints\"][0, :, 0].cpu(), features[\"keypoints\"][0, :, 1].cpu(), s=0.5, c=\"red\")  # 在第二个子图上绘制提取的关键点。关键点以红色小点的形式显示。\n\ndel extractor  # 删除特征提取器对象，这有助于释放可能占用的资源。","metadata":{"execution":{"iopub.status.busy":"2024-04-08T04:08:44.527930Z","iopub.execute_input":"2024-04-08T04:08:44.528287Z","iopub.status.idle":"2024-04-08T04:08:45.552625Z","shell.execute_reply.started":"2024-04-08T04:08:44.528260Z","shell.execute_reply":"2024-04-08T04:08:45.551737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"src = '/kaggle/input/image-matching-challenge-2024/'\n# 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        if i== 0:\n            print (l)\n        # Skip header.\n        if l and i > 0:\n            image_path, 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_path)\nfor dataset in data_dict:\n    for scene in data_dict[dataset]:\n        print(f'{dataset} / {scene} -> {len(data_dict[dataset][scene])} images')\n\nout_results = {}\ntimings = {\"shortlisting\":[],\n           \"feature_detection\": [],\n           \"feature_matching\":[],\n           \"RANSAC\": [],\n           \"Reconstruction\": []}","metadata":{"execution":{"iopub.status.busy":"2024-04-08T02:29:20.807390Z","iopub.execute_input":"2024-04-08T02:29:20.808301Z","iopub.status.idle":"2024-04-08T02:29:20.824957Z","shell.execute_reply.started":"2024-04-08T02:29:20.808260Z","shell.execute_reply":"2024-04-08T02:29:20.823876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-04-08T02:29:23.481071Z","iopub.execute_input":"2024-04-08T02:29:23.481708Z","iopub.status.idle":"2024-04-08T02:29:23.490195Z","shell.execute_reply.started":"2024-04-08T02:29:23.481675Z","shell.execute_reply":"2024-04-08T02:29:23.489221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()\nfrom copy import deepcopy\ndatasets = []\nfor dataset in data_dict:\n    datasets.append(dataset)\nprint (f\"Extracting on device {device}\")\nfor dataset in data_dict:\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        img_dir =  os.path.join(src,  '/'.join(data_dict[dataset][scene][0].split('/')[:-1]))\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        # Wrap the meaty part in a try-except block.\n        try:\n            out_results[dataset][scene] = {}\n            img_fnames = [os.path.join(src, x) for x in data_dict[dataset][scene] ] \n            print (f\"Got {len(img_fnames)} images\")\n            feature_dir = f'featureout/{dataset}_{scene}'\n            os.makedirs(feature_dir, exist_ok=True)\n            t=time()\n            #if len(img_fnames) > 60:\n            #    continue\n            index_pairs = get_image_pairs_shortlist(img_fnames,\n                                  sim_th = 0.3, # should be strict\n                                  min_pairs = 20, # 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            detect_aliked(img_fnames, feature_dir, 4096, device=device)\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_with_lightglue(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            sleep(1)\n            import_into_colmap(img_dir, feature_dir=feature_dir, database_path=database_path)\n            output_path = f'{feature_dir}/colmap_rec_aliked'\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            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.IncrementalPipelineOptions()\n            mapper_options.min_model_size = 3\n            mapper_options.max_num_models = 2\n            os.makedirs(output_path, exist_ok=True)\n            maps = pycolmap.incremental_mapping(database_path=database_path, \n                                                image_path=img_dir,\n                                                output_path=output_path, options=mapper_options)\n            sleep(1)\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                    try:\n                        if len(rec.images) > imgs_registered:\n                            imgs_registered = len(rec.images)\n                            best_idx = idx1\n                    except:\n                        continue\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'test/{scene}/images/{im.name}'\n                    print(key1)\n                    out_results[dataset][scene][key1] = {}\n                    out_results[dataset][scene][key1][\"R\"] = deepcopy(im.cam_from_world.rotation.matrix())\n                    out_results[dataset][scene][key1][\"t\"] = deepcopy(np.array(im.cam_from_world.translation))\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 Exception as e:\n            print (e)\n            pass","metadata":{"execution":{"iopub.status.busy":"2024-04-08T02:29:28.616554Z","iopub.execute_input":"2024-04-08T02:29:28.616935Z","iopub.status.idle":"2024-04-08T02:34:56.132613Z","shell.execute_reply.started":"2024-04-08T02:29:28.616906Z","shell.execute_reply":"2024-04-08T02:34:56.131604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{"execution":{"iopub.status.busy":"2024-03-19T11:48:34.416172Z","iopub.execute_input":"2024-03-19T11:48:34.417113Z"}}},{"cell_type":"code","source":"!cat submission.csv\n#image_path,dataset,scene,rotation_matrix,translation_vector\n#rotation matrix: 3*3\n# translation_vector 3*1","metadata":{"execution":{"iopub.status.busy":"2024-04-08T04:19:14.139734Z","iopub.execute_input":"2024-04-08T04:19:14.140131Z","iopub.status.idle":"2024-04-08T04:19:15.119686Z","shell.execute_reply.started":"2024-04-08T04:19:14.140101Z","shell.execute_reply":"2024-04-08T04:19:15.118512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}