Upload biplet-asmk-mast3r-ps2-gs-kg-31oq.ipynb
Browse files
biplet-asmk-mast3r-ps2-gs-kg-31oq.ipynb
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"colab":{"provenance":[],"gpuType":"T4"},"accelerator":"GPU","kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":14571475,"sourceType":"datasetVersion","datasetId":1429416}],"dockerImageVersionId":31260,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **biplet-asmk-mast3r-ps2-gs-kg** \n\n","metadata":{"id":"qDQLX3PArmh8"}},{"cell_type":"markdown","source":"https://www.kaggle.com/code/stpeteishii/dino-mast3r-gs-kg-34","metadata":{}},{"cell_type":"code","source":"!pip install roma einops timm huggingface_hub\n!pip install opencv-python pillow tqdm pyaml cython plyfile\n!pip install pycolmap trimesh\n!pip uninstall -y numpy scipy\n!pip install numpy==1.26.4 scipy==1.11.4\n\nbreak","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# restart, then run after","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:23:40.805863Z","iopub.execute_input":"2026-01-22T06:23:40.806197Z","iopub.status.idle":"2026-01-22T06:23:40.810507Z","shell.execute_reply.started":"2026-01-22T06:23:40.806162Z","shell.execute_reply":"2026-01-22T06:23:40.809602Z"}},"outputs":[],"execution_count":32},{"cell_type":"code","source":"#!rm output/images/*","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:23:40.811883Z","iopub.execute_input":"2026-01-22T06:23:40.812195Z","iopub.status.idle":"2026-01-22T06:23:40.822747Z","shell.execute_reply.started":"2026-01-22T06:23:40.812169Z","shell.execute_reply":"2026-01-22T06:23:40.821989Z"}},"outputs":[],"execution_count":33},{"cell_type":"code","source":"#!ls output/images","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:23:40.824420Z","iopub.execute_input":"2026-01-22T06:23:40.824887Z","iopub.status.idle":"2026-01-22T06:23:40.837106Z","shell.execute_reply.started":"2026-01-22T06:23:40.824860Z","shell.execute_reply":"2026-01-22T06:23:40.836172Z"}},"outputs":[],"execution_count":34},{"cell_type":"code","source":"import numpy as np\nprint(f\"✓ np: {np.__version__} - {np.__file__}\")\n!pip show numpy | grep Version","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# romaが必要な時点で確認・インストール\ntry:\n import roma\n print(\"✓ roma is installed\")\nexcept ModuleNotFoundError:\n print(\"⚠️ roma not found, installing...\")\n !pip install roma\n import roma\n print(\"✓ roma installed\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:23:43.332455Z","iopub.execute_input":"2026-01-22T06:23:43.332775Z","iopub.status.idle":"2026-01-22T06:23:43.338489Z","shell.execute_reply.started":"2026-01-22T06:23:43.332716Z","shell.execute_reply":"2026-01-22T06:23:43.337637Z"}},"outputs":[{"name":"stdout","text":"✓ roma is installed\n","output_type":"stream"}],"execution_count":36},{"cell_type":"code","source":"import os\nimport sys\n\n# MASt3Rをクローン\nif not os.path.exists('/kaggle/working/mast3r'):\n print(\"Cloning MASt3R repository...\")\n !git clone --recursive https://github.com/naver/mast3r.git /kaggle/working/mast3r\n print(\"✓ MASt3R cloned\")\nelse:\n print(\"✓ MASt3R already exists\")\n\n# DUSt3Rをクローン(MASt3R内に必要)\nif not os.path.exists('/kaggle/working/mast3r/dust3r'):\n print(\"Cloning DUSt3R repository...\")\n !git clone --recursive https://github.com/naver/dust3r.git /kaggle/working/mast3r/dust3r\n print(\"✓ DUSt3R cloned\")\nelse:\n print(\"✓ DUSt3R already exists\")\n\n# ASMKをクローン\nif not os.path.exists('/kaggle/working/asmk'):\n print(\"Cloning ASMK repository...\")\n !git clone https://github.com/jenicek/asmk.git /kaggle/working/asmk\n print(\"✓ ASMK cloned\")\nelse:\n print(\"✓ ASMK already exists\")\n\n# パスを追加\nsys.path.insert(0, '/kaggle/working/mast3r')\nsys.path.insert(0, '/kaggle/working/mast3r/dust3r')\nsys.path.insert(0, '/kaggle/working/asmk')\n\n# 確認\ntry:\n from dust3r.model import AsymmetricCroCo3DStereo\n print(\"✓ dust3r.model imported successfully\")\nexcept ImportError as e:\n print(f\"✗ Import error: {e}\")\n\n# croco(MASt3Rの依存関係)もクローン\nif not os.path.exists('/kaggle/working/mast3r/croco'):\n print(\"Cloning CroCo repository...\")\n !git clone --recursive https://github.com/naver/croco.git /kaggle/working/mast3r/croco\n print(\"✓ CroCo cloned\")\n\n# CroCo v2の依存関係\nif not os.path.exists('/kaggle/working/mast3r/croco/models/curope'):\n print(\"Cloning CuRoPe...\")\n !git clone --recursive https://github.com/naver/curope.git /kaggle/working/mast3r/croco/models/curope\n print(\"✓ CuRoPe cloned\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:23:43.339716Z","iopub.execute_input":"2026-01-22T06:23:43.340102Z","iopub.status.idle":"2026-01-22T06:23:43.361015Z","shell.execute_reply.started":"2026-01-22T06:23:43.340069Z","shell.execute_reply":"2026-01-22T06:23:43.360304Z"}},"outputs":[{"name":"stdout","text":"✓ MASt3R already exists\n✓ DUSt3R already exists\n✓ ASMK already exists\n✓ dust3r.model imported successfully\n","output_type":"stream"}],"execution_count":37},{"cell_type":"code","source":"# =====================================================================\n# STEP 2: Clone Gaussian Splatting\n# =====================================================================\nprint(\"\\n\" + \"=\"*70)\nprint(\"STEP 2: Clone Gaussian Splatting\")\nprint(\"=\"*70)\nWORK_DIR = \"/kaggle/working/gaussian-splatting\"\n\nimport subprocess\nif not os.path.exists(WORK_DIR):\n subprocess.run([\n \"git\", \"clone\", \"--recursive\",\n \"https://github.com/graphdeco-inria/gaussian-splatting.git\",\n WORK_DIR\n ], capture_output=True)\n print(\"✓ Cloned\")\nelse:\n print(\"✓ Already exists\")\n\n# インストールが必要なディレクトリ\nsubmodules = [\n \"/kaggle/working/gaussian-splatting/submodules/diff-gaussian-rasterization\",\n \"/kaggle/working/gaussian-splatting/submodules/simple-knn\"\n]\n\nfor path in submodules:\n print(f\"Installing {path}...\")\n # -e は編集可能モード、不要なら外してもOKです\n subprocess.run([\"pip\", \"install\", path], check=True)\n\nprint(\"✓ Custom CUDA modules installed.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:23:43.362110Z","iopub.execute_input":"2026-01-22T06:23:43.362388Z","iopub.status.idle":"2026-01-22T06:24:06.980493Z","shell.execute_reply.started":"2026-01-22T06:23:43.362360Z","shell.execute_reply":"2026-01-22T06:24:06.979818Z"}},"outputs":[{"name":"stdout","text":"\n======================================================================\nSTEP 2: Clone Gaussian Splatting\n======================================================================\n✓ Already exists\nInstalling /kaggle/working/gaussian-splatting/submodules/diff-gaussian-rasterization...\nProcessing ./gaussian-splatting/submodules/diff-gaussian-rasterization\n Preparing metadata (setup.py): started\n Preparing metadata (setup.py): finished with status 'done'\nBuilding wheels for collected packages: diff_gaussian_rasterization\n Building wheel for diff_gaussian_rasterization (setup.py): started\n Building wheel for diff_gaussian_rasterization (setup.py): finished with status 'done'\n Created wheel for diff_gaussian_rasterization: filename=diff_gaussian_rasterization-0.0.0-cp312-cp312-linux_x86_64.whl size=3455607 sha256=b162a676512ef536704512c471b001d63aa2bd086183ec432689a63f0ed8a56e\n Stored in directory: /root/.cache/pip/wheels/ba/99/d3/014520068aca8c2e8bdc358ca774581380cadb65788559b3ea\nSuccessfully built diff_gaussian_rasterization\nInstalling collected packages: diff_gaussian_rasterization\n Attempting uninstall: diff_gaussian_rasterization\n Found existing installation: diff_gaussian_rasterization 0.0.0\n Uninstalling diff_gaussian_rasterization-0.0.0:\n Successfully uninstalled diff_gaussian_rasterization-0.0.0\nSuccessfully installed diff_gaussian_rasterization-0.0.0\nInstalling /kaggle/working/gaussian-splatting/submodules/simple-knn...\nProcessing ./gaussian-splatting/submodules/simple-knn\n Preparing metadata (setup.py): started\n Preparing metadata (setup.py): finished with status 'done'\nBuilding wheels for collected packages: simple_knn\n Building wheel for simple_knn (setup.py): started\n Building wheel for simple_knn (setup.py): finished with status 'done'\n Created wheel for simple_knn: filename=simple_knn-0.0.0-cp312-cp312-linux_x86_64.whl size=3212333 sha256=9d5dcc21a6c9e7635c0aa47924d5021730c2c30d93b97359cb5c486cc730f258\n Stored in directory: /root/.cache/pip/wheels/ca/30/df/7f4f362d12edead48c699acde5962cbb06ca05033b9d970934\nSuccessfully built simple_knn\nInstalling collected packages: simple_knn\n Attempting uninstall: simple_knn\n Found existing installation: simple_knn 0.0.0\n Uninstalling simple_knn-0.0.0:\n Successfully uninstalled simple_knn-0.0.0\nSuccessfully installed simple_knn-0.0.0\n✓ Custom CUDA modules installed.\n","output_type":"stream"}],"execution_count":38},{"cell_type":"code","source":"import numpy as np\nprint(f\"✓ np: {np.__version__} - {np.__file__}\")\n!pip show numpy | grep Version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:06.981524Z","iopub.execute_input":"2026-01-22T06:24:06.981865Z","iopub.status.idle":"2026-01-22T06:24:09.315567Z","shell.execute_reply.started":"2026-01-22T06:24:06.981830Z","shell.execute_reply":"2026-01-22T06:24:09.314660Z"}},"outputs":[{"name":"stdout","text":"✓ np: 1.26.4 - /usr/local/lib/python3.12/dist-packages/numpy/__init__.py\nVersion: 1.26.4\nVersion 3.1, 31 March 2009\n Version 3, 29 June 2007\n 5. Conveying Modified Source Versions.\n 14. Revised Versions of this License.\n","output_type":"stream"}],"execution_count":39},{"cell_type":"code","source":"import os\nimport sys\nimport gc\nimport torch\nimport numpy as np\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport torch.nn.functional as F\n\n# ======================================================================\n# MEMORY MANAGEMENT\n# ======================================================================\n\nos.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'\n\ndef clear_memory():\n \"\"\"メモリクリア関数\"\"\"\n gc.collect()\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n torch.cuda.synchronize()\n\n\n# ======================================================================\n# CONFIGURATION\n# ======================================================================\n\nclass Config:\n DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # 正しいMASt3Rモデル名\n MAST3R_WEIGHTS = \"naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\"\n DUST3R_WEIGHTS = \"naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt\" # フォールバック用\n RETRIEVAL_TOPK = 10\n IMAGE_SIZE = 224 # メモリ節約のため224に設定\n\n\n# ======================================================================\n# IMAGE PREPROCESSING\n# ======================================================================\n\nimport os\nimport shutil\nfrom PIL import Image\nfrom tqdm import tqdm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.318395Z","iopub.execute_input":"2026-01-22T06:24:09.318749Z","iopub.status.idle":"2026-01-22T06:24:09.326128Z","shell.execute_reply.started":"2026-01-22T06:24:09.318703Z","shell.execute_reply":"2026-01-22T06:24:09.325288Z"}},"outputs":[],"execution_count":40},{"cell_type":"code","source":"# ======================================================================\n# IMAGE PREPROCESSING\n# ======================================================================\n\nimport os\nimport shutil\nfrom PIL import Image\nfrom tqdm import tqdm\n\n# ======================================================================\n# IMAGE PREPROCESSING\n# ======================================================================\n\ndef normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024):\n \"\"\"\n Generates two square crops (Left & Right or Top & Bottom)\n from each image in a directory.\n Bipletクロップのみ生成(元画像はコピーしない)\n \"\"\"\n if output_dir is None:\n output_dir = input_dir + \"_biplet\"\n \n os.makedirs(output_dir, exist_ok=True)\n \n print(f\"\\n=== Generating Biplet Crops ({size}x{size}) ===\")\n \n converted_count = 0\n size_stats = {}\n \n for img_file in tqdm(sorted(os.listdir(input_dir)), desc=\"Creating biplets\"):\n if not img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n continue\n \n input_path = os.path.join(input_dir, img_file)\n \n try:\n img = Image.open(input_path)\n original_size = img.size\n \n size_key = f\"{original_size[0]}x{original_size[1]}\"\n size_stats[size_key] = size_stats.get(size_key, 0) + 1\n \n # Generate 2 crops (元画像のコピーは削除)\n crops = generate_two_crops(img, size)\n \n base_name, ext = os.path.splitext(img_file)\n for mode, cropped_img in crops.items():\n output_path = os.path.join(output_dir, f\"{base_name}_{mode}{ext}\")\n cropped_img.save(output_path, quality=95)\n \n converted_count += 1\n \n except Exception as e:\n print(f\" ✗ Error processing {img_file}: {e}\")\n \n print(f\"\\n✓ Biplet generation complete:\")\n print(f\" Source images: {converted_count}\")\n print(f\" Biplet crops generated: {converted_count * 2}\")\n print(f\" Original size distribution: {size_stats}\")\n \n return output_dir\n\n\ndef generate_two_crops(img, size):\n \"\"\"\n Crops the image into a square and returns 2 variations\n (Left/Right for landscape, Top/Bottom for portrait).\n \"\"\"\n width, height = img.size\n crop_size = min(width, height)\n crops = {}\n \n if width > height:\n # Landscape → Left & Right\n positions = {\n 'left': 0,\n 'right': width - crop_size\n }\n for mode, x_offset in positions.items():\n box = (x_offset, 0, x_offset + crop_size, crop_size)\n crops[mode] = img.crop(box).resize(\n (size, size),\n Image.Resampling.LANCZOS\n )\n \n else:\n # Portrait or Square → Top & Bottom\n positions = {\n 'top': 0,\n 'bottom': height - crop_size\n }\n for mode, y_offset in positions.items():\n box = (0, y_offset, crop_size, y_offset + crop_size)\n crops[mode] = img.crop(box).resize(\n (size, size),\n Image.Resampling.LANCZOS\n )\n \n return crops\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.327035Z","iopub.execute_input":"2026-01-22T06:24:09.327313Z","iopub.status.idle":"2026-01-22T06:24:09.343475Z","shell.execute_reply.started":"2026-01-22T06:24:09.327279Z","shell.execute_reply":"2026-01-22T06:24:09.342929Z"}},"outputs":[],"execution_count":41},{"cell_type":"code","source":"# ======================================================================\n# IMAGE LOADING\n# ======================================================================\n\ndef load_images_from_directory(image_dir, max_images=200):\n \"\"\"ディレクトリから画像をロード\"\"\"\n print(f\"\\nLoading images from: {image_dir}\")\n \n valid_extensions = {'.jpg', '.jpeg', '.png', '.bmp'}\n image_paths = []\n \n for ext in valid_extensions:\n image_paths.extend(sorted(Path(image_dir).glob(f'*{ext}')))\n image_paths.extend(sorted(Path(image_dir).glob(f'*{ext.upper()}')))\n \n image_paths = sorted(set(str(p) for p in image_paths))\n \n if len(image_paths) > max_images:\n print(f\"⚠️ Limiting from {len(image_paths)} to {max_images} images\")\n image_paths = image_paths[:max_images]\n \n print(f\"✓ Found {len(image_paths)} images\")\n return image_paths\n\n\n# ======================================================================\n# MAST3R MODEL\n# ======================================================================\n\ndef load_mast3r_model(device):\n \"\"\"MASt3Rモデルをロード\"\"\"\n print(\"\\n=== Loading MASt3R Model ===\")\n \n # mast3rのパスを追加\n if '/kaggle/working/mast3r' not in sys.path:\n sys.path.insert(0, '/kaggle/working/mast3r')\n if '/kaggle/working/mast3r/dust3r' not in sys.path:\n sys.path.insert(0, '/kaggle/working/mast3r/dust3r')\n \n from dust3r.model import AsymmetricCroCo3DStereo\n \n try:\n # MASt3Rモデルを試す\n print(f\"Attempting to load: {Config.MAST3R_WEIGHTS}\")\n model = AsymmetricCroCo3DStereo.from_pretrained(Config.MAST3R_WEIGHTS).to(device)\n print(\"✓ Loaded MASt3R model\")\n except Exception as e:\n print(f\"⚠️ Failed to load MASt3R: {e}\")\n print(f\"Trying DUSt3R instead: {Config.DUST3R_WEIGHTS}\")\n try:\n model = AsymmetricCroCo3DStereo.from_pretrained(Config.DUST3R_WEIGHTS).to(device)\n print(\"✓ Loaded DUSt3R model as fallback\")\n except Exception as e2:\n print(f\"⚠️ Failed to load DUSt3R: {e2}\")\n raise Exception(\"Could not load any model. Please check model names and internet connection.\")\n \n model.eval()\n \n print(f\"✓ Model loaded on {device}\")\n return model\n\n\n# ======================================================================\n# FEATURE EXTRACTION & PAIR SELECTION\n# ======================================================================\n\ndef load_asmk_retrieval_model(device):\n \"\"\"ASMKリトリーバルモデルをロード\"\"\"\n print(\"\\n=== Loading ASMK Retrieval Model ===\")\n \n # mast3rとasmkのパスを追加\n if '/kaggle/working/mast3r' not in sys.path:\n sys.path.insert(0, '/kaggle/working/mast3r')\n if '/kaggle/working/mast3r/dust3r' not in sys.path:\n sys.path.insert(0, '/kaggle/working/mast3r/dust3r')\n if '/kaggle/working/asmk' not in sys.path:\n sys.path.insert(0, '/kaggle/working/asmk')\n \n from dust3r.model import AsymmetricCroCo3DStereo\n \n try:\n # MASt3Rモデルを試す\n model = AsymmetricCroCo3DStereo.from_pretrained(Config.MAST3R_WEIGHTS).to(device)\n print(\"✓ Loaded MASt3R model for retrieval\")\n except Exception as e:\n print(f\"⚠️ Failed to load MASt3R: {e}\")\n print(f\"Trying DUSt3R instead\")\n model = AsymmetricCroCo3DStereo.from_pretrained(Config.DUST3R_WEIGHTS).to(device)\n print(\"✓ Loaded DUSt3R model for retrieval\")\n \n model.eval()\n \n # Codebookの初期化(簡易版)\n codebook = np.random.randn(1024, 24).astype(np.float32)\n \n print(\"✓ ASMK model loaded\")\n return model, codebook\n\n\ndef extract_mast3r_features(model, image_paths, device, batch_size=1):\n \"\"\"MASt3Rモデルを使用して特徴量を抽出(ペア画像として処理)\"\"\"\n print(\"\\n=== Extracting MASt3R Features ===\")\n from dust3r.utils.image import load_images\n from dust3r.inference import inference\n \n all_features = []\n \n # 各画像を自分自身とペアにして処理\n for i in tqdm(range(len(image_paths)), desc=\"Features\"):\n img_path = image_paths[i]\n \n # 同じ画像を2回ロード(ペアとして)\n images = load_images([img_path, img_path], size=Config.IMAGE_SIZE)\n \n # ペア形式で推論\n pairs = [(images[0], images[1])]\n \n with torch.no_grad():\n output = inference(pairs, model, device, batch_size=1)\n \n # outputの構造を確認してデータを抽出\n try:\n # outputが辞書の場合 (DUSt3R形式)\n if isinstance(output, dict):\n # pred1から3D点または特徴量を取得\n if 'pred1' in output:\n pred1 = output['pred1']\n if isinstance(pred1, dict):\n # pts3dまたはdescを探す\n if 'pts3d' in pred1:\n desc = pred1['pts3d']\n elif 'desc' in pred1:\n desc = pred1['desc']\n else:\n # 利用可能な最初のテンソルを使用\n for key, val in pred1.items():\n if isinstance(val, torch.Tensor):\n desc = val\n break\n else:\n desc = pred1\n elif 'view1' in output:\n desc = output['view1']\n else:\n # 最初の値を使用\n desc = list(output.values())[0]\n # outputがタプル (view1, view2) の形式\n elif isinstance(output, tuple) and len(output) == 2:\n view1, view2 = output\n # view1から特徴量を取得\n if isinstance(view1, dict):\n if 'pts3d' in view1:\n desc = view1['pts3d']\n elif 'desc' in view1:\n desc = view1['desc']\n else:\n desc = list(view1.values())[0]\n else:\n desc = view1\n # outputがリストの場合\n elif isinstance(output, list):\n if len(output) > 0:\n item = output[0]\n if isinstance(item, dict):\n if 'pts3d' in item:\n desc = item['pts3d']\n elif 'desc' in item:\n desc = item['desc']\n else:\n desc = list(item.values())[0]\n else:\n desc = item\n else:\n raise ValueError(\"Empty output\")\n else:\n # その他の形式\n desc = output\n \n # テンソルの次元を調整\n if isinstance(desc, torch.Tensor):\n if desc.dim() == 4:\n desc = desc.squeeze(0) # [1, H, W, C] -> [H, W, C]\n elif desc.dim() == 2:\n # [H*W, C] の場合、適切な形状に変換\n h = w = int(np.sqrt(desc.shape[0]))\n if h * w == desc.shape[0]:\n desc = desc.reshape(h, w, desc.shape[1])\n \n all_features.append(desc)\n \n except Exception as e:\n print(f\"⚠️ Error extracting features for image {i}: {e}\")\n print(f\" Output type: {type(output)}\")\n if isinstance(output, (list, tuple)):\n print(f\" Output length: {len(output)}\")\n if len(output) > 0:\n print(f\" First item type: {type(output[0])}\")\n if isinstance(output[0], dict):\n print(f\" Keys: {output[0].keys()}\")\n # デフォルトの特徴量を追加\n all_features.append(torch.zeros((Config.IMAGE_SIZE, Config.IMAGE_SIZE, 24)))\n \n # メモリクリア\n del output, images, pairs\n if i % 10 == 0:\n torch.cuda.empty_cache()\n \n print(f\"✓ Extracted features for {len(all_features)} images\")\n if all_features:\n first_feat = all_features[0]\n if isinstance(first_feat, torch.Tensor):\n print(f\" Feature shape: {first_feat.shape}\")\n elif isinstance(first_feat, dict):\n print(f\" Feature type: dict with keys: {first_feat.keys()}\")\n elif isinstance(first_feat, np.ndarray):\n print(f\" Feature shape: {first_feat.shape}\")\n else:\n print(f\" Feature type: {type(first_feat)}\")\n \n return all_features\n\n\ndef compute_asmk_similarity(features, codebook):\n \"\"\"ASMKを使用して類似度行列を計算\"\"\"\n print(\"\\n=== Computing ASMK Similarity ===\")\n \n n_images = len(features)\n similarity_matrix = np.zeros((n_images, n_images), dtype=np.float32)\n \n # 各特徴量をグローバル記述子に変換\n global_features = []\n \n for feat in features:\n # featが辞書の場合、テンソルを抽出\n if isinstance(feat, dict):\n if 'pts3d' in feat:\n feat = feat['pts3d']\n elif 'desc' in feat:\n feat = feat['desc']\n elif 'pred1' in feat:\n pred1 = feat['pred1']\n if isinstance(pred1, dict) and 'pts3d' in pred1:\n feat = pred1['pts3d']\n else:\n feat = pred1\n else:\n # 最初のテンソル値を使用\n for val in feat.values():\n if isinstance(val, (torch.Tensor, np.ndarray)):\n feat = val\n break\n \n if isinstance(feat, torch.Tensor):\n feat = feat.cpu().numpy()\n \n # featの形状を確認\n if isinstance(feat, np.ndarray):\n if feat.ndim == 3: # [H, W, C]\n h, w, c = feat.shape\n feat_flat = feat.reshape(-1, c)\n elif feat.ndim == 2: # [N, C]\n feat_flat = feat\n else:\n print(f\"⚠️ Unexpected feature shape: {feat.shape}\")\n feat_flat = feat.reshape(-1, feat.shape[-1])\n \n global_desc = np.mean(feat_flat, axis=0)\n global_features.append(global_desc)\n else:\n print(f\"⚠️ Unexpected feature type: {type(feat)}\")\n # ダミー特徴量\n global_features.append(np.zeros(24))\n \n global_features = np.stack(global_features)\n \n if codebook is not None and len(codebook) > 0:\n try:\n print(f\"Using ASMK with codebook size: {len(codebook)}\")\n \n for i in range(n_images):\n feat_i = features[i]\n \n # 辞書からテンソルを抽出\n if isinstance(feat_i, dict):\n if 'pts3d' in feat_i:\n feat_i = feat_i['pts3d']\n elif 'pred1' in feat_i and isinstance(feat_i['pred1'], dict):\n feat_i = feat_i['pred1'].get('pts3d', feat_i['pred1'])\n \n if isinstance(feat_i, torch.Tensor):\n feat_i = feat_i.cpu().numpy()\n \n if feat_i.ndim == 3:\n feat_i = feat_i.reshape(-1, feat_i.shape[-1])\n \n for j in range(i+1, n_images):\n feat_j = features[j]\n \n # 辞書からテンソルを抽出\n if isinstance(feat_j, dict):\n if 'pts3d' in feat_j:\n feat_j = feat_j['pts3d']\n elif 'pred1' in feat_j and isinstance(feat_j['pred1'], dict):\n feat_j = feat_j['pred1'].get('pts3d', feat_j['pred1'])\n \n if isinstance(feat_j, torch.Tensor):\n feat_j = feat_j.cpu().numpy()\n \n if feat_j.ndim == 3:\n feat_j = feat_j.reshape(-1, feat_j.shape[-1])\n \n dist_i = np.linalg.norm(feat_i[:, None, :] - codebook[None, :, :], axis=2)\n dist_j = np.linalg.norm(feat_j[:, None, :] - codebook[None, :, :], axis=2)\n \n assign_i = np.argmin(dist_i, axis=1)\n assign_j = np.argmin(dist_j, axis=1)\n \n common = len(set(assign_i) & set(assign_j))\n sim = common / max(len(set(assign_i)), len(set(assign_j)))\n \n similarity_matrix[i, j] = sim\n similarity_matrix[j, i] = sim\n \n if (i + 1) % 10 == 0:\n print(f\"Processed {i+1}/{n_images} images\")\n \n print(\"✓ ASMK similarity computation completed\")\n \n except Exception as e:\n print(f\"⚠️ ASMK failed: {e}, using cosine similarity\")\n global_features_norm = global_features / (np.linalg.norm(global_features, axis=1, keepdims=True) + 1e-8)\n similarity_matrix = global_features_norm @ global_features_norm.T\n \n else:\n print(\"No codebook provided, using cosine similarity\")\n global_features_norm = global_features / (np.linalg.norm(global_features, axis=1, keepdims=True) + 1e-8)\n similarity_matrix = global_features_norm @ global_features_norm.T\n \n np.fill_diagonal(similarity_matrix, -1)\n \n print(f\"Similarity matrix shape: {similarity_matrix.shape}\")\n print(f\"Similarity range: [{similarity_matrix.min():.3f}, {similarity_matrix.max():.3f}]\")\n \n return similarity_matrix\n\n\ndef build_pairs_from_similarity(similarity_matrix, top_k=10):\n \"\"\"類似度行列からペアを構築\"\"\"\n n_images = similarity_matrix.shape[0]\n pairs = []\n \n for i in range(n_images):\n similarities = similarity_matrix[i]\n top_indices = np.argsort(similarities)[::-1][:top_k]\n \n for j in top_indices:\n if j > i:\n pairs.append((i, j))\n \n pairs = list(set(pairs))\n print(f\"✓ Built {len(pairs)} unique pairs\")\n \n return pairs\n\n\ndef get_image_pairs_asmk(image_paths, max_pairs=100):\n \"\"\"ASMKを使用して画像ペアを取得\"\"\"\n print(\"\\n=== Getting Image Pairs with ASMK ===\")\n \n device = Config.DEVICE\n model, codebook = load_asmk_retrieval_model(device)\n features = extract_mast3r_features(model, image_paths, device)\n similarity_matrix = compute_asmk_similarity(features, codebook)\n pairs = build_pairs_from_similarity(similarity_matrix, Config.RETRIEVAL_TOPK)\n \n # モデルを解放\n del model\n clear_memory()\n \n if len(pairs) > max_pairs:\n pairs = pairs[:max_pairs]\n print(f\"Limited to {max_pairs} pairs\")\n \n return pairs\n\n\n# ======================================================================\n# MAST3R RECONSTRUCTION\n# ======================================================================\n\ndef run_mast3r_pairs(model, image_paths, pairs, device, batch_size=1):\n \"\"\"MASt3Rでペア画像を処理(メモリ最適化版)\"\"\"\n print(\"\\n=== Running MASt3R Reconstruction ===\")\n from dust3r.inference import inference\n from dust3r.cloud_opt import global_aligner, GlobalAlignerMode\n from dust3r.utils.image import load_images\n \n # ペアを制限(メモリ節約)\n max_pairs_for_memory = 50\n if len(pairs) > max_pairs_for_memory:\n print(f\"⚠️ Limiting pairs from {len(pairs)} to {max_pairs_for_memory} for memory\")\n pairs = pairs[:max_pairs_for_memory]\n \n # ペアから画像インデックスを取得\n pair_indices = []\n for i, j in pairs:\n pair_indices.extend([i, j])\n unique_indices = sorted(set(pair_indices))\n \n selected_paths = [image_paths[i] for i in unique_indices]\n print(f\"Selected {len(selected_paths)} unique images from {len(pairs)} pairs\")\n \n # 画像をロード\n images = load_images(selected_paths, size=Config.IMAGE_SIZE)\n \n clear_memory()\n \n # インデックスマッピング(元のインデックス → 新しいインデックス)\n index_map = {old_idx: new_idx for new_idx, old_idx in enumerate(unique_indices)}\n \n # ペアを新しいインデックスに変換してペア画像リストを作成\n image_pairs = []\n for i, j in pairs:\n new_i = index_map[i]\n new_j = index_map[j]\n image_pairs.append((images[new_i], images[new_j]))\n \n print(f\"Created {len(image_pairs)} image pairs\")\n \n clear_memory()\n \n # バッチサイズを動的に調整\n available_memory = torch.cuda.get_device_properties(device).total_memory\n used_memory = torch.cuda.memory_allocated(device)\n free_memory = available_memory - used_memory\n \n if free_memory < 2e9:\n batch_size = 1\n print(f\"⚠️ Low memory, using batch_size=1\")\n \n # 推論を実行\n print(f\"Running inference on {len(image_pairs)} pairs...\")\n with torch.no_grad():\n output = inference(image_pairs, model, device, batch_size=batch_size)\n \n print(f\"✓ Processed {len(output)} predictions\")\n \n clear_memory()\n \n # Global alignmentの準備\n scene = global_aligner(\n dust3r_output=output,\n device=device,\n mode=GlobalAlignerMode.PointCloudOptimizer,\n verbose=True\n )\n \n clear_memory()\n \n # Global alignment\n print(\"Running global alignment...\")\n try:\n loss = scene.compute_global_alignment(\n init=\"mst\", \n niter=50,\n schedule='cosine', \n lr=0.01\n )\n print(f\"✓ Alignment complete (loss: {loss:.6f})\")\n except RuntimeError as e:\n if \"out of memory\" in str(e).lower():\n print(\"⚠️ OOM during alignment, trying with fewer iterations...\")\n clear_memory()\n \n loss = scene.compute_global_alignment(\n init=\"mst\", \n niter=20,\n schedule='cosine', \n lr=0.01\n )\n print(f\"✓ Alignment complete with reduced iterations (loss: {loss:.6f})\")\n else:\n raise\n \n clear_memory()\n \n return scene, images\n\n\n# ======================================================================\n# CAMERA PARAMETER EXTRACTION (PROCESS2)\n# ======================================================================\n\ndef extract_camera_params_process2(scene, image_paths, conf_threshold=1.5):\n \"\"\"Process2: sceneから直接カメラパラメータと3D点を抽出\"\"\"\n print(\"\\n=== Extracting Camera Parameters (Process2) ===\")\n \n cameras_dict = {}\n all_pts3d = []\n all_confidence = []\n \n # sceneから実際の画像��を取得\n try:\n if hasattr(scene, 'get_im_poses'):\n poses = scene.get_im_poses()\n n_images = len(poses)\n elif hasattr(scene, 'im_poses'):\n poses = scene.im_poses\n n_images = len(poses)\n else:\n n_images = len(image_paths)\n poses = None\n \n print(f\"Scene has {n_images} images, image_paths has {len(image_paths)} images\")\n \n # 実際のscene画像数とimage_pathsの小さい方を使用\n n_images = min(n_images, len(image_paths))\n \n if hasattr(scene, 'get_focals'):\n focals = scene.get_focals()\n elif hasattr(scene, 'im_focals'):\n focals = scene.im_focals\n else:\n focals = None\n \n if hasattr(scene, 'get_principal_points'):\n pps = scene.get_principal_points()\n elif hasattr(scene, 'im_pp'):\n pps = scene.im_pp\n else:\n pps = None\n \n except Exception as e:\n print(f\"⚠️ Error getting camera parameters: {e}\")\n n_images = len(image_paths)\n poses = None\n focals = None\n pps = None\n \n for idx in range(n_images):\n #-------------------------------------------------------------------\n print(f\"\\n=== Image {idx}: {os.path.basename(image_paths[idx])} ===\")\n \n # Poseを取得の後に追加\n if poses is not None and idx < len(poses):\n pose = poses[idx]\n if isinstance(pose, torch.Tensor):\n pose = pose.detach().cpu().numpy()\n \n print(f\" Pose type: {type(pose)}\")\n print(f\" Pose shape: {pose.shape if hasattr(pose, 'shape') else 'N/A'}\")\n if hasattr(pose, 'shape') and pose.shape == (4, 4):\n print(f\" Rotation det: {np.linalg.det(pose[:3, :3]):.3f}\")\n #-------------------------------------------------------------------\n \n img_name = os.path.basename(image_paths[idx])\n \n try:\n # Poseを取得\n if poses is not None and idx < len(poses):\n pose = poses[idx]\n if isinstance(pose, torch.Tensor):\n pose = pose.detach().cpu().numpy()\n \n # poseが正しい形状でない場合、単位行列を使用\n if not isinstance(pose, np.ndarray) or pose.shape != (4, 4):\n print(f\" → Image {idx}: pose shape {pose.shape if hasattr(pose, 'shape') else 'N/A'}, using identity\")\n pose = np.eye(4)\n else:\n pose = np.eye(4)\n \n # Focalを取得\n if focals is not None and idx < len(focals):\n focal = focals[idx]\n if isinstance(focal, torch.Tensor):\n focal = focal.detach().cpu().item()\n else:\n focal = float(focal)\n else:\n focal = 1000.0\n \n # Principal pointを取得\n if pps is not None and idx < len(pps):\n pp = pps[idx]\n if isinstance(pp, torch.Tensor):\n pp = pp.detach().cpu().numpy()\n else:\n pp = np.array([112.0, 112.0])\n \n # カメラパラメータを保存\n cameras_dict[img_name] = {\n 'focal': focal,\n 'pp': pp,\n 'pose': pose\n }\n \n # 3D点を取得\n if hasattr(scene, 'im_pts3d') and idx < len(scene.im_pts3d):\n pts3d_img = scene.im_pts3d[idx]\n elif hasattr(scene, 'get_pts3d'):\n pts3d_all = scene.get_pts3d()\n if idx < len(pts3d_all):\n pts3d_img = pts3d_all[idx]\n else:\n pts3d_img = None\n else:\n pts3d_img = None\n \n # Confidenceを取得\n if hasattr(scene, 'im_conf') and idx < len(scene.im_conf):\n conf_img = scene.im_conf[idx]\n elif hasattr(scene, 'get_conf'):\n conf_all = scene.get_conf()\n if idx < len(conf_all):\n conf_img = conf_all[idx]\n else:\n conf_img = None\n else:\n conf_img = None\n \n # 3D点とconfidenceを処理\n if pts3d_img is not None:\n if isinstance(pts3d_img, torch.Tensor):\n pts3d_img = pts3d_img.detach().cpu().numpy()\n \n if pts3d_img.ndim == 3:\n pts3d_flat = pts3d_img.reshape(-1, 3)\n else:\n pts3d_flat = pts3d_img\n \n all_pts3d.append(pts3d_flat)\n \n # confidenceを処理\n if conf_img is not None:\n if isinstance(conf_img, list):\n conf_img = np.array(conf_img)\n elif isinstance(conf_img, torch.Tensor):\n conf_img = conf_img.detach().cpu().numpy()\n \n if conf_img.ndim > 1:\n conf_flat = conf_img.reshape(-1)\n else:\n conf_flat = conf_img\n \n if len(conf_flat) != len(pts3d_flat):\n conf_flat = np.ones(len(pts3d_flat))\n \n all_confidence.append(conf_flat)\n else:\n all_confidence.append(np.ones(len(pts3d_flat)))\n \n except Exception as e:\n print(f\"⚠️ Error processing image {idx} ({img_name}): {e}\")\n cameras_dict[img_name] = {\n 'focal': 1000.0,\n 'pp': np.array([112.0, 112.0]),\n 'pose': np.eye(4)\n }\n continue\n \n # 全3D点を結合\n if all_pts3d:\n pts3d = np.vstack(all_pts3d)\n confidence = np.concatenate(all_confidence)\n else:\n pts3d = np.zeros((0, 3))\n confidence = np.zeros(0)\n \n print(f\"✓ Extracted camera parameters for {len(cameras_dict)} images\")\n print(f\"✓ Total 3D points: {len(pts3d)}\")\n \n # Confidenceでフィルタリング\n if len(confidence) > 0:\n valid_mask = confidence > conf_threshold\n pts3d = pts3d[valid_mask]\n confidence = confidence[valid_mask]\n print(f\"✓ After confidence filtering (>{conf_threshold}): {len(pts3d)} points\")\n \n return cameras_dict, pts3d, confidence","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.344803Z","iopub.execute_input":"2026-01-22T06:24:09.345101Z","iopub.status.idle":"2026-01-22T06:24:09.404283Z","shell.execute_reply.started":"2026-01-22T06:24:09.345073Z","shell.execute_reply":"2026-01-22T06:24:09.403568Z"}},"outputs":[],"execution_count":42},{"cell_type":"code","source":"# ======================================================================\n# COLMAP EXPORT v.10\n# ======================================================================\nimport os\nimport struct\nimport numpy as np\nfrom scipy.spatial.transform import Rotation as R\n\ndef write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, output_dir):\n \"\"\"\n COLMAP sparse形式をバイナリファイルで出力\n Gaussian Splattingが要求する .bin 形式\n \"\"\"\n os.makedirs(output_dir, exist_ok=True)\n \n # カメラパラメータを取得\n if not cameras_dict:\n raise ValueError(\"cameras_dict is empty\")\n \n first_key = list(cameras_dict.keys())[0]\n first_cam = cameras_dict[first_key]\n \n w = int(first_cam.get('width', 1920))\n h = int(first_cam.get('height', 1080))\n focal = float(first_cam.get('focal', max(w, h) * 1.2))\n cx = w / 2.0\n cy = h / 2.0\n \n # --- 1. cameras.bin を書き出し ---\n cameras_file = os.path.join(output_dir, 'cameras.bin')\n with open(cameras_file, 'wb') as f:\n # ヘッダー: カメラ数\n f.write(struct.pack('Q', 1)) # 1つのカメラ\n \n # カメラデータ\n camera_id = 1\n model_id = 1 # PINHOLE\n f.write(struct.pack('i', camera_id))\n f.write(struct.pack('i', model_id))\n f.write(struct.pack('Q', w))\n f.write(struct.pack('Q', h))\n # PINHOLE: fx, fy, cx, cy\n f.write(struct.pack('d', focal))\n f.write(struct.pack('d', focal))\n f.write(struct.pack('d', cx))\n f.write(struct.pack('d', cy))\n \n print(f\"✓ Written cameras.bin\")\n \n # --- 2. images.bin を書き出し ---\n images_file = os.path.join(output_dir, 'images.bin')\n with open(images_file, 'wb') as f:\n # ヘッダー: 画像数\n f.write(struct.pack('Q', len(image_paths)))\n \n for i, img_path in enumerate(image_paths):\n img_name = os.path.basename(img_path)\n \n cam_info = cameras_dict.get(i) or cameras_dict.get(str(i)) or cameras_dict.get(img_name)\n if cam_info is None:\n print(f\" ⚠️ No camera info for {img_name}, using identity pose\")\n pose = np.eye(4)\n else:\n pose = cam_info['pose']\n \n # Pose (C2W -> W2C)\n try:\n w2c = np.linalg.inv(pose)\n except np.linalg.LinAlgError:\n print(f\" ⚠️ Singular matrix for {img_name}, using identity\")\n w2c = np.eye(4)\n \n rot_mat = w2c[:3, :3]\n tvec = w2c[:3, 3]\n \n # Rotation -> Quaternion [w, x, y, z]\n quat = R.from_matrix(rot_mat).as_quat() # [x, y, z, w]\n qw, qx, qy, qz = quat[3], quat[0], quat[1], quat[2]\n \n # 画像データ\n image_id = i + 1\n f.write(struct.pack('i', image_id))\n f.write(struct.pack('d', qw))\n f.write(struct.pack('d', qx))\n f.write(struct.pack('d', qy))\n f.write(struct.pack('d', qz))\n f.write(struct.pack('d', tvec[0]))\n f.write(struct.pack('d', tvec[1]))\n f.write(struct.pack('d', tvec[2]))\n f.write(struct.pack('i', 1)) # camera_id\n \n # 画像名 (null終端文字列)\n img_name_bytes = img_name.encode('utf-8') + b'\\x00'\n f.write(img_name_bytes)\n \n # 2D点数 (0個)\n f.write(struct.pack('Q', 0))\n \n print(f\"✓ Written images.bin ({len(image_paths)} images)\")\n \n # --- 3. points3D.bin を書き出し ---\n points_file = os.path.join(output_dir, 'points3D.bin')\n with open(points_file, 'wb') as f:\n # ヘッダー: 点数\n f.write(struct.pack('Q', len(pts3d)))\n \n for point_id, point in enumerate(pts3d, start=1):\n f.write(struct.pack('Q', point_id))\n f.write(struct.pack('d', point[0])) # X\n f.write(struct.pack('d', point[1])) # Y\n f.write(struct.pack('d', point[2])) # Z\n f.write(struct.pack('B', 255)) # R\n f.write(struct.pack('B', 255)) # G\n f.write(struct.pack('B', 255)) # B\n f.write(struct.pack('d', 0.0)) # error\n \n # Track (空)\n f.write(struct.pack('Q', 0)) # track length\n \n print(f\"✓ Written points3D.bin ({len(pts3d)} points)\")\n \n # --- 4. テキスト形式も書き出し (デバッグ用) ---\n write_text_versions(cameras_dict, pts3d, image_paths, output_dir, w, h, focal, cx, cy)\n \n print(f\"\\n✓ COLMAP sparse reconstruction saved (binary + text)\")\n print(f\" - Camera: PINHOLE\")\n print(f\" - Images: {len(image_paths)}\")\n print(f\" - Points: {len(pts3d)}\")\n print(f\" - Output: {output_dir}\")\n \n return output_dir\n\n\ndef write_text_versions(cameras_dict, pts3d, image_paths, output_dir, w, h, focal, cx, cy):\n \"\"\"テキスト形式も出力(デバッグ用)\"\"\"\n \n # cameras.txt\n with open(os.path.join(output_dir, 'cameras.txt'), 'w') as file:\n file.write(\"# Camera list with one line of data per camera:\\n\")\n file.write(\"# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\\n\")\n file.write(f\"1 PINHOLE {w} {h} {focal} {focal} {cx} {cy}\\n\")\n \n # images.txt\n with open(os.path.join(output_dir, 'images.txt'), 'w') as file:\n file.write(\"# Image list with two lines of data per image:\\n\")\n file.write(\"# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\\n\")\n file.write(\"# POINTS2D[] as (X, Y, POINT3D_ID)\\n\")\n \n for i, img_path in enumerate(image_paths):\n img_name = os.path.basename(img_path)\n cam_info = cameras_dict.get(i) or cameras_dict.get(str(i)) or cameras_dict.get(img_name)\n \n if cam_info is None:\n pose = np.eye(4)\n else:\n pose = cam_info['pose']\n \n try:\n w2c = np.linalg.inv(pose)\n except np.linalg.LinAlgError:\n w2c = np.eye(4)\n \n rot_mat = w2c[:3, :3]\n tvec = w2c[:3, 3]\n quat = R.from_matrix(rot_mat).as_quat()\n qw, qx, qy, qz = quat[3], quat[0], quat[1], quat[2]\n \n image_id = i + 1\n file.write(f\"{image_id} {qw} {qx} {qy} {qz} {tvec[0]} {tvec[1]} {tvec[2]} 1 {img_name}\\n\")\n file.write(\"\\n\")\n \n # points3D.txt\n with open(os.path.join(output_dir, 'points3D.txt'), 'w') as file:\n file.write(\"# 3D point list with one line of data per point:\\n\")\n file.write(\"# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[]\\n\")\n \n for point_id, point in enumerate(pts3d, start=1):\n file.write(f\"{point_id} {point[0]} {point[1]} {point[2]} 255 255 255 0.0\\n\")\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.405330Z","iopub.execute_input":"2026-01-22T06:24:09.405565Z","iopub.status.idle":"2026-01-22T06:24:09.425890Z","shell.execute_reply.started":"2026-01-22T06:24:09.405543Z","shell.execute_reply":"2026-01-22T06:24:09.425161Z"}},"outputs":[],"execution_count":43},{"cell_type":"code","source":"import os\nimport subprocess\n\ndef run_gaussian_splatting(source_dir, output_dir, iterations=30000):\n \"\"\"\n Gaussian Splattingを実行\n \n Args:\n source_dir: COLMAPデータのあるディレクトリ (sparse/0 と images を含む)\n output_dir: 出力ディレクトリ\n iterations: 学習イテレーション数\n \"\"\"\n print(\"\\n=== Running Gaussian Splatting ===\")\n \n # 出力ディレクトリを作成\n os.makedirs(output_dir, exist_ok=True)\n \n cmd = [\n \"python\", \"/kaggle/working/gaussian-splatting/train.py\",\n \"-s\", source_dir, # ソースディレクトリ (sparse/0とimagesを含む)\n \"-m\", output_dir, # モデル出力ディレクトリ\n \"--iterations\", str(iterations),\n \"--eval\"\n ]\n \n print(f\"Command: {' '.join(cmd)}\")\n print(f\" Source: {source_dir}\")\n print(f\" Output: {output_dir}\")\n \n # 実行\n result = subprocess.run(cmd, capture_output=False, text=True)\n \n if result.returncode == 0:\n print(f\"\\n✓ Gaussian Splatting complete\")\n \n # 生成されたファイルを確認\n point_cloud_dir = os.path.join(output_dir, \"point_cloud\")\n if os.path.exists(point_cloud_dir):\n print(f\"\\n✓ Point cloud directory found: {point_cloud_dir}\")\n \n # iteration_*フォルダを検索\n for item in sorted(os.listdir(point_cloud_dir)):\n item_path = os.path.join(point_cloud_dir, item)\n if os.path.isdir(item_path) and item.startswith(\"iteration_\"):\n ply_file = os.path.join(item_path, \"point_cloud.ply\")\n if os.path.exists(ply_file):\n file_size = os.path.getsize(ply_file) / (1024 * 1024) # MB\n print(f\" ✓ {item}/point_cloud.ply ({file_size:.2f} MB)\")\n else:\n print(f\"\\n⚠️ Warning: point_cloud directory not found\")\n print(f\" Expected: {point_cloud_dir}\")\n print(f\" Contents of {output_dir}:\")\n if os.path.exists(output_dir):\n for item in os.listdir(output_dir):\n print(f\" - {item}\")\n else:\n print(f\"\\n✗ Gaussian Splatting failed with return code {result.returncode}\")\n \n return output_dir\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.426720Z","iopub.execute_input":"2026-01-22T06:24:09.426959Z","iopub.status.idle":"2026-01-22T06:24:09.439526Z","shell.execute_reply.started":"2026-01-22T06:24:09.426935Z","shell.execute_reply":"2026-01-22T06:24:09.438794Z"}},"outputs":[],"execution_count":44},{"cell_type":"code","source":"def main_pipeline(image_dir, output_dir, square_size=1024, iterations=30000, \n max_images=200, max_pairs=100, max_points=500000, \n conf_threshold=1.5, preprocess_mode='none'):\n \"\"\"\n メインパイプライン(完全版)\n \n Args:\n image_dir: 入力画像ディレクトリ\n output_dir: 出力ディレクトリ\n square_size: Biplet前処理時の正方形サイズ\n iterations: Gaussian Splattingの反復回数\n max_images: 最大画像数\n max_pairs: 最大ペア数\n max_points: 最大点群数\n conf_threshold: Confidence閾値\n preprocess_mode: 前処理モード\n - 'none': 前処理なし(元画像をそのまま使用)\n - 'biplet': 2つの正方形クロップを生成(元画像も保存)\n \"\"\"\n \n # ======================================================================\n # STEP 0: Image Preprocessing (Optional)\n # ======================================================================\n if preprocess_mode == 'biplet':\n print(\"=\"*70)\n print(\"STEP 0: Image Preprocessing (Biplet Crops)\")\n print(\"=\"*70)\n \n # Bipletクロップを一時ディレクトリに生成\n temp_biplet_dir = os.path.join(output_dir, \"temp_biplet\")\n biplet_dir = normalize_image_sizes_biplet(\n image_dir,\n temp_biplet_dir,\n size=square_size\n )\n \n # Bipletクロップのみをimagesフォルダに移動\n images_dir = os.path.join(output_dir, \"images\")\n os.makedirs(images_dir, exist_ok=True)\n \n # _left, _right, _top, _bottom のファイルのみコピー\n biplet_suffixes = ['_left', '_right', '_top', '_bottom']\n copied_count = 0\n \n for img_file in os.listdir(temp_biplet_dir):\n if any(suffix in img_file for suffix in biplet_suffixes):\n src = os.path.join(temp_biplet_dir, img_file)\n dst = os.path.join(images_dir, img_file)\n shutil.copy2(src, dst)\n copied_count += 1\n \n print(f\"✓ Copied {copied_count} biplet images to {images_dir}\")\n \n # 元画像を別フォルダに保存(入力ディレクトリから直接コピー)\n original_images_dir = os.path.join(output_dir, \"original_images\")\n os.makedirs(original_images_dir, exist_ok=True)\n \n original_count = 0\n valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp')\n for img_file in os.listdir(image_dir):\n if img_file.lower().endswith(valid_extensions):\n src = os.path.join(image_dir, img_file)\n dst = os.path.join(original_images_dir, img_file)\n shutil.copy2(src, dst)\n original_count += 1\n \n print(f\"✓ Saved {original_count} original images to {original_images_dir}\")\n \n # 一時ディレクトリを削除\n shutil.rmtree(temp_biplet_dir)\n \n image_dir = images_dir\n clear_memory()\n else:\n # preprocess_mode == 'none'の場合、画像をimagesフォルダにコピー\n images_dir = os.path.join(output_dir, \"images\")\n if not os.path.exists(images_dir):\n print(\"=\"*70)\n print(\"STEP 0: Copying images to output directory\")\n print(\"=\"*70)\n shutil.copytree(image_dir, images_dir)\n print(f\"✓ Copied images to {images_dir}\")\n image_dir = images_dir\n \n # ======================================================================\n # STEP 1: Loading and Preparing Images\n # ======================================================================\n print(\"\\n\" + \"=\"*70)\n print(\"STEP 1: Loading and Preparing Images\")\n print(\"=\"*70)\n \n image_paths = load_images_from_directory(image_dir, max_images=max_images)\n print(f\"Loaded {len(image_paths)} images\")\n clear_memory()\n \n # ======================================================================\n # STEP 2: Image Pair Selection\n # ======================================================================\n print(\"\\n\" + \"=\"*70)\n print(\"STEP 2: Image Pair Selection\")\n print(\"=\"*70)\n \n max_pairs = min(max_pairs, 50)\n pairs = get_image_pairs_asmk(image_paths, max_pairs=max_pairs)\n print(f\"Selected {len(pairs)} image pairs\")\n clear_memory()\n \n # ======================================================================\n # STEP 3: MASt3R 3D Reconstruction\n # ======================================================================\n print(\"\\n\" + \"=\"*70)\n print(\"STEP 3: MASt3R 3D Reconstruction\")\n print(\"=\"*70)\n \n device = Config.DEVICE\n model = load_mast3r_model(device)\n \n scene, mast3r_images = run_mast3r_pairs(model, image_paths, pairs, device)\n \n # モデルを解放\n del model\n clear_memory()\n \n # ======================================================================\n # STEP 4: Converting to COLMAP (PINHOLE)\n # ======================================================================\n print(\"\\n\" + \"=\"*70)\n print(\"STEP 4: Converting to COLMAP (PINHOLE)\")\n print(\"=\"*70)\n \n cameras_dict, pts3d, confidence = extract_camera_params_process2(\n scene, image_paths, conf_threshold=conf_threshold\n )\n \n # sceneを解放\n del scene\n clear_memory()\n \n # 点数を制限\n if len(pts3d) > max_points:\n print(f\"⚠️ Limiting points from {len(pts3d)} to {max_points}\")\n indices = np.random.choice(len(pts3d), max_points, replace=False)\n pts3d = pts3d[indices]\n confidence = confidence[indices]\n \n print(f\"Final point count: {len(pts3d)}\")\n \n # COLMAP変換(バイナリ形式)\n colmap_dir = os.path.join(output_dir, \"sparse/0\")\n os.makedirs(colmap_dir, exist_ok=True)\n \n write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, colmap_dir)\n \n clear_memory()\n \n # ======================================================================\n # STEP 5: Running Gaussian Splatting\n # ======================================================================\n print(\"\\n\" + \"=\"*70)\n print(\"STEP 5: Running Gaussian Splatting\")\n print(\"=\"*70)\n \n # ソースディレクトリ(sparse/0とimagesを含む)\n source_dir = output_dir\n \n # モデル出力ディレクトリ\n model_output_dir = os.path.join(output_dir, \"gaussian_splatting\")\n \n gs_output = run_gaussian_splatting(\n source_dir=source_dir,\n output_dir=model_output_dir,\n iterations=iterations\n )\n \n # ======================================================================\n # STEP 6: Verify Output\n # ======================================================================\n print(\"\\n\" + \"=\"*70)\n print(\"PIPELINE COMPLETE\")\n print(\"=\"*70)\n \n # PLYファイルの確認\n ply_path = os.path.join(\n model_output_dir, \n \"point_cloud\", \n f\"iteration_{iterations}\", \n \"point_cloud.ply\"\n )\n \n if os.path.exists(ply_path):\n file_size = os.path.getsize(ply_path) / (1024 * 1024)\n print(f\"✓ Point cloud generated: {ply_path}\")\n print(f\" Size: {file_size:.2f} MB\")\n else:\n print(f\"⚠️ Point cloud not found at: {ply_path}\")\n print(f\"\\nChecking alternative locations...\")\n \n # 他のiterationフォルダを確認\n point_cloud_dir = os.path.join(model_output_dir, \"point_cloud\")\n if os.path.exists(point_cloud_dir):\n for item in sorted(os.listdir(point_cloud_dir)):\n item_path = os.path.join(point_cloud_dir, item)\n if os.path.isdir(item_path) and item.startswith(\"iteration_\"):\n ply_file = os.path.join(item_path, \"point_cloud.ply\")\n if os.path.exists(ply_file):\n file_size = os.path.getsize(ply_file) / (1024 * 1024)\n print(f\" Found: {item}/point_cloud.ply ({file_size:.2f} MB)\")\n \n print(f\"\\nOutput directory structure:\")\n print(f\" {output_dir}/\")\n print(f\" ├── images/ (processed images for training)\")\n if preprocess_mode == 'biplet':\n print(f\" ├── original_images/ (original source images)\")\n print(f\" ├── sparse/0/ (COLMAP data)\")\n print(f\" └── gaussian_splatting/ (GS output)\")\n \n return gs_output\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.440487Z","iopub.execute_input":"2026-01-22T06:24:09.440872Z","iopub.status.idle":"2026-01-22T06:24:09.459052Z","shell.execute_reply.started":"2026-01-22T06:24:09.440842Z","shell.execute_reply":"2026-01-22T06:24:09.458495Z"}},"outputs":[],"execution_count":45},{"cell_type":"markdown","source":" # ======================================================================\n # USAGE EXAMPLE\n # ======================================================================\n \n if __name__ == \"__main__\":\n IMAGE_DIR = \"/kaggle/input/your-dataset/images\"\n OUTPUT_DIR = \"/kaggle/working/output\"\n \n # 使用例1: 前処理なし(元画像をそのまま使用)\n gs_output = main_pipeline(\n image_dir=IMAGE_DIR,\n output_dir=OUTPUT_DIR,\n iterations=30000,\n max_images=100,\n max_pairs=50,\n max_points=300000,\n conf_threshold=1.5,\n preprocess_mode='none' # 前処理なし\n )\n \n # 使用例2: Bipletクロップ(画像数が2倍になる)\n gs_output = main_pipeline(\n image_dir=IMAGE_DIR,\n output_dir=OUTPUT_DIR,\n square_size=1024, # クロップサイズ\n iterations=30000,\n max_images=50, # Bipletで2倍になるので少なめに\n max_pairs=50,\n max_points=300000,\n conf_threshold=1.5,\n preprocess_mode='biplet' # 2つのクロップ生成\n )\n \n print(\"\\n\" + \"=\"*70)\n print(\"PIPELINE COMPLETE\")\n print(\"=\"*70)\n print(f\"Output directory: {gs_output}\")","metadata":{}},{"cell_type":"code","source":"print(f\"✓ np: {np.__version__} - {np.__file__}\")\n!pip show numpy | grep Version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:09.459798Z","iopub.execute_input":"2026-01-22T06:24:09.460091Z","iopub.status.idle":"2026-01-22T06:24:11.731872Z","shell.execute_reply.started":"2026-01-22T06:24:09.460070Z","shell.execute_reply":"2026-01-22T06:24:11.731121Z"}},"outputs":[{"name":"stdout","text":"✓ np: 1.26.4 - /usr/local/lib/python3.12/dist-packages/numpy/__init__.py\nVersion: 1.26.4\nVersion 3.1, 31 March 2009\n Version 3, 29 June 2007\n 5. Conveying Modified Source Versions.\n 14. Revised Versions of this License.\n","output_type":"stream"}],"execution_count":46},{"cell_type":"code","source":"# romaが必要な時点で確認・インストール\ntry:\n import roma\n print(\"✓ roma is installed\")\nexcept ModuleNotFoundError:\n print(\"⚠️ roma not found, installing...\")\n !pip install roma\n import roma\n print(\"✓ roma installed\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:11.733297Z","iopub.execute_input":"2026-01-22T06:24:11.733561Z","iopub.status.idle":"2026-01-22T06:24:11.738952Z","shell.execute_reply.started":"2026-01-22T06:24:11.733532Z","shell.execute_reply":"2026-01-22T06:24:11.738195Z"}},"outputs":[{"name":"stdout","text":"✓ roma is installed\n","output_type":"stream"}],"execution_count":47},{"cell_type":"code","source":"# ======================================================================\n# USAGE EXAMPLE\n# ======================================================================\n\nif __name__ == \"__main__\":\n IMAGE_DIR = \"/kaggle/input/two-dogs/fountain80/fountain80\"\n OUTPUT_DIR = \"/kaggle/working/output\"\n\n gs_output = main_pipeline(\n image_dir=IMAGE_DIR,\n output_dir=OUTPUT_DIR,\n square_size=1024,\n iterations=1000,\n max_images=10, #\n max_pairs=10,\n max_points=1000,\n conf_threshold=1.5,\n preprocess_mode='biplet' \n )\n \n print(\"\\n\" + \"=\"*70)\n print(\"PIPELINE COMPLETE\")\n print(\"=\"*70)\n print(f\"Output directory: {gs_output}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-22T06:24:11.739811Z","iopub.execute_input":"2026-01-22T06:24:11.740074Z","execution_failed":"2026-01-22T06:31:24.562Z"}},"outputs":[{"name":"stdout","text":"======================================================================\nSTEP 0: Image Preprocessing (Biplet Crops)\n======================================================================\n\n=== Generating Biplet Crops (512x512) ===\n","output_type":"stream"},{"name":"stderr","text":"Creating biplets: 100%|██████████| 80/80 [00:06<00:00, 11.79it/s]\n","output_type":"stream"},{"name":"stdout","text":"\n✓ Biplet generation complete:\n Source images: 80\n Biplet crops generated: 160\n Original size distribution: {'1440x1920': 80}\n✓ Copied 160 biplet images to /kaggle/working/output/images\n✓ Saved 80 original images to /kaggle/working/output/original_images\n\n======================================================================\nSTEP 1: Loading and Preparing Images\n======================================================================\n\nLoading images from: /kaggle/working/output/images\n⚠️ Limiting from 160 to 30 images\n✓ Found 30 images\nLoaded 30 images\n\n======================================================================\nSTEP 2: Image Pair Selection\n======================================================================\n\n=== Getting Image Pairs with ASMK ===\n\n=== Loading ASMK Retrieval Model ===\n⚠️ Failed to load MASt3R: tried to load naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric from huggingface, but failed\nTrying DUSt3R instead\n✓ Loaded DUSt3R model for retrieval\n✓ ASMK model loaded\n\n=== Extracting MASt3R Features ===\n","output_type":"stream"},{"name":"stderr","text":"Features: 0%| | 0/30 [00:00<?, ?it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A/kaggle/working/mast3r/dust3r/dust3r/inference.py:44: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n with torch.cuda.amp.autocast(enabled=bool(use_amp)):\n/kaggle/working/mast3r/dust3r/dust3r/model.py:206: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n with torch.cuda.amp.autocast(enabled=False):\n/kaggle/working/mast3r/dust3r/dust3r/inference.py:48: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n with torch.cuda.amp.autocast(enabled=False):\n\n100%|██████████| 1/1 [00:00<00:00, 3.63it/s]\u001b[A\nFeatures: 3%|▎ | 1/30 [00:00<00:08, 3.27it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_001_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_001_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 4.97it/s]\u001b[A\nFeatures: 7%|▋ | 2/30 [00:00<00:07, 3.88it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.26it/s]\u001b[A\nFeatures: 10%|█ | 3/30 [00:00<00:06, 4.20it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_002_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_002_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.16it/s]\u001b[A\nFeatures: 13%|█▎ | 4/30 [00:00<00:05, 4.36it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.13it/s]\u001b[A\nFeatures: 17%|█▋ | 5/30 [00:01<00:05, 4.45it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_003_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_003_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.08it/s]\u001b[A\nFeatures: 20%|██ | 6/30 [00:01<00:05, 4.47it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.13it/s]\u001b[A\nFeatures: 23%|██▎ | 7/30 [00:01<00:05, 4.50it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_004_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_004_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.10it/s]\u001b[A\nFeatures: 27%|██▋ | 8/30 [00:01<00:04, 4.52it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.12it/s]\u001b[A\nFeatures: 30%|███ | 9/30 [00:02<00:04, 4.54it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_005_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_005_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.04it/s]\u001b[A\nFeatures: 33%|███▎ | 10/30 [00:02<00:04, 4.51it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_006_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_006_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.12it/s]\u001b[A\nFeatures: 37%|███▋ | 11/30 [00:02<00:04, 4.50it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_006_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_006_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.05it/s]\u001b[A\nFeatures: 40%|████ | 12/30 [00:02<00:04, 4.47it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_007_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_007_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.13it/s]\u001b[A\nFeatures: 43%|████▎ | 13/30 [00:02<00:03, 4.49it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_007_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_007_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.06it/s]\u001b[A\nFeatures: 47%|████▋ | 14/30 [00:03<00:03, 4.49it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_008_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_008_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.06it/s]\u001b[A\nFeatures: 50%|█████ | 15/30 [00:03<00:03, 4.48it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_008_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_008_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.17it/s]\u001b[A\nFeatures: 53%|█████▎ | 16/30 [00:03<00:03, 4.51it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_009_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_009_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.10it/s]\u001b[A\nFeatures: 57%|█████▋ | 17/30 [00:03<00:02, 4.53it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_009_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_009_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.17it/s]\u001b[A\nFeatures: 60%|██████ | 18/30 [00:04<00:02, 4.55it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_010_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_010_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.09it/s]\u001b[A\nFeatures: 63%|██████▎ | 19/30 [00:04<00:02, 4.56it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_010_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_010_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.09it/s]\u001b[A\nFeatures: 67%|██████▋ | 20/30 [00:04<00:02, 4.56it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_011_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_011_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.15it/s]\u001b[A\nFeatures: 70%|███████ | 21/30 [00:04<00:01, 4.54it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_011_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_011_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.07it/s]\u001b[A\nFeatures: 73%|███████▎ | 22/30 [00:04<00:01, 4.53it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_012_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_012_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.04it/s]\u001b[A\nFeatures: 77%|███████▋ | 23/30 [00:05<00:01, 4.49it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_012_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_012_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.18it/s]\u001b[A\nFeatures: 80%|████████ | 24/30 [00:05<00:01, 4.51it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_013_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_013_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.10it/s]\u001b[A\nFeatures: 83%|████████▎ | 25/30 [00:05<00:01, 4.52it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_013_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_013_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.18it/s]\u001b[A\nFeatures: 87%|████████▋ | 26/30 [00:05<00:00, 4.56it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_014_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_014_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.14it/s]\u001b[A\nFeatures: 90%|█████████ | 27/30 [00:06<00:00, 4.57it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_014_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_014_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.09it/s]\u001b[A\nFeatures: 93%|█████████▎| 28/30 [00:06<00:00, 4.58it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_015_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_015_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.09it/s]\u001b[A\nFeatures: 97%|█████████▋| 29/30 [00:06<00:00, 4.56it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/images/image_015_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_015_top.jpeg with resolution 512x512 --> 224x224\n (Found 2 images)\n>> Inference with model on 1 image pairs\n","output_type":"stream"},{"name":"stderr","text":"\n 0%| | 0/1 [00:00<?, ?it/s]\u001b[A\n100%|██████████| 1/1 [00:00<00:00, 5.12it/s]\u001b[A\nFeatures: 100%|██████████| 30/30 [00:06<00:00, 4.48it/s]\n","output_type":"stream"},{"name":"stdout","text":"✓ Extracted features for 30 images\n Feature shape: torch.Size([224, 224, 3])\n\n=== Computing ASMK Similarity ===\nUsing ASMK with codebook size: 1024\n⚠️ ASMK failed: operands could not be broadcast together with shapes (50176,1,3) (1,1024,24) , using cosine similarity\nSimilarity matrix shape: (30, 30)\nSimilarity range: [-1.000, 1.000]\n✓ Built 148 unique pairs\nLimited to 5 pairs\nSelected 5 image pairs\n\n======================================================================\nSTEP 3: MASt3R 3D Reconstruction\n======================================================================\n\n=== Loading MASt3R Model ===\nAttempting to load: naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\n⚠️ Failed to load MASt3R: tried to load naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric from huggingface, but failed\nTrying DUSt3R instead: naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt\n✓ Loaded DUSt3R model as fallback\n✓ Model loaded on cuda\n\n=== Running MASt3R Reconstruction ===\nSelected 9 unique images from 5 pairs\n>> Loading a list of 9 images\n - adding /kaggle/working/output/images/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_002_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_003_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_009_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_011_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_012_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_012_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_013_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/images/image_014_bottom.jpeg with resolution 512x512 --> 224x224\n (Found 9 images)\nCreated 5 image pairs\nRunning inference on 5 pairs...\n>> Inference with model on 5 image pairs\n","output_type":"stream"},{"name":"stderr","text":"100%|██████████| 5/5 [00:01<00:00, 4.70it/s]\n","output_type":"stream"},{"name":"stdout","text":"✓ Processed 5 predictions\nRunning global alignment...\n init edge (5*,8*) score=20.55644416809082\n init edge (1*,5) score=13.340322494506836\n","output_type":"stream"}],"execution_count":null},{"cell_type":"code","source":"print(f\"✓ np: {np.__version__} - {np.__file__}\")\n!pip show numpy | grep Version","metadata":{"trusted":true,"execution":{"execution_failed":"2026-01-22T06:31:24.562Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}
|