stpete2 commited on
Commit
f845cd9
·
verified ·
1 Parent(s): 566e7e3

Upload biplet-asmk-mast3r-ps2-gs-kg-04.ipynb

Browse files
biplet-asmk-mast3r-ps2-gs-kg-04.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":14569969,"sourceType":"datasetVersion","datasetId":1429416}],"dockerImageVersionId":31259,"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\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-21T12:00:26.429317Z","iopub.execute_input":"2026-01-21T12:00:26.430203Z","iopub.status.idle":"2026-01-21T12:00:26.434010Z","shell.execute_reply.started":"2026-01-21T12:00:26.430167Z","shell.execute_reply":"2026-01-21T12:00:26.433301Z"}},"outputs":[],"execution_count":1},{"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-21T12:00:26.435531Z","iopub.execute_input":"2026-01-21T12:00:26.435824Z","iopub.status.idle":"2026-01-21T12:00:28.529448Z","shell.execute_reply.started":"2026-01-21T12:00:26.435792Z","shell.execute_reply":"2026-01-21T12:00:28.528767Z"}},"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":2},{"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-21T12:00:28.530681Z","iopub.execute_input":"2026-01-21T12:00:28.530951Z","iopub.status.idle":"2026-01-21T12:00:30.310084Z","shell.execute_reply.started":"2026-01-21T12:00:28.530922Z","shell.execute_reply":"2026-01-21T12:00:30.309382Z"}},"outputs":[{"name":"stdout","text":"✓ MASt3R already exists\n✓ DUSt3R already exists\n✓ ASMK already exists\nWarning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead\n✓ dust3r.model imported successfully\n","output_type":"stream"}],"execution_count":3},{"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-21T12:00:30.310921Z","iopub.execute_input":"2026-01-21T12:00:30.311292Z","iopub.status.idle":"2026-01-21T12:00:32.394852Z","shell.execute_reply.started":"2026-01-21T12:00:30.311266Z","shell.execute_reply":"2026-01-21T12:00:32.393876Z"}},"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":4},{"cell_type":"code","source":"\"\"\"\nComplete MASt3R to Gaussian Splatting Pipeline\nProcess2 Only - Memory Optimized Version\n\"\"\"\n\nimport 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\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 \"\"\"\n from PIL import Image\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\" Output images: {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 from PIL import Image\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\n\n# ======================================================================\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 n_images = len(image_paths)\n \n for idx in range(n_images):\n img_name = os.path.basename(image_paths[idx])\n \n try:\n # カメラパラメータを取得\n if hasattr(scene, 'im_poses'):\n pose = scene.im_poses[idx]\n elif hasattr(scene, 'get_im_poses'):\n pose = scene.get_im_poses()[idx]\n else:\n pose = torch.eye(4)\n \n if hasattr(scene, 'im_focals'):\n focal = scene.im_focals[idx]\n elif hasattr(scene, 'get_focals'):\n focal = scene.get_focals()[idx]\n else:\n focal = 1000.0\n \n if hasattr(scene, 'im_pp'):\n pp = scene.im_pp[idx]\n elif hasattr(scene, 'get_principal_points'):\n pp = scene.get_principal_points()[idx]\n else:\n pp = torch.tensor([112.0, 112.0])\n \n # テンソルをnumpyに変換\n if isinstance(pose, torch.Tensor):\n pose = pose.detach().cpu().numpy()\n if isinstance(focal, torch.Tensor):\n focal = focal.detach().cpu().item()\n if isinstance(pp, torch.Tensor):\n pp = pp.detach().cpu().numpy()\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'):\n pts3d_img = scene.im_pts3d[idx]\n elif hasattr(scene, 'get_pts3d'):\n pts3d_img = scene.get_pts3d()[idx]\n else:\n pts3d_img = None\n \n # Confidenceを取得\n if hasattr(scene, 'im_conf'):\n conf_img = scene.im_conf[idx]\n elif hasattr(scene, 'get_conf'):\n conf_img = scene.get_conf()[idx]\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 print(f\"✓ Confidence shape: {confidence.shape}\")\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\n\n\n# ======================================================================\n# COLMAP EXPORT\n# ======================================================================\n\ndef write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, output_dir):\n \"\"\"COLMAPフォーマットでスパース再構成を書き出し\"\"\"\n print(\"\\n=== Writing COLMAP Sparse Reconstruction ===\")\n \n import pycolmap\n from scipy.spatial.transform import Rotation\n \n os.makedirs(output_dir, exist_ok=True)\n \n # Reconstruction オブジェクトを作成\n reconstruction = pycolmap.Reconstruction()\n \n # カメラを追加\n camera = pycolmap.Camera(\n model='SIMPLE_PINHOLE',\n width=Config.IMAGE_SIZE,\n height=Config.IMAGE_SIZE,\n params=[1000.0, Config.IMAGE_SIZE/2, Config.IMAGE_SIZE/2]\n )\n camera_id = reconstruction.add_camera(camera)\n \n # 画像を追加\n for img_idx, img_path in enumerate(image_paths):\n img_name = os.path.basename(img_path)\n \n if img_name in cameras_dict:\n cam_params = cameras_dict[img_name]\n pose = cam_params['pose']\n \n # poseが1次元の場合のチェック\n if isinstance(pose, np.ndarray):\n if pose.ndim == 1:\n print(f\"⚠️ Warning: pose for {img_name} is 1D, using identity matrix\")\n pose = np.eye(4)\n elif pose.shape != (4, 4):\n print(f\"⚠️ Warning: pose for {img_name} has shape {pose.shape}, using identity matrix\")\n pose = np.eye(4)\n elif isinstance(pose, torch.Tensor):\n if pose.dim() == 1:\n print(f\"⚠️ Warning: pose for {img_name} is 1D tensor, using identity matrix\")\n pose = np.eye(4)\n else:\n pose = pose.cpu().numpy()\n if pose.shape != (4, 4):\n print(f\"⚠️ Warning: pose for {img_name} has shape {pose.shape}, using identity matrix\")\n pose = np.eye(4)\n else:\n print(f\"⚠️ Warning: pose for {img_name} has unexpected type {type(pose)}, using identity matrix\")\n pose = np.eye(4)\n \n # Rotation and translation\n R = pose[:3, :3]\n t = pose[:3, 3]\n \n # 回転行列が有効かチェック\n if not np.allclose(np.linalg.det(R), 1.0, atol=0.1):\n print(f\"⚠️ Warning: Invalid rotation matrix for {img_name}, using identity\")\n R = np.eye(3)\n t = np.zeros(3)\n \n try:\n # scipyを使って回転行列をクォータニオンに変換\n rot = Rotation.from_matrix(R)\n qvec = rot.as_quat() # [x, y, z, w]\n # COLMAPは [w, x, y, z] 形式\n qvec = np.array([qvec[3], qvec[0], qvec[1], qvec[2]])\n tvec = t\n \n # pycolmap.Imageオブジェクトを作成\n image = pycolmap.Image()\n image.name = img_name\n image.camera_id = camera_id\n \n # cam_from_world (R, t) を設定\n image.cam_from_world = pycolmap.Rigid3d(qvec, tvec)\n \n reconstruction.add_image(image)\n \n except Exception as e:\n print(f\"⚠️ Error adding image {img_name}: {e}\")\n # デフォルト値で追加を試みる\n try:\n image = pycolmap.Image()\n image.name = img_name\n image.camera_id = camera_id\n image.cam_from_world = pycolmap.Rigid3d()\n reconstruction.add_image(image)\n except Exception as e2:\n print(f\"⚠️ Failed to add image with default values: {e2}\")\n \n # 3D点を追加\n point_limit = min(len(pts3d), 100000)\n for i in range(point_limit):\n pt = pts3d[i]\n \n try:\n point = pycolmap.Point3D()\n point.xyz = pt\n point.color = np.array([128, 128, 128], dtype=np.uint8)\n point.error = float(1.0 - confidence[i] if i < len(confidence) else 1.0)\n reconstruction.add_point3D(point)\n except Exception as e:\n if i == 0: # 最初のエラーのみ表示\n print(f\"⚠️ Error adding 3D point: {e}\")\n continue\n \n # 保存\n try:\n reconstruction.write(output_dir)\n print(f\"✓ Wrote COLMAP reconstruction to: {output_dir}\")\n print(f\" - Cameras: {len(reconstruction.cameras)}\")\n print(f\" - Images: {len(reconstruction.images)}\")\n print(f\" - Points: {len(reconstruction.points3D)}\")\n except Exception as e:\n print(f\"⚠️ Error writing reconstruction: {e}\")\n print(f\" Attempting to write with minimal data...\")\n # 最小限のデータで保存を試みる\n reconstruction.write_text(output_dir)\n\n\n# ======================================================================\n# GAUSSIAN SPLATTING\n# ======================================================================\n\ndef run_gaussian_splatting(output_dir, iterations=30000):\n \"\"\"Gaussian Splattingを実行\"\"\"\n print(\"\\n=== Running Gaussian Splatting ===\")\n \n gs_source = output_dir\n gs_model = os.path.join(output_dir, \"output\")\n \n cmd = f\"\"\"\n python /kaggle/working/gaussian-splatting/train.py \\\n -s {gs_source} \\\n -m {gs_model} \\\n --iterations {iterations} \\\n --eval\n \"\"\"\n \n print(f\"Command: {cmd}\")\n os.system(cmd)\n \n print(f\"✓ Gaussian Splatting complete\")\n print(f\" Output: {gs_model}\")\n \n return gs_model\n\n\n# ======================================================================\n# MAIN PIPELINE\n# ======================================================================\n\ndef 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 メインパイプライン(Process2のみ、メモリ最適化版)\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つの正方形クロップを生成(画像数2倍)\n \"\"\"\n \n # 前処理\n if preprocess_mode == 'biplet':\n print(\"=\"*70)\n print(\"STEP 0: Image Preprocessing (Biplet Crops)\")\n print(\"=\"*70)\n preprocessed_dir = os.path.join(output_dir, \"preprocessed_biplet\")\n image_dir = normalize_image_sizes_biplet(\n image_dir,\n preprocessed_dir,\n size=square_size\n )\n clear_memory()\n \n print(\"=\"*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 \n clear_memory()\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 \n clear_memory()\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 print(\"\\n\" + \"=\"*70)\n print(\"STEP 4: Converting to COLMAP (Process2 Method)\")\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 print(\"\\n\" + \"=\"*70)\n print(\"STEP 5: Running Gaussian Splatting\")\n print(\"=\"*70)\n \n gs_output = run_gaussian_splatting(\n output_dir=output_dir,\n iterations=iterations\n )\n \n return gs_output","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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-21T12:00:32.526382Z","iopub.execute_input":"2026-01-21T12:00:32.526665Z","iopub.status.idle":"2026-01-21T12:00:34.719466Z","shell.execute_reply.started":"2026-01-21T12:00:32.526626Z","shell.execute_reply":"2026-01-21T12:00:34.718740Z"}},"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":6},{"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=512,\n iterations=3000,\n max_images=10, #\n max_pairs=10,\n max_points=3000,\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-21T12:00:34.720740Z","iopub.execute_input":"2026-01-21T12:00:34.720984Z","iopub.status.idle":"2026-01-21T12:01:06.953257Z","shell.execute_reply.started":"2026-01-21T12:00:34.720956Z","shell.execute_reply":"2026-01-21T12:01:06.952172Z"}},"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, 12.05it/s]\n","output_type":"stream"},{"name":"stdout","text":"\n✓ Biplet generation complete:\n Source images: 80\n Output images: 160\n Original size distribution: {'1440x1920': 80}\n======================================================================\nSTEP 1: Loading and Preparing Images\n======================================================================\n\nLoading images from: /kaggle/working/output/preprocessed_biplet\n⚠️ Limiting from 160 to 10 images\n✓ Found 10 images\nLoaded 10 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/10 [00:00<?, ?it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 1.79it/s]\u001b[A\nFeatures: 10%|█ | 1/10 [00:00<00:05, 1.67it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_001_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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.55it/s]\u001b[A\nFeatures: 20%|██ | 2/10 [00:00<00:03, 2.57it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.76it/s]\u001b[A\nFeatures: 30%|███ | 3/10 [00:01<00:02, 3.13it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_002_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.69it/s]\u001b[A\nFeatures: 40%|████ | 4/10 [00:01<00:01, 3.49it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.75it/s]\u001b[A\nFeatures: 50%|█████ | 5/10 [00:01<00:01, 3.73it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_003_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.75it/s]\u001b[A\nFeatures: 60%|██████ | 6/10 [00:01<00:01, 3.90it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.72it/s]\u001b[A\nFeatures: 70%|███████ | 7/10 [00:02<00:00, 4.00it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_004_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.73it/s]\u001b[A\nFeatures: 80%|████████ | 8/10 [00:02<00:00, 4.08it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.56it/s]\u001b[A\nFeatures: 90%|█████████ | 9/10 [00:02<00:00, 4.10it/s]","output_type":"stream"},{"name":"stdout","text":">> Loading a list of 2 images\n - adding /kaggle/working/output/preprocessed_biplet/image_005_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/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, 4.72it/s]\u001b[A\nFeatures: 100%|██████████| 10/10 [00:02<00:00, 3.66it/s]\n","output_type":"stream"},{"name":"stdout","text":"✓ Extracted features for 10 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: (10, 10)\nSimilarity range: [-1.000, 1.000]\n✓ Built 45 unique pairs\nLimited to 10 pairs\nSelected 10 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 ===\n","output_type":"stream"},{"name":"stderr","text":"/kaggle/working/mast3r/dust3r/dust3r/cloud_opt/base_opt.py:275: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n @torch.cuda.amp.autocast(enabled=False)\n","output_type":"stream"},{"name":"stdout","text":"Selected 10 unique images from 10 pairs\n>> Loading a list of 10 images\n - adding /kaggle/working/output/preprocessed_biplet/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_001_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_002_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_003_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_004_top.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n - adding /kaggle/working/output/preprocessed_biplet/image_005_top.jpeg with resolution 512x512 --> 224x224\n (Found 10 images)\nCreated 10 image pairs\nRunning inference on 10 pairs...\n>> Inference with model on 10 image pairs\n","output_type":"stream"},{"name":"stderr","text":" 0%| | 0/10 [00:00<?, ?it/s]/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):\n100%|██████████| 10/10 [00:02<00:00, 4.48it/s]\n","output_type":"stream"},{"name":"stdout","text":"✓ Processed 5 predictions\nRunning global alignment...\n init edge (0*,2*) score=24.667621612548828\n init edge (0,8*) score=21.67432975769043\n init edge (0,5*) score=11.146766662597656\n init edge (5,7*) score=11.700783729553223\n init edge (3*,7) score=19.910110473632812\n init edge (3,4*) score=18.220979690551758\n init edge (4,6*) score=16.17308807373047\n init edge (1*,6) score=8.707744598388672\n init edge (4,9*) score=6.044977188110352\n init loss = 0.01797846145927906\nGlobal alignement - optimizing for:\n['pw_poses', 'im_depthmaps', 'im_poses', 'im_focals']\n","output_type":"stream"},{"name":"stderr","text":" 0%| | 0/50 [00:00<?, ?it/s]/kaggle/working/mast3r/dust3r/dust3r/cloud_opt/base_opt.py:366: UserWarning: Converting a tensor with requires_grad=True to a scalar may lead to unexpected behavior.\nConsider using tensor.detach() first. (Triggered internally at /pytorch/torch/csrc/autograd/generated/python_variable_methods.cpp:835.)\n return float(loss), lr\n100%|██████████| 50/50 [00:01<00:00, 45.22it/s, lr=1.08654e-05 loss=0.0132409]\n","output_type":"stream"},{"name":"stdout","text":"✓ Alignment complete (loss: 0.013241)\n\n======================================================================\nSTEP 4: Converting to COLMAP (Process2 Method)\n======================================================================\n\n=== Extracting Camera Parameters (Process2) ===\n✓ Extracted camera parameters for 10 images\n✓ Total 3D points: 501760\n✓ Confidence shape: (501760,)\n✓ After confidence filtering (>1.5): 468348 points\n⚠️ Limiting points from 468348 to 3000\nFinal point count: 3000\n\n=== Writing COLMAP Sparse Reconstruction ===\n⚠️ Warning: pose for image_001_bottom.jpeg is 1D, using identity matrix\n⚠️ Error adding image image_001_bottom.jpeg: module 'pycolmap' has no attribute 'rotmat_to_qvec'\n","output_type":"stream"},{"name":"stderr","text":"E20260121 12:01:06.943480 134646666695808 helpers.h:111] Internal AttributeError: 'pycolmap._core.Image' object has no attribute 'id'\n","output_type":"stream"},{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m/tmp/ipykernel_411/1711296541.py\u001b[0m in \u001b[0;36mwrite_colmap_sparse\u001b[0;34m(cameras_dict, pts3d, confidence, image_paths, output_dir)\u001b[0m\n\u001b[1;32m 824\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 825\u001b[0;31m \u001b[0mqvec\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpycolmap\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrotmat_to_qvec\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mR\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 826\u001b[0m \u001b[0mtvec\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mAttributeError\u001b[0m: module 'pycolmap' has no attribute 'rotmat_to_qvec'","\nDuring handling of the above exception, another exception occurred:\n","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m/tmp/ipykernel_411/3313817172.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mOUTPUT_DIR\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"/kaggle/working/output\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m gs_output = main_pipeline(\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0mimage_dir\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mIMAGE_DIR\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0moutput_dir\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mOUTPUT_DIR\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/tmp/ipykernel_411/1711296541.py\u001b[0m in \u001b[0;36mmain_pipeline\u001b[0;34m(image_dir, output_dir, square_size, iterations, max_images, max_pairs, max_points, conf_threshold, preprocess_mode)\u001b[0m\n\u001b[1;32m 992\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmakedirs\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcolmap_dir\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mexist_ok\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 993\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 994\u001b[0;31m \u001b[0mwrite_colmap_sparse\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcameras_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpts3d\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mconfidence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mimage_paths\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcolmap_dir\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 995\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 996\u001b[0m \u001b[0mclear_memory\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/tmp/ipykernel_411/1711296541.py\u001b[0m in \u001b[0;36mwrite_colmap_sparse\u001b[0;34m(cameras_dict, pts3d, confidence, image_paths, output_dir)\u001b[0m\n\u001b[1;32m 839\u001b[0m \u001b[0;31m# デフォルト値で追加\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 840\u001b[0m reconstruction.add_image(\n\u001b[0;32m--> 841\u001b[0;31m pycolmap.Image(\n\u001b[0m\u001b[1;32m 842\u001b[0m \u001b[0mid\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mimg_idx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 843\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mimg_name\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mAttributeError\u001b[0m: 'pycolmap._core.Image' object has no attribute 'id'"],"ename":"AttributeError","evalue":"'pycolmap._core.Image' object has no attribute 'id'","output_type":"error"}],"execution_count":7},{"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-21T12:01:06.953820Z","iopub.status.idle":"2026-01-21T12:01:06.954089Z","shell.execute_reply.started":"2026-01-21T12:01:06.953972Z","shell.execute_reply":"2026-01-21T12:01:06.953987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}