File size: 120,983 Bytes
1b4d259
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"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14628798,"sourceType":"datasetVersion","datasetId":1429416}],"dockerImageVersionId":31260,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"colab":{"provenance":[],"gpuType":"T4"},"accelerator":"GPU"},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"id":"yhVNR6GETKyA"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### **ps2p means revised extract_camera_params_process2 and includes color infomation**","metadata":{}},{"cell_type":"code","source":"# =====================================================================\n# biplet_dino_mast3r_ps2_gs_colab_01.ipynb\n# ASMK を DINO に置き換えたバージョン\n# =====================================================================\n\n# =====================================================================\n# CELL 1: Install Dependencies\n# =====================================================================\n!pip install roma einops timm huggingface_hub\n!pip install opencv-python pillow tqdm pyaml cython plyfile\n!pip install pycolmap trimesh\n!pip install transformers==4.40.0  # DINOに必要\n!pip uninstall -y numpy scipy\n!pip install numpy==1.26.4 scipy==1.11.4\nbreak","metadata":{"trusted":true,"id":"6C3QGJD8TKyC","outputId":"b362f97d-fbc1-474f-f2cb-b84b565acdb9"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"id":"TPcj5qcmedBw","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# restart & run after\n# =====================================================================\n# CELL 2: Mount Drive and Verify\n# =====================================================================\n\nimport numpy as np\nprint(f\"✓ np: {np.__version__} - {np.__file__}\")\n!pip show numpy | grep Version\n\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\")\n\n# =====================================================================\n# CELL 3: Clone Repositories\n# =====================================================================\nimport 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# パスを追加\nsys.path.insert(0, '/kaggle/working/mast3r')\nsys.path.insert(0, '/kaggle/working/mast3r/dust3r')\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# =====================================================================\n# CELL 4: Clone and Build Gaussian Splatting\n# =====================================================================\nprint(\"\\n\" + \"=\"*70)\nprint(\"STEP: 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    subprocess.run([\"pip\", \"install\", path], check=True)\n\nprint(\"✓ Custom CUDA modules installed.\")\n\nprint(f\"✓ np: {np.__version__} - {np.__file__}\")\n!pip show numpy | grep Version\n\n# =====================================================================\n# CELL 5: Import Core Libraries and Configure Memory\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\nimport shutil\nfrom PIL import Image\nfrom transformers import AutoImageProcessor, AutoModel\n\n# MEMORY MANAGEMENT\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\ndef get_memory_info():\n    \"\"\"Get current memory usage\"\"\"\n    if torch.cuda.is_available():\n        allocated = torch.cuda.memory_allocated() / 1024**3\n        reserved = torch.cuda.memory_reserved() / 1024**3\n        print(f\"GPU Memory - Allocated: {allocated:.2f}GB, Reserved: {reserved:.2f}GB\")\n\n    import psutil\n    cpu_mem = psutil.virtual_memory().percent\n    print(f\"CPU Memory Usage: {cpu_mem:.1f}%\")\n\n# CONFIGURATION\nclass Config:\n    DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n    MAST3R_WEIGHTS = \"naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\"\n    DUST3R_WEIGHTS = \"naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt\"\n\n    # DINO設定\n    DINO_MODEL = \"facebook/dinov2-base\"\n    GLOBAL_TOPK = 20  # 各画像がペアを組む上位K個\n\n    IMAGE_SIZE = 224\n\n# =====================================================================\n# CELL 6: Image Preprocessing Functions (Biplet)\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    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    \"\"\"\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    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# CELL 7: Image Loading Function\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# CELL 8: MASt3R Model Loading\n# =====================================================================\ndef load_mast3r_model(device):\n    \"\"\"MASt3Rモデルをロード\"\"\"\n    print(\"\\n=== Loading MASt3R Model ===\")\n\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        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        model = AsymmetricCroCo3DStereo.from_pretrained(Config.DUST3R_WEIGHTS).to(device)\n        print(\"✓ Loaded DUSt3R model as fallback\")\n\n    model.eval()\n    print(f\"✓ Model loaded on {device}\")\n    return model\n\n# =====================================================================\n# CELL 9: DINO Pair Selection (REPLACES ASMK)\n# =====================================================================\ndef load_torch_image(fname, device):\n    \"\"\"Load image as torch tensor\"\"\"\n    import torchvision.transforms as T\n\n    img = Image.open(fname).convert('RGB')\n    transform = T.Compose([\n        T.ToTensor(),\n    ])\n    return transform(img).unsqueeze(0).to(device)\n\ndef extract_dino_global(image_paths, model_path, device):\n    \"\"\"Extract DINO global descriptors with memory management\"\"\"\n    print(\"\\n=== Extracting DINO Global Features ===\")\n    print(\"Initial memory state:\")\n    get_memory_info()\n\n    processor = AutoImageProcessor.from_pretrained(model_path)\n    model = AutoModel.from_pretrained(model_path).eval().to(device)\n\n    global_descs = []\n    batch_size = 4  # Small batch to save memory\n\n    for i in tqdm(range(0, len(image_paths), batch_size), desc=\"DINO extraction\"):\n        batch_paths = image_paths[i:i+batch_size]\n        batch_imgs = []\n\n        for img_path in batch_paths:\n            img = load_torch_image(img_path, device)\n            batch_imgs.append(img)\n\n        batch_tensor = torch.cat(batch_imgs, dim=0)\n\n        with torch.no_grad():\n            inputs = processor(images=batch_tensor, return_tensors=\"pt\", do_rescale=False).to(device)\n            outputs = model(**inputs)\n            desc = F.normalize(outputs.last_hidden_state[:, 1:].max(dim=1)[0], dim=1, p=2)\n            global_descs.append(desc.cpu())\n\n        # Clear batch memory\n        del batch_tensor, inputs, outputs, desc\n        clear_memory()\n\n    global_descs = torch.cat(global_descs, dim=0)\n\n    del model, processor\n    clear_memory()\n\n    print(\"After DINO extraction:\")\n    get_memory_info()\n\n    return global_descs\n\ndef build_topk_pairs(global_feats, k, device):\n    \"\"\"Build top-k similar pairs from global features\"\"\"\n    g = global_feats.to(device)\n    sim = g @ g.T\n    sim.fill_diagonal_(-1)\n\n    N = sim.size(0)\n    k = min(k, N - 1)\n\n    topk_indices = torch.topk(sim, k, dim=1).indices.cpu()\n\n    pairs = []\n    for i in range(N):\n        for j in topk_indices[i]:\n            j = j.item()\n            if i < j:\n                pairs.append((i, j))\n\n    # Remove duplicates\n    pairs = list(set(pairs))\n\n    return pairs\n\ndef select_diverse_pairs(pairs, max_pairs, num_images):\n    \"\"\"\n    Select diverse pairs to ensure good image coverage\n    \"\"\"\n    import random\n    random.seed(42)\n\n    if len(pairs) <= max_pairs:\n        return pairs\n\n    print(f\"Selecting {max_pairs} diverse pairs from {len(pairs)} candidates...\")\n\n    # Count how many times each image appears in pairs\n    image_counts = {i: 0 for i in range(num_images)}\n    for i, j in pairs:\n        image_counts[i] += 1\n        image_counts[j] += 1\n\n    # Sort pairs by: prefer pairs with less-connected images\n    def pair_score(pair):\n        i, j = pair\n        return image_counts[i] + image_counts[j]\n\n    pairs_scored = [(pair, pair_score(pair)) for pair in pairs]\n    pairs_scored.sort(key=lambda x: x[1])\n\n    # Select pairs greedily to maximize coverage\n    selected = []\n    selected_images = set()\n\n    # Phase 1: Select pairs that add new images\n    for pair, score in pairs_scored:\n        if len(selected) >= max_pairs:\n            break\n        i, j = pair\n        if i not in selected_images or j not in selected_images:\n            selected.append(pair)\n            selected_images.add(i)\n            selected_images.add(j)\n\n    # Phase 2: Fill remaining slots\n    if len(selected) < max_pairs:\n        remaining = [p for p, s in pairs_scored if p not in selected]\n        random.shuffle(remaining)\n        selected.extend(remaining[:max_pairs - len(selected)])\n\n    print(f\"Selected pairs cover {len(selected_images)} / {num_images} images ({100*len(selected_images)/num_images:.1f}%)\")\n\n    return selected\n\ndef get_image_pairs_dino(image_paths, max_pairs=None):\n    \"\"\"DINO-based pair selection\"\"\"\n    device = Config.DEVICE\n\n    # DINO global features\n    global_feats = extract_dino_global(image_paths, Config.DINO_MODEL, device)\n    pairs = build_topk_pairs(global_feats, Config.GLOBAL_TOPK, device)\n\n    print(f\"Initial pairs from DINO: {len(pairs)}\")\n\n    # Apply intelligent pair selection if limit specified\n    if max_pairs and len(pairs) > max_pairs:\n        pairs = select_diverse_pairs(pairs, max_pairs, len(image_paths))\n\n    return pairs\n\n# =====================================================================\n# CELL 10: MASt3R Reconstruction\n# =====================================================================\ndef run_mast3r_pairs(model, image_paths, pairs, device, batch_size=1, max_pairs=None):\n    \"\"\"Run MASt3R on selected pairs with memory management\"\"\"\n    print(\"\\n=== Running MASt3R Reconstruction ===\")\n    print(\"Initial memory state:\")\n    get_memory_info()\n\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    # Limit number of pairs if specified\n    if max_pairs and len(pairs) > max_pairs:\n        print(f\"Limiting pairs from {len(pairs)} to {max_pairs}\")\n        step = max(1, len(pairs) // max_pairs)\n        pairs = pairs[::step][:max_pairs]\n\n    print(f\"Processing {len(pairs)} pairs...\")\n\n    # Load images in smaller size\n    print(f\"Loading {len(image_paths)} images at {Config.IMAGE_SIZE}x{Config.IMAGE_SIZE}...\")\n    images = load_images(image_paths, size=Config.IMAGE_SIZE)\n\n    print(f\"Loaded {len(images)} images\")\n    print(\"After loading images:\")\n    get_memory_info()\n\n    # Create all image pairs\n    print(f\"Creating {len(pairs)} image pairs...\")\n    mast3r_pairs = []\n    for idx1, idx2 in tqdm(pairs, desc=\"Preparing pairs\"):\n        mast3r_pairs.append((images[idx1], images[idx2]))\n\n    print(f\"Running MASt3R inference on {len(mast3r_pairs)} pairs...\")\n\n    # Run inference\n    output = inference(mast3r_pairs, model, device, batch_size=batch_size, verbose=True)\n\n    del mast3r_pairs\n    clear_memory()\n\n    print(\"✓ MASt3R inference complete\")\n    print(\"After inference:\")\n    get_memory_info()\n\n    # Global alignment\n    print(\"Running global alignment...\")\n    scene = global_aligner(\n        output,\n        device=device,\n        mode=GlobalAlignerMode.PointCloudOptimizer\n    )\n\n    del output\n    clear_memory()\n\n    print(\"Computing global alignment...\")\n    loss = scene.compute_global_alignment(\n        init=\"mst\",\n        niter=50,  # Reduced iterations\n        schedule='cosine',\n        lr=0.01\n    )\n\n    print(f\"✓ Global alignment complete (final loss: {loss:.6f})\")\n    print(\"Final memory state:\")\n    get_memory_info()\n\n    return scene, images\n\n\n\n","metadata":{"trusted":true,"id":"OWJEB1oQTKyD","outputId":"fa123527-2b15-4fa5-8d3c-c830ccc43365","execution":{"iopub.status.busy":"2026-02-01T07:13:59.804995Z","iopub.execute_input":"2026-02-01T07:13:59.805314Z","iopub.status.idle":"2026-02-01T07:17:30.292541Z","shell.execute_reply.started":"2026-02-01T07:13:59.805287Z","shell.execute_reply":"2026-02-01T07:17:30.291526Z"}},"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✓ roma is installed\nCloning MASt3R repository...\nCloning into '/kaggle/working/mast3r'...\nremote: Enumerating objects: 269, done.\u001b[K\nremote: Counting objects: 100% (170/170), done.\u001b[K\nremote: Compressing objects: 100% (61/61), done.\u001b[K\nremote: Total 269 (delta 115), reused 109 (delta 109), pack-reused 99 (from 1)\u001b[K\nReceiving objects: 100% (269/269), 3.59 MiB | 10.19 MiB/s, done.\nResolving deltas: 100% (151/151), done.\nSubmodule 'dust3r' (https://github.com/naver/dust3r) registered for path 'dust3r'\nCloning into '/kaggle/working/mast3r/dust3r'...\nremote: Enumerating objects: 611, done.        \nremote: Total 611 (delta 0), reused 0 (delta 0), pack-reused 611 (from 1)        \nReceiving objects: 100% (611/611), 756.60 KiB | 2.65 MiB/s, done.\nResolving deltas: 100% (355/355), done.\nSubmodule path 'dust3r': checked out '3cc8c88c413bb9e34c41db0e0eef99c2ee010b12'\nSubmodule 'croco' (https://github.com/naver/croco) registered for path 'dust3r/croco'\nCloning into '/kaggle/working/mast3r/dust3r/croco'...\nremote: Enumerating objects: 198, done.        \nremote: Counting objects: 100% (87/87), done.        \nremote: Compressing objects: 100% (54/54), done.        \nremote: Total 198 (delta 54), reused 33 (delta 33), pack-reused 111 (from 1)        \nReceiving objects: 100% (198/198), 403.93 KiB | 2.28 MiB/s, done.\nResolving deltas: 100% (94/94), done.\nSubmodule path 'dust3r/croco': checked out 'd7de0705845239092414480bd829228723bf20de'\n✓ MASt3R cloned\n✓ DUSt3R already exists\nWarning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead\n✓ dust3r.model imported successfully\nCloning CroCo repository...\nCloning into '/kaggle/working/mast3r/croco'...\nremote: Enumerating objects: 198, done.\u001b[K\nremote: Counting objects: 100% (87/87), done.\u001b[K\nremote: Compressing objects: 100% (54/54), done.\u001b[K\nremote: Total 198 (delta 54), reused 33 (delta 33), pack-reused 111 (from 1)\u001b[K\nReceiving objects: 100% (198/198), 403.93 KiB | 2.28 MiB/s, done.\nResolving deltas: 100% (94/94), done.\n✓ CroCo cloned\n\n======================================================================\nSTEP: Clone Gaussian Splatting\n======================================================================\n✓ Cloned\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=3457000 sha256=6cd46ff194764b233975640619619a19903f620f43daf5be8cc747241a4889e6\n  Stored in directory: /root/.cache/pip/wheels/ba/99/d3/014520068aca8c2e8bdc358ca774581380cadb65788559b3ea\nSuccessfully built diff_gaussian_rasterization\nInstalling collected packages: diff_gaussian_rasterization\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=3209861 sha256=b31752d43022c3690e53aeaa1243d28f1988ce457b1d18ae38d78dcfc0315cc5\n  Stored in directory: /root/.cache/pip/wheels/ca/30/df/7f4f362d12edead48c699acde5962cbb06ca05033b9d970934\nSuccessfully built simple_knn\nInstalling collected packages: simple_knn\nSuccessfully installed simple_knn-0.0.0\n✓ Custom CUDA modules installed.\n✓ 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"},{"name":"stderr","text":"2026-02-01 07:17:19.374015: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\nWARNING: All log messages before absl::InitializeLog() is called are written to STDERR\nE0000 00:00:1769930239.543895     141 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\nE0000 00:00:1769930239.599685     141 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\nW0000 00:00:1769930240.004523     141 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\nW0000 00:00:1769930240.004565     141 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\nW0000 00:00:1769930240.004568     141 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\nW0000 00:00:1769930240.004570     141 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","output_type":"stream"}],"execution_count":1},{"cell_type":"markdown","source":"# process2","metadata":{}},{"cell_type":"code","source":"\nimport struct\nimport numpy as np\nfrom pathlib import Path\n\ndef rotmat_to_qvec(R):\n    \"\"\"回転行列をクォータニオンに変換\"\"\"\n    R = np.asarray(R, dtype=np.float64)\n    trace = np.trace(R)\n\n    if trace > 0:\n        s = 0.5 / np.sqrt(trace + 1.0)\n        w = 0.25 / s\n        x = (R[2, 1] - R[1, 2]) * s\n        y = (R[0, 2] - R[2, 0]) * s\n        z = (R[1, 0] - R[0, 1]) * s\n    elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:\n        s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])\n        w = (R[2, 1] - R[1, 2]) / s\n        x = 0.25 * s\n        y = (R[0, 1] + R[1, 0]) / s\n        z = (R[0, 2] + R[2, 0]) / s\n    elif R[1, 1] > R[2, 2]:\n        s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])\n        w = (R[0, 2] - R[2, 0]) / s\n        x = (R[0, 1] + R[1, 0]) / s\n        y = 0.25 * s\n        z = (R[1, 2] + R[2, 1]) / s\n    else:\n        s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])\n        w = (R[1, 0] - R[0, 1]) / s\n        x = (R[0, 2] + R[2, 0]) / s\n        y = (R[1, 2] + R[2, 1]) / s\n        z = 0.25 * s\n\n    qvec = np.array([w, x, y, z], dtype=np.float64)\n    qvec = qvec / np.linalg.norm(qvec)\n\n    return qvec\n\n\ndef write_cameras_binary(cameras_dict, image_size, output_file):\n    \"\"\"\n    cameras.binを出力(PINHOLEモデル使用)\n    \"\"\"\n    width, height = image_size\n    num_cameras = len(cameras_dict)\n\n    # COLMAP camera models\n    PINHOLE = 1  # 🔧 SIMPLE_PINHOLE (0) から PINHOLE (1) に変更\n\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', num_cameras))\n\n        for camera_id, (img_id, cam_params) in enumerate(cameras_dict.items(), start=1):\n            focal = cam_params['focal']\n\n            # PINHOLEの場合: fx, fy, cx, cy\n            #fx = fy = focal  # 等方性カメラを仮定\n            \n            #new settiing 2026/01/26\n            if isinstance(focal, (tuple, list)):\n                fx, fy = focal\n            else:\n                fx = fy = focal\n            \n\n            # Principal pointを取得(存在しない場合は中心)\n            if 'pp' in cam_params:\n                pp = cam_params['pp']\n                cx = float(pp[0])\n                cy = float(pp[1])\n            else:\n                cx = width / 2.0\n                cy = height / 2.0\n\n            # camera_id\n            f.write(struct.pack('I', camera_id))\n            # model_id (PINHOLE = 1)\n            f.write(struct.pack('i', PINHOLE))\n            # width\n            f.write(struct.pack('Q', width))\n            # height\n            f.write(struct.pack('Q', height))\n            # params: fx, fy, cx, cy (4パラメータ)\n            f.write(struct.pack('d', fx))\n            f.write(struct.pack('d', fy))\n            f.write(struct.pack('d', cx))\n            f.write(struct.pack('d', cy))\n\n    print(f\"COLMAP cameras.bin saved to {output_file}\")\n\n\ndef write_images_binary(cameras_dict, output_file):\n    \"\"\"images.binを出力\"\"\"\n    num_images = len(cameras_dict)\n\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', num_images))\n\n        for image_id, (img_id, cam_params) in enumerate(cameras_dict.items(), start=1):\n            R = cam_params['rotation']\n            quat = rotmat_to_qvec(R)\n            t = cam_params['translation']\n            camera_id = image_id\n\n            f.write(struct.pack('I', image_id))\n            for q in quat:\n                f.write(struct.pack('d', q))\n            for ti in t:\n                f.write(struct.pack('d', ti))\n            f.write(struct.pack('I', camera_id))\n\n            name_bytes = img_id.encode('utf-8') + b'\\x00'\n            f.write(name_bytes)\n            f.write(struct.pack('Q', 0))\n\n    print(f\"COLMAP images.bin saved to {output_file}\")\n\n\ndef write_points3D_binary(pts3d, confidence, output_file):\n    \"\"\"points3D.binを出力\"\"\"\n    num_points = len(pts3d)\n\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', num_points))\n\n        for point_id, pt in enumerate(pts3d, start=1):\n            x, y, z = pt\n\n            f.write(struct.pack('Q', point_id))\n            f.write(struct.pack('d', x))\n            f.write(struct.pack('d', y))\n            f.write(struct.pack('d', z))\n\n            # RGB (グレー)\n            f.write(struct.pack('B', 128))\n            f.write(struct.pack('B', 128))\n            f.write(struct.pack('B', 128))\n\n            # error\n            if confidence is not None and point_id <= len(confidence):\n                error = 1.0 / max(confidence[point_id-1], 0.001)\n            else:\n                error = 1.0\n            f.write(struct.pack('d', error))\n\n            # track_length\n            f.write(struct.pack('Q', 0))\n\n    print(f\"COLMAP points3D.bin saved to {output_file}\")\n\n\ndef export_colmap_binary(cameras_dict, pts3d, confidence, image_size, output_dir):\n    \"\"\"COLMAPバイナリファイルを出力\"\"\"\n    output_path = Path(output_dir)\n    output_path.mkdir(parents=True, exist_ok=True)\n\n    write_cameras_binary(\n        cameras_dict,\n        image_size,\n        output_path / 'cameras.bin'\n    )\n\n    write_images_binary(\n        cameras_dict,\n        output_path / 'images.bin'\n    )\n\n    write_points3D_binary(\n        pts3d,\n        confidence,\n        output_path / 'points3D.bin'\n    )\n\n    print(f\"\\nCOLMAP binary files exported to {output_dir}/\")\n    print(f\"  - cameras.bin: {len(cameras_dict)} cameras (PINHOLE model)\")\n    print(f\"  - images.bin: {len(cameras_dict)} images\")\n    print(f\"  - points3D.bin: {len(pts3d)} points\")\n\n\n# =====================================================================\n# CELL 11: Camera Parameter Extraction (REVISED 2026/01/26)\n# =====================================================================\ndef extract_camera_params_process2(scene, image_paths, conf_threshold=1.5):\n    \"\"\"\n    Extracts camera parameters and 3D points from the scene (FIXED: proper fx, fy handling).\n    \"\"\"\n    print(\"\\n=== Extracting Camera Parameters ===\")\n\n    cameras_dict = {}\n    all_pts3d = []\n    all_confidence = []\n\n    try:\n        # Attempt to get camera poses\n        if hasattr(scene, 'get_im_poses'):\n            poses = scene.get_im_poses()\n        elif hasattr(scene, 'im_poses'):\n            poses = scene.im_poses\n        else:\n            poses = None\n\n        # Attempt to get focal lengths\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        # Attempt to get principal points\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    except Exception as e:\n        print(f\"⚠️ Error getting camera parameters: {e}\")\n        poses = None\n        focals = None\n        pps = None\n\n    # [Important] MASt3R internal processing size\n    mast3r_size = 224.0\n\n    n_images = min(len(poses) if poses is not None else len(image_paths), len(image_paths))\n\n    for idx in range(n_images):\n        img_name = os.path.basename(image_paths[idx])\n\n        try:\n            # Get original image dimensions\n            img = Image.open(image_paths[idx])\n            W, H = img.size\n            img.close()\n\n            # Calculate scaling ratio\n            scale = W / mast3r_size\n\n            # Get Pose (Convert camera-to-world to world-to-camera)\n            if poses is not None and idx < len(poses):\n                pose_c2w = poses[idx]\n                if isinstance(pose_c2w, torch.Tensor):\n                    pose_c2w = pose_c2w.detach().cpu().numpy()\n                if not isinstance(pose_c2w, np.ndarray) or pose_c2w.shape != (4, 4):\n                    pose_c2w = np.eye(4)\n\n                # Invert to get world-to-camera pose\n                pose = np.linalg.inv(pose_c2w)\n            else:\n                pose = np.eye(4)\n\n            # 🔧 FIX: Get and scale focal length (handle both isotropic and anisotropic)\n            if focals is not None and idx < len(focals):\n                focal_mast3r = focals[idx]\n                if isinstance(focal_mast3r, torch.Tensor):\n                    focal_mast3r = focal_mast3r.detach().cpu()\n\n                # Check if isotropic (fx = fy) or anisotropic (fx ≠ fy)\n                if focals.shape[1] == 1:\n                    # Isotropic camera (fx = fy)\n                    focal_val = float(focal_mast3r) if focal_mast3r.numel() == 1 else float(focal_mast3r[0])\n                    fx = fy = focal_val * scale\n                else:\n                    # Anisotropic camera (fx ≠ fy)\n                    fx = float(focal_mast3r[0]) * scale\n                    fy = float(focal_mast3r[1]) * scale\n            else:\n                # Default fallback\n                fx = fy = 1000.0\n\n            # Get and scale principal point\n            if pps is not None and idx < len(pps):\n                pp_mast3r = pps[idx]\n                if isinstance(pp_mast3r, torch.Tensor):\n                    pp_mast3r = pp_mast3r.detach().cpu().numpy()\n\n                # 🔧 Apply scaling\n                pp = pp_mast3r * scale\n            else:\n                pp = np.array([W / 2.0, H / 2.0])\n\n            # 🔧 FIX: Store camera parameters with focal as tuple (fx, fy)\n            cameras_dict[img_name] = {\n                'focal': (fx, fy),  # ← FIXED: Store as tuple\n                'pp': pp,\n                'pose': pose,\n                'rotation': pose[:3, :3],\n                'translation': pose[:3, 3],\n                'width': W,\n                'height': H\n            }\n\n            # Debugging info (First image only)\n            if idx == 0:\n                print(f\"\\nExample camera 0:\")\n                print(f\"  Original size: {W}x{H}\")\n                print(f\"  MASt3R size: {mast3r_size}\")\n                print(f\"  Scale factor: {scale:.3f}\")\n                print(f\"  focals.shape: {focals.shape}\")\n                if focals.shape[1] == 1:\n                    print(f\"  MASt3R focal: {focal_val:.2f}\")\n                    print(f\"  Scaled focal: fx = fy = {fx:.2f}\")\n                else:\n                    print(f\"  MASt3R focals: fx={float(focal_mast3r[0]):.2f}, fy={float(focal_mast3r[1]):.2f}\")\n                    print(f\"  Scaled focals: fx={fx:.2f}, fy={fy:.2f}\")\n                print(f\"  MASt3R pp: [{pp_mast3r[0]:.2f}, {pp_mast3r[1]:.2f}]\")\n                print(f\"  Scaled pp: [{pp[0]:.2f}, {pp[1]:.2f}]\")\n\n            # Extract 3D points\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                pts3d_img = pts3d_all[idx] if idx < len(pts3d_all) else None\n            else:\n                pts3d_img = None\n\n            # Extract confidence scores\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                conf_img = conf_all[idx] if idx < len(conf_all) else None\n            else:\n                conf_img = None\n\n            # Process 3D points and 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                pts3d_flat = pts3d_img.reshape(-1, 3) if pts3d_img.ndim == 3 else pts3d_img\n                all_pts3d.append(pts3d_flat)\n\n                if conf_img is not None:\n                    if isinstance(conf_img, (list, torch.Tensor)):\n                        conf_img = np.array(conf_img) if isinstance(conf_img, list) else conf_img.detach().cpu().numpy()\n\n                    conf_flat = conf_img.reshape(-1) if conf_img.ndim > 1 else 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            # Fallback to default values with scaling applied\n            img = Image.open(image_paths[idx])\n            W, H = img.size\n            img.close()\n\n            cameras_dict[img_name] = {\n                'focal': (1000.0 * (W / mast3r_size), 1000.0 * (W / mast3r_size)),  # ← FIXED: Tuple\n                'pp': np.array([W / 2.0, H / 2.0]),\n                'pose': np.eye(4),\n                'rotation': np.eye(3),\n                'translation': np.zeros(3),\n                'width': W,\n                'height': H\n            }\n            continue\n\n    # Consolidate all 3D points\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 parameters for {len(cameras_dict)} cameras\")\n    print(f\"✓ Total 3D points: {len(pts3d)}\")\n\n    # Filter points by 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\"✓ Points after confidence filtering (>{conf_threshold}): {len(pts3d)}\")\n\n    return cameras_dict, pts3d, confidence\n\n# =====================================================================\n# Complete Color Extraction for Process2 (newly defined 2026/01/26)\n# =====================================================================\n\nimport numpy as np\nfrom PIL import Image\nimport struct\nfrom pathlib import Path\n\n# =====================================================================\n# STEP 1: Color Extraction Function\n# =====================================================================\n\ndef extract_colors_from_images(scene, image_paths, pts3d, confidence, conf_threshold=1.5):\n    \"\"\"\n    Extract colors from images that match the filtered pts3d.\n    \n    This matches Traditional method's color extraction.\n    \n    Args:\n        scene: MASt3R scene object\n        image_paths: List of image file paths\n        pts3d: (N, 3) filtered 3D points (after confidence filtering)\n        confidence: (N,) filtered confidence scores\n        conf_threshold: Confidence threshold used for filtering\n    \n    Returns:\n        colors: (N, 3) RGB colors [0-255] matching pts3d\n    \"\"\"\n    print(\"\\n=== Extracting Colors from Images ===\")\n    \n    # Get all 3D points BEFORE filtering (to match with colors)\n    all_pts3d = []\n    for idx in range(len(image_paths)):\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            pts3d_img = pts3d_all[idx] if idx < len(pts3d_all) else None\n        else:\n            pts3d_img = None\n        \n        if pts3d_img is not None:\n            if isinstance(pts3d_img, torch.Tensor):\n                pts3d_img = pts3d_img.detach().cpu().numpy()\n            pts3d_flat = pts3d_img.reshape(-1, 3) if pts3d_img.ndim == 3 else pts3d_img\n            all_pts3d.append(pts3d_flat)\n    \n    # Get dimensions from first image\n    first_img = Image.open(image_paths[0])\n    W_orig, H_orig = first_img.size\n    first_img.close()\n    \n    # MASt3R uses 224x224 internally\n    mast3r_size = 224\n    \n    # Extract colors from all images\n    print(f\"Extracting colors from {len(image_paths)} images...\")\n    all_colors = []\n    \n    for idx, img_path in enumerate(image_paths):\n        # Open and resize image to MASt3R size (224x224)\n        img = Image.open(img_path)\n        img_resized = img.resize((mast3r_size, mast3r_size), Image.BILINEAR)\n        img_array = np.array(img_resized)  # Shape: (224, 224, 3)\n        img.close()\n        \n        # Reshape to (224*224, 3) to match point order\n        colors_flat = img_array.reshape(-1, 3)\n        all_colors.append(colors_flat)\n        \n        if idx == 0:\n            print(f\"  Example image 0:\")\n            print(f\"    Original size: {W_orig}x{H_orig}\")\n            print(f\"    Resized to: {mast3r_size}x{mast3r_size}\")\n            print(f\"    Colors shape: {colors_flat.shape}\")\n    \n    # Stack all colors\n    colors_all = np.vstack(all_colors)  # Shape: (N_total, 3)\n    print(f\"✓ Total colors extracted: {len(colors_all):,}\")\n    \n    # Get confidence for all points (before filtering)\n    all_conf = []\n    for idx in range(len(image_paths)):\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            conf_img = conf_all[idx] if idx < len(conf_all) else None\n        else:\n            conf_img = None\n        \n        if conf_img is not None:\n            if isinstance(conf_img, torch.Tensor):\n                conf_img = conf_img.detach().cpu().numpy()\n            conf_flat = conf_img.reshape(-1) if conf_img.ndim > 1 else conf_img\n        else:\n            conf_flat = np.ones(len(all_pts3d[idx]))\n        \n        all_conf.append(conf_flat)\n    \n    conf_all = np.concatenate(all_conf)\n    \n    # Apply THE SAME filtering as pts3d\n    valid_mask = conf_all > conf_threshold\n    colors_filtered = colors_all[valid_mask]\n    \n    print(f\"✓ Colors after confidence filtering (>{conf_threshold}): {len(colors_filtered):,}\")\n    \n    # Verify shapes match\n    if len(colors_filtered) != len(pts3d):\n        print(f\"⚠️ WARNING: Color count ({len(colors_filtered)}) != Point count ({len(pts3d)})\")\n        print(f\"  Adjusting to match...\")\n        min_len = min(len(colors_filtered), len(pts3d))\n        colors_filtered = colors_filtered[:min_len]\n    else:\n        print(f\"✓ Colors match points: {len(colors_filtered):,} colors for {len(pts3d):,} points\")\n    \n    # Verify colors are diverse\n    unique_colors = len(np.unique(colors_filtered, axis=0))\n    print(f\"✓ Unique colors: {unique_colors:,}\")\n    \n    if unique_colors < 100:\n        print(f\"⚠️ WARNING: Very few unique colors!\")\n    else:\n        print(f\"✓ Good color diversity\")\n    \n    return colors_filtered\n\n\n# =====================================================================\n# STEP 2: Write points3D.bin with Colors\n# =====================================================================\n\ndef write_points3D_binary_with_colors(pts3d, confidence, colors, output_file):\n    \"\"\"\n    Export points3D.bin with actual colors.\n    \n    Args:\n        pts3d: (N, 3) array of 3D points\n        confidence: (N,) array of confidence scores\n        colors: (N, 3) array of RGB colors [0-255]\n        output_file: Path to output file\n    \"\"\"\n    num_points = len(pts3d)\n\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', num_points))\n\n        for point_id, (pt, color) in enumerate(zip(pts3d, colors), start=1):\n            x, y, z = pt\n\n            f.write(struct.pack('Q', point_id))\n            f.write(struct.pack('d', x))\n            f.write(struct.pack('d', y))\n            f.write(struct.pack('d', z))\n\n            # RGB Color (ACTUAL colors now!)\n            r = int(np.clip(color[0], 0, 255))\n            g = int(np.clip(color[1], 0, 255))\n            b = int(np.clip(color[2], 0, 255))\n            \n            f.write(struct.pack('B', r))\n            f.write(struct.pack('B', g))\n            f.write(struct.pack('B', b))\n\n            # Error estimation\n            if confidence is not None and point_id <= len(confidence):\n                error = 1.0 / max(confidence[point_id-1], 0.001)\n            else:\n                error = 1.0\n            f.write(struct.pack('d', error))\n\n            # track_length (Set to 0)\n            f.write(struct.pack('Q', 0))\n\n    print(f\"COLMAP points3D.bin saved to {output_file}\")\n    print(f\"  ✓ With actual RGB colors from images!\")\n\n\n# =====================================================================\n# STEP 3: Export with Colors\n# =====================================================================\n\ndef export_colmap_binary_with_colors(cameras_dict, pts3d, confidence, colors, \n                                     image_size, output_dir):\n    \"\"\"\n    Export COLMAP binary files with actual colors.\n    \n    Args:\n        cameras_dict: Dictionary of camera parameters\n        pts3d: (N, 3) filtered 3D points\n        confidence: (N,) filtered confidence scores\n        colors: (N, 3) RGB colors [0-255]\n        image_size: (width, height) tuple\n        output_dir: Output directory path\n    \"\"\"\n    output_path = Path(output_dir)\n    output_path.mkdir(parents=True, exist_ok=True)\n\n    # Write cameras.bin (same as before)\n    write_cameras_binary(\n        cameras_dict,\n        image_size,\n        output_path / 'cameras.bin'\n    )\n\n    # Write images.bin (same as before)\n    write_images_binary(\n        cameras_dict,\n        output_path / 'images.bin'\n    )\n\n    # Write points3D.bin WITH COLORS (NEW!)\n    write_points3D_binary_with_colors(\n        pts3d,\n        confidence,\n        colors,  # ← Actual colors!\n        output_path / 'points3D.bin'\n    )\n\n    print(f\"\\n✓ COLMAP binary files exported to {output_dir}/\")\n    print(f\"  - cameras.bin: {len(cameras_dict)} cameras (PINHOLE model)\")\n    print(f\"  - images.bin: {len(cameras_dict)} images\")\n    print(f\"  - points3D.bin: {len(pts3d)} points WITH COLORS\")\n\n\n# =====================================================================\n# STEP 4: Complete Workflow\n# =====================================================================\n\ndef create_process2_with_colors(scene, image_paths, output_dir, conf_threshold=1.5):\n    \"\"\"\n    Complete workflow: Process2 with color extraction.\n    \n    Usage:\n        create_process2_with_colors(\n            scene, \n            image_paths, \n            '/kaggle/working/output/sparse_process2_with_colors/0',\n            conf_threshold=1.5\n        )\n    \"\"\"\n    print(\"=\"*80)\n    print(\"CREATING PROCESS2 COLMAP WITH COLORS\")\n    print(\"=\"*80)\n    \n    # Step 1: Extract camera parameters and points\n    cameras_dict, pts3d, confidence = extract_camera_params_process2(\n        scene, image_paths, conf_threshold=conf_threshold\n    )\n    \n    print(f\"\\n✓ Extracted:\")\n    print(f\"  - {len(cameras_dict)} cameras\")\n    print(f\"  - {len(pts3d):,} 3D points\")\n    \n    # Step 2: Extract colors (NEW!)\n    colors = extract_colors_from_images(\n        scene, image_paths, pts3d, confidence, conf_threshold\n    )\n    \n    # Step 3: Get image size\n    img = Image.open(image_paths[0])\n    image_size = img.size\n    img.close()\n    \n    # Step 4: Export with colors\n    export_colmap_binary_with_colors(\n        cameras_dict, pts3d, confidence, colors,\n        image_size, output_dir\n    )\n    \n    print(\"\\n\" + \"=\"*80)\n    print(\"✓ COMPLETE!\")\n    print(\"=\"*80)\n    print(\"\\nOutput directory:\", output_dir)\n    print(\"\\nNext steps:\")\n    print(\"1. Train 3DGS with this reconstruction\")\n    print(\"2. Compare quality with gray Process2 and Traditional\")\n    print(\"3. Check if colors improve geometry convergence\")\n    \n    return cameras_dict, pts3d, confidence, colors","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:17:30.294772Z","iopub.execute_input":"2026-02-01T07:17:30.295353Z","iopub.status.idle":"2026-02-01T07:17:30.354448Z","shell.execute_reply.started":"2026-02-01T07:17:30.295323Z","shell.execute_reply":"2026-02-01T07:17:30.353539Z"}},"outputs":[],"execution_count":2},{"cell_type":"markdown","source":"# end of process2\n# process1","metadata":{}},{"cell_type":"code","source":"\n# ===== Traditional Method: extract_colmap_data =====\ndef extract_colmap_data_traditional(scene, image_paths, max_points=1000000):\n    \"\"\"\n    Traditional Method: Extract COLMAP-compatible data from a MASt3R scene.\n    (Derived from dino-mast3r-gs-kg-34oo.ipynb)\n    \"\"\"\n    print(\"\\n=== [TRADITIONAL] Extracting COLMAP-compatible data ===\")\n\n    # Extract point cloud\n    pts_all = scene.get_pts3d()\n    print(f\"pts_all type: {type(pts_all)}\")\n\n    if isinstance(pts_all, list):\n        print(f\"pts_all is a list with {len(pts_all)} elements\")\n        if len(pts_all) > 0:\n            print(f\"First element type: {type(pts_all[0])}\")\n            if hasattr(pts_all[0], 'shape'):\n                print(f\"First element shape: {pts_all[0].shape}\")\n\n        pts_all = torch.stack([p if isinstance(p, torch.Tensor) else torch.tensor(p)\n                              for p in pts_all])\n        print(f\"pts_all shape after conversion: {pts_all.shape}\")\n\n    if len(pts_all.shape) == 4:\n        print(f\"Found batched point cloud: {pts_all.shape}\")\n        B, H, W, _ = pts_all.shape\n        pts3d = pts_all.reshape(-1, 3).detach().cpu().numpy()\n\n        # Extract colors\n        colors = []\n        for img_path in image_paths:\n            img = Image.open(img_path).resize((W, H))\n            colors.append(np.array(img))\n        colors = np.stack(colors).reshape(-1, 3) / 255.0\n    else:\n        pts3d = pts_all.detach().cpu().numpy() if isinstance(pts_all, torch.Tensor) else pts_all\n        colors = np.ones((len(pts3d), 3)) * 0.5\n\n    print(f\"✓ Extracted {len(pts3d)} 3D points from {len(image_paths)} images\")\n\n    # Downsample points\n    if len(pts3d) > max_points:\n        print(f\"\\n⚠ Downsampling from {len(pts3d)} to {max_points} points...\")\n        valid_mask = ~(np.isnan(pts3d).any(axis=1) | np.isinf(pts3d).any(axis=1))\n        pts3d_valid = pts3d[valid_mask]\n        colors_valid = colors[valid_mask]\n        \n        # Count excluded points\n        num_excluded = len(pts3d_valid) - max_points\n        \n        indices = np.random.choice(len(pts3d_valid), size=max_points, replace=False)\n        pts3d = pts3d_valid[indices]\n        colors = colors_valid[indices]\n        print(f\"✓ Downsampled to {len(pts3d)} points\")\n        print(f\"⚠ Excluded {num_excluded} points due to max_points limit\")\n\n    # Extract camera parameters\n    print(\"Extracting camera parameters...\")\n\n    # [Important] Convert camera-to-world (C2W) to world-to-camera (W2C)\n    poses_c2w = scene.get_im_poses().detach().cpu().numpy()\n    print(f\"Retrieved camera-to-world poses: shape {poses_c2w.shape}\")\n\n    poses = []\n    for i, pose_c2w in enumerate(poses_c2w):\n        pose_w2c = np.linalg.inv(pose_c2w)\n        poses.append(pose_w2c)\n    poses = np.array(poses)\n    print(\"Converted to world-to-camera poses for COLMAP\")\n\n    focals = scene.get_focals().detach().cpu().numpy()\n    pp = scene.get_principal_points().detach().cpu().numpy()\n    print(f\"Focals shape: {focals.shape}\")\n    print(f\"Principal points shape: {pp.shape}\")\n\n    mast3r_size = 224.0\n\n    cameras = []\n    for i, img_path in enumerate(image_paths):\n        img = Image.open(img_path)\n        W, H = img.size\n        scale = W / mast3r_size\n\n        if focals.shape[1] == 1:\n            focal_mast3r = float(focals[i, 0])\n            fx = fy = focal_mast3r * scale\n        else:\n            fx = float(focals[i, 0]) * scale\n            fy = float(focals[i, 1]) * scale\n\n        cx = float(pp[i, 0]) * scale\n        cy = float(pp[i, 1]) * scale\n\n        camera = {\n            'camera_id': i + 1,\n            'model': 'PINHOLE',\n            'width': W,\n            'height': H,\n            'params': [fx, fy, cx, cy]\n        }\n        cameras.append(camera)\n\n        if i == 0:\n            print(f\"\\nExample camera 0:\")\n            print(f\"  Image size: {W}x{H}\")\n            print(f\"  MASt3R focal: {focal_mast3r:.2f}, pp: ({pp[i,0]:.2f}, {pp[i,1]:.2f})\")\n            print(f\"  Scaled fx={fx:.2f}, fy={fy:.2f}, cx={cx:.2f}, cy={cy:.2f}\")\n            print(f\"  Pose (first row): {poses[i][0]}\")\n\n    print(f\"\\n✓ Extracted {len(cameras)} cameras and {len(poses)} poses\")\n\n    pts3d = pts3d.reshape(-1, 3)\n    colors = np.ones((len(pts3d), 3)) * 0.5\n    \n    return pts3d, colors, cameras, poses\n\n\n# ===== Traditional Method: rotmat2qvec =====\ndef rotmat2qvec_traditional(R):\n    \"\"\"Traditional Method: Convert rotation matrix to quaternion.\"\"\"\n    R = np.asarray(R, dtype=np.float64)\n    trace = np.trace(R)\n\n    if trace > 0:\n        s = 0.5 / np.sqrt(trace + 1.0)\n        w = 0.25 / s\n        x = (R[2, 1] - R[1, 2]) * s\n        y = (R[0, 2] - R[2, 0]) * s\n        z = (R[1, 0] - R[0, 1]) * s\n    elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:\n        s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])\n        w = (R[2, 1] - R[1, 2]) / s\n        x = 0.25 * s\n        y = (R[0, 1] + R[1, 0]) / s\n        z = (R[0, 2] + R[2, 0]) / s\n    elif R[1, 1] > R[2, 2]:\n        s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])\n        w = (R[0, 2] - R[2, 0]) / s\n        x = (R[0, 1] + R[1, 0]) / s\n        y = 0.25 * s\n        z = (R[1, 2] + R[2, 1]) / s\n    else:\n        s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])\n        w = (R[1, 0] - R[0, 1]) / s\n        x = (R[0, 2] + R[2, 0]) / s\n        y = (R[1, 2] + R[2, 1]) / s\n        z = 0.25 * s\n\n    qvec = np.array([w, x, y, z], dtype=np.float64)\n    qvec = qvec / np.linalg.norm(qvec)\n\n    return qvec\n\n\n# ===== Traditional Method: Save Functions =====\ndef write_cameras_binary_traditional(cameras, output_file):\n    \"\"\"Traditional Method: Write cameras.bin.\"\"\"\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', len(cameras)))\n\n        for i, cam in enumerate(cameras):\n            camera_id = cam.get('camera_id', i + 1)\n            model_id = 1  # PINHOLE\n            width = cam['width']\n            height = cam['height']\n            params = cam['params']\n\n            f.write(struct.pack('i', camera_id))\n            f.write(struct.pack('i', model_id))\n            f.write(struct.pack('Q', width))\n            f.write(struct.pack('Q', height))\n\n            for param in params[:4]:\n                f.write(struct.pack('d', param))\n\n\ndef write_images_binary_traditional(image_paths, cameras, poses, output_file):\n    \"\"\"Traditional Method: Write images.bin.\"\"\"\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', len(image_paths)))\n\n        for i, (img_path, pose) in enumerate(zip(image_paths, poses)):\n            image_id = i + 1\n            camera_id = cameras[i].get('camera_id', i + 1)\n            image_name = os.path.basename(img_path)\n\n            R = pose[:3, :3]\n            t = pose[:3, 3]\n            qvec = rotmat2qvec_traditional(R)\n            tvec = t\n\n            f.write(struct.pack('i', image_id))\n            for q in qvec:\n                f.write(struct.pack('d', float(q)))\n            for tv in tvec:\n                f.write(struct.pack('d', float(tv)))\n            f.write(struct.pack('i', camera_id))\n            f.write(image_name.encode('utf-8') + b'\\x00')\n            f.write(struct.pack('Q', 0))\n\n\ndef write_points3d_binary_traditional(pts3d, colors, output_file):\n    \"\"\"Traditional Method: Write points3D.bin.\"\"\"\n    valid_indices = []\n    invalid_count = 0\n    \n    for i, pt in enumerate(pts3d):\n        if not (np.isnan(pt).any() or np.isinf(pt).any()):\n            valid_indices.append(i)\n        else:\n            invalid_count += 1\n\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', len(valid_indices)))\n\n        for idx, point_id in enumerate(valid_indices):\n            pt = pts3d[point_id]\n            color = colors[point_id]\n\n            f.write(struct.pack('Q', point_id))\n            for coord in np.asarray(pt).ravel(): \n                    f.write(struct.pack('d', float(coord)))\n\n            col_int = (color * 255).astype(np.uint8)\n            for c in col_int:\n                f.write(struct.pack('B', int(c)))\n\n            f.write(struct.pack('d', 0.0))\n            f.write(struct.pack('Q', 0))\n\n    if invalid_count > 0:\n        print(f\"  ⚠ Excluded {invalid_count} invalid points (NaN/Inf)\")\n\n    return len(valid_indices)\n\n\ndef save_colmap_reconstruction_traditional(pts3d, colors, cameras, poses, image_paths, output_dir):\n    \"\"\"Traditional Method: Save COLMAP reconstruction.\"\"\"\n    print(\"\\n=== [TRADITIONAL] Saving COLMAP reconstruction ===\")\n\n    sparse_dir = Path(output_dir) / 'sparse_traditional' / '0'\n    sparse_dir.mkdir(parents=True, exist_ok=True)\n\n    write_cameras_binary_traditional(cameras, sparse_dir / 'cameras.bin')\n    print(f\"  ✓ Wrote {len(cameras)} cameras\")\n\n    write_images_binary_traditional(image_paths, cameras, poses, sparse_dir / 'images.bin')\n    print(f\"  ✓ Wrote {len(image_paths)} images\")\n\n    num_points = write_points3d_binary_traditional(pts3d, colors, sparse_dir / 'points3D.bin')\n    print(f\"  ✓ Wrote {num_points} 3D points\")\n\n    print(f\"\\n✓ Traditional COLMAP reconstruction saved to {sparse_dir}\")\n\n    return sparse_dir","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:17:30.355449Z","iopub.execute_input":"2026-02-01T07:17:30.355724Z","iopub.status.idle":"2026-02-01T07:17:30.385258Z","shell.execute_reply.started":"2026-02-01T07:17:30.355701Z","shell.execute_reply":"2026-02-01T07:17:30.384421Z"}},"outputs":[],"execution_count":3},{"cell_type":"markdown","source":"# end of process1","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================================================================\n# CELL 20: Traditional Method Functions (for comparison)\n# =====================================================================\nimport struct\nimport numpy as np\nfrom pathlib import Path\n\n# ===== 従来法: extract_colmap_data =====\ndef extract_colmap_data_traditional(scene, image_paths, max_points=1000000):\n    \"\"\"\n    従来法: MASt3Rシーンから COLMAP互換データを抽出\n    (dino-mast3r-gs-kg-34oo.ipynb からの抽出)\n    \"\"\"\n    print(\"\\n=== [TRADITIONAL] Extracting COLMAP-compatible data ===\")\n\n    # Extract point cloud\n    pts_all = scene.get_pts3d()\n    print(f\"pts_all type: {type(pts_all)}\")\n\n    if isinstance(pts_all, list):\n        print(f\"pts_all is a list with {len(pts_all)} elements\")\n        if len(pts_all) > 0:\n            print(f\"First element type: {type(pts_all[0])}\")\n            if hasattr(pts_all[0], 'shape'):\n                print(f\"First element shape: {pts_all[0].shape}\")\n\n        pts_all = torch.stack([p if isinstance(p, torch.Tensor) else torch.tensor(p)\n                              for p in pts_all])\n        print(f\"pts_all shape after conversion: {pts_all.shape}\")\n\n    if len(pts_all.shape) == 4:\n        print(f\"Found batched point cloud: {pts_all.shape}\")\n        B, H, W, _ = pts_all.shape\n        pts3d = pts_all.reshape(-1, 3).detach().cpu().numpy()\n\n        # Extract colors\n        colors = []\n        for img_path in image_paths:\n            img = Image.open(img_path).resize((W, H))\n            colors.append(np.array(img))\n        colors = np.stack(colors).reshape(-1, 3) / 255.0\n    else:\n        pts3d = pts_all.detach().cpu().numpy() if isinstance(pts_all, torch.Tensor) else pts_all\n        colors = np.ones((len(pts3d), 3)) * 0.5\n\n    print(f\"✓ Extracted {len(pts3d)} 3D points from {len(image_paths)} images\")\n\n    # Downsample points\n    if len(pts3d) > max_points:\n        print(f\"\\n⚠ Downsampling from {len(pts3d)} to {max_points} points...\")\n        valid_mask = ~(np.isnan(pts3d).any(axis=1) | np.isinf(pts3d).any(axis=1))\n        pts3d_valid = pts3d[valid_mask]\n        colors_valid = colors[valid_mask]\n        indices = np.random.choice(len(pts3d_valid), size=max_points, replace=False)\n        pts3d = pts3d_valid[indices]\n        colors = colors_valid[indices]\n        print(f\"✓ Downsampled to {len(pts3d)} points\")\n\n    # Extract camera parameters\n    print(\"Extracting camera parameters...\")\n\n    # 【重要】camera-to-world を world-to-camera に変換\n    poses_c2w = scene.get_im_poses().detach().cpu().numpy()\n    print(f\"Retrieved camera-to-world poses: shape {poses_c2w.shape}\")\n\n    poses = []\n    for i, pose_c2w in enumerate(poses_c2w):\n        pose_w2c = np.linalg.inv(pose_c2w)\n        poses.append(pose_w2c)\n    poses = np.array(poses)\n    print(f\"Converted to world-to-camera poses for COLMAP\")\n\n    focals = scene.get_focals().detach().cpu().numpy()\n    pp = scene.get_principal_points().detach().cpu().numpy()\n    print(f\"Focals shape: {focals.shape}\")\n    print(f\"Principal points shape: {pp.shape}\")\n\n    mast3r_size = 224.0\n\n    cameras = []\n    for i, img_path in enumerate(image_paths):\n        img = Image.open(img_path)\n        W, H = img.size\n        scale = W / mast3r_size\n\n        if focals.shape[1] == 1:\n            focal_mast3r = float(focals[i, 0])\n            fx = fy = focal_mast3r * scale\n        else:\n            fx = float(focals[i, 0]) * scale\n            fy = float(focals[i, 1]) * scale\n\n        cx = float(pp[i, 0]) * scale\n        cy = float(pp[i, 1]) * scale\n\n        camera = {\n            'camera_id': i + 1,\n            'model': 'PINHOLE',\n            'width': W,\n            'height': H,\n            'params': [fx, fy, cx, cy]\n        }\n        cameras.append(camera)\n\n        if i == 0:\n            print(f\"\\nExample camera 0:\")\n            print(f\"  Image size: {W}x{H}\")\n            print(f\"  MASt3R focal: {focal_mast3r:.2f}, pp: ({pp[i,0]:.2f}, {pp[i,1]:.2f})\")\n            print(f\"  Scaled fx={fx:.2f}, fy={fy:.2f}, cx={cx:.2f}, cy={cy:.2f}\")\n            print(f\"  Pose (first row): {poses[i][0]}\")\n\n    print(f\"\\n✓ Extracted {len(cameras)} cameras and {len(poses)} poses\")\n\n    return pts3d, colors, cameras, poses\n\n\n# ===== 従来法: rotmat2qvec =====\ndef rotmat2qvec_traditional(R):\n    \"\"\"従来法: 回転行列をクォータニオンに変換\"\"\"\n    R = np.asarray(R, dtype=np.float64)\n    trace = np.trace(R)\n\n    if trace > 0:\n        s = 0.5 / np.sqrt(trace + 1.0)\n        w = 0.25 / s\n        x = (R[2, 1] - R[1, 2]) * s\n        y = (R[0, 2] - R[2, 0]) * s\n        z = (R[1, 0] - R[0, 1]) * s\n    elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:\n        s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])\n        w = (R[2, 1] - R[1, 2]) / s\n        x = 0.25 * s\n        y = (R[0, 1] + R[1, 0]) / s\n        z = (R[0, 2] + R[2, 0]) / s\n    elif R[1, 1] > R[2, 2]:\n        s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])\n        w = (R[0, 2] - R[2, 0]) / s\n        x = (R[0, 1] + R[1, 0]) / s\n        y = 0.25 * s\n        z = (R[1, 2] + R[2, 1]) / s\n    else:\n        s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])\n        w = (R[1, 0] - R[0, 1]) / s\n        x = (R[0, 2] + R[2, 0]) / s\n        y = (R[1, 2] + R[2, 1]) / s\n        z = 0.25 * s\n\n    qvec = np.array([w, x, y, z], dtype=np.float64)\n    qvec = qvec / np.linalg.norm(qvec)\n\n    return qvec\n\n\n# ===== 従来法: save関数群 =====\ndef write_cameras_binary_traditional(cameras, output_file):\n    \"\"\"従来法: cameras.binを書き込み\"\"\"\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', len(cameras)))\n\n        for i, cam in enumerate(cameras):\n            camera_id = cam.get('camera_id', i + 1)\n            model_id = 1  # PINHOLE\n            width = cam['width']\n            height = cam['height']\n            params = cam['params']\n\n            f.write(struct.pack('i', camera_id))\n            f.write(struct.pack('i', model_id))\n            f.write(struct.pack('Q', width))\n            f.write(struct.pack('Q', height))\n\n            for param in params[:4]:\n                f.write(struct.pack('d', param))\n\n\ndef write_images_binary_traditional(image_paths, cameras, poses, output_file):\n    \"\"\"従来法: images.binを書き込み\"\"\"\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', len(image_paths)))\n\n        for i, (img_path, pose) in enumerate(zip(image_paths, poses)):\n            image_id = i + 1\n            camera_id = cameras[i].get('camera_id', i + 1)\n            image_name = os.path.basename(img_path)\n\n            R = pose[:3, :3]\n            t = pose[:3, 3]\n            qvec = rotmat2qvec_traditional(R)\n            tvec = t\n\n            f.write(struct.pack('i', image_id))\n            for q in qvec:\n                f.write(struct.pack('d', float(q)))\n            for tv in tvec:\n                f.write(struct.pack('d', float(tv)))\n            f.write(struct.pack('i', camera_id))\n            f.write(image_name.encode('utf-8') + b'\\x00')\n            f.write(struct.pack('Q', 0))\n\n\ndef write_points3d_binary_traditional(pts3d, colors, output_file):\n    \"\"\"従来法: points3D.binを書き込み\"\"\"\n    valid_indices = []\n    for i, pt in enumerate(pts3d):\n        if not (np.isnan(pt).any() or np.isinf(pt).any()):\n            valid_indices.append(i)\n\n    with open(output_file, 'wb') as f:\n        f.write(struct.pack('Q', len(valid_indices)))\n\n        for idx, point_id in enumerate(valid_indices):\n            pt = pts3d[point_id]\n            color = colors[point_id]\n\n            f.write(struct.pack('Q', point_id))\n            for coord in pt:\n                f.write(struct.pack('d', float(coord)))\n\n            col_int = (color * 255).astype(np.uint8)\n            for c in col_int:\n                f.write(struct.pack('B', int(c)))\n\n            f.write(struct.pack('d', 0.0))\n            f.write(struct.pack('Q', 0))\n\n    return len(valid_indices)\n\n\ndef save_colmap_reconstruction_traditional(pts3d, colors, cameras, poses, image_paths, output_dir):\n    \"\"\"従来法: COLMAP再構成を保存\"\"\"\n    print(\"\\n=== [TRADITIONAL] Saving COLMAP reconstruction ===\")\n\n    sparse_dir = Path(output_dir) / 'sparse_traditional' / '0'\n    sparse_dir.mkdir(parents=True, exist_ok=True)\n\n    write_cameras_binary_traditional(cameras, sparse_dir / 'cameras.bin')\n    print(f\"  ✓ Wrote {len(cameras)} cameras\")\n\n    write_images_binary_traditional(image_paths, cameras, poses, sparse_dir / 'images.bin')\n    print(f\"  ✓ Wrote {len(image_paths)} images\")\n\n    num_points = write_points3d_binary_traditional(pts3d, colors, sparse_dir / 'points3D.bin')\n    print(f\"  ✓ Wrote {num_points} 3D points\")\n\n    print(f\"\\n✓ Traditional COLMAP reconstruction saved to {sparse_dir}\")\n\n    return sparse_dir","metadata":{"id":"kIrrlZXQEkSA","trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:17:30.386183Z","iopub.execute_input":"2026-02-01T07:17:30.386424Z","iopub.status.idle":"2026-02-01T07:17:30.415173Z","shell.execute_reply.started":"2026-02-01T07:17:30.386403Z","shell.execute_reply":"2026-02-01T07:17:30.414280Z"}},"outputs":[],"execution_count":4},{"cell_type":"code","source":"# =====================================================================\n# CELL 21: Convert BIN to CSV for Easy Comparison\n# =====================================================================\nimport pandas as pd\nimport struct\n\ndef bin_to_csv_cameras(bin_file, csv_file):\n    \"\"\"cameras.bin → CSV\"\"\"\n    data = []\n    with open(bin_file, 'rb') as f:\n        num_cameras = struct.unpack('Q', f.read(8))[0]\n        for _ in range(num_cameras):\n            camera_id = struct.unpack('i', f.read(4))[0]\n            model_id = struct.unpack('i', f.read(4))[0]\n            width = struct.unpack('Q', f.read(8))[0]\n            height = struct.unpack('Q', f.read(8))[0]\n\n            # PINHOLE: 4 params\n            if model_id == 1:\n                params = struct.unpack('dddd', f.read(32))\n            # SIMPLE_PINHOLE: 3 params\n            else:\n                params = struct.unpack('ddd', f.read(24))\n\n            data.append({\n                'camera_id': camera_id,\n                'model_id': model_id,\n                'width': width,\n                'height': height,\n                'fx': params[0] if len(params) >= 1 else None,\n                'fy': params[1] if len(params) >= 2 else params[0] if len(params) == 1 else None,\n                'cx': params[2] if len(params) >= 3 else None,\n                'cy': params[3] if len(params) >= 4 else None\n            })\n\n    df = pd.DataFrame(data)\n    df.to_csv(csv_file, index=False)\n    print(f\"✓ Cameras CSV saved: {csv_file}\")\n    return df\n\n\ndef bin_to_csv_images(bin_file, csv_file):\n    \"\"\"images.bin → CSV\"\"\"\n    data = []\n    with open(bin_file, 'rb') as f:\n        num_images = struct.unpack('Q', f.read(8))[0]\n        for _ in range(num_images):\n            image_id = struct.unpack('i', f.read(4))[0]\n            qvec = struct.unpack('dddd', f.read(32))\n            tvec = struct.unpack('ddd', f.read(24))\n            camera_id = struct.unpack('i', f.read(4))[0]\n\n            name = b''\n            while True:\n                char = f.read(1)\n                if char == b'\\x00':\n                    break\n                name += char\n            name = name.decode('utf-8')\n\n            num_points2D = struct.unpack('Q', f.read(8))[0]\n            f.read(num_points2D * 24)\n\n            data.append({\n                'image_id': image_id,\n                'qw': qvec[0],\n                'qx': qvec[1],\n                'qy': qvec[2],\n                'qz': qvec[3],\n                'tx': tvec[0],\n                'ty': tvec[1],\n                'tz': tvec[2],\n                'camera_id': camera_id,\n                'name': name\n            })\n\n    df = pd.DataFrame(data)\n    df.to_csv(csv_file, index=False)\n    print(f\"✓ Images CSV saved: {csv_file}\")\n    return df\n\n\ndef bin_to_csv_points3d(bin_file, csv_file, max_rows=10000):\n    \"\"\"points3D.bin → CSV (サンプリング)\"\"\"\n    data = []\n    with open(bin_file, 'rb') as f:\n        num_points = struct.unpack('Q', f.read(8))[0]\n\n        # サンプリング間隔を計算\n        step = max(1, num_points // max_rows)\n\n        for i in range(num_points):\n            point_id = struct.unpack('Q', f.read(8))[0]\n            xyz = struct.unpack('ddd', f.read(24))\n            rgb = struct.unpack('BBB', f.read(3))\n            error = struct.unpack('d', f.read(8))[0]\n            track_length = struct.unpack('Q', f.read(8))[0]\n            f.read(track_length * 8)\n\n            # サンプリング\n            if i % step == 0:\n                data.append({\n                    'point_id': point_id,\n                    'x': xyz[0],\n                    'y': xyz[1],\n                    'z': xyz[2],\n                    'r': rgb[0],\n                    'g': rgb[1],\n                    'b': rgb[2],\n                    'error': error\n                })\n\n    df = pd.DataFrame(data)\n    df.to_csv(csv_file, index=False)\n    print(f\"✓ Points3D CSV saved: {csv_file} (sampled {len(df)} / {num_points} points)\")\n    return df\n\n\ndef convert_colmap_bins_to_csv(sparse_dir, output_prefix):\n    \"\"\"全BINファイルをCSVに変換\"\"\"\n    print(f\"\\n=== Converting {sparse_dir} to CSV ===\")\n\n    cameras_df = bin_to_csv_cameras(\n        os.path.join(sparse_dir, 'cameras.bin'),\n        f\"{output_prefix}_cameras.csv\"\n    )\n\n    images_df = bin_to_csv_images(\n        os.path.join(sparse_dir, 'images.bin'),\n        f\"{output_prefix}_images.csv\"\n    )\n\n    points_df = bin_to_csv_points3d(\n        os.path.join(sparse_dir, 'points3D.bin'),\n        f\"{output_prefix}_points3d.csv\",\n        max_rows=10000\n    )\n\n    return cameras_df, images_df, points_df","metadata":{"id":"c7A05pXLFt2E","trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:17:30.417176Z","iopub.execute_input":"2026-02-01T07:17:30.417533Z","iopub.status.idle":"2026-02-01T07:17:30.435058Z","shell.execute_reply.started":"2026-02-01T07:17:30.417502Z","shell.execute_reply":"2026-02-01T07:17:30.434392Z"}},"outputs":[],"execution_count":5},{"cell_type":"code","source":"# =====================================================================\n# CELL 22: Comparison Function\n# =====================================================================\n\ndef compare_extraction_methods(scene, image_paths, output_dir, conf_threshold=0.5, max_points=100000):\n    \"\"\"\n    新方式と従来法の両方でCOLMAP形式を出力し、比較する\n\n    Args:\n        scene: MASt3Rのシーンオブジェクト\n        image_paths: 画像パスのリスト\n        output_dir: 出力ディレクトリ\n        conf_threshold: 信頼度閾値(新方式用)\n        max_points: 最大点数(従来法用)\n\n    Returns:\n        dict: 比較結果の辞書\n    \"\"\"\n    print(\"\\n\" + \"=\"*70)\n    print(\"COMPARISON: New vs Traditional Extraction Methods\")\n    print(\"=\"*70)\n\n    # ===== METHOD 1: 新方式 (extract_camera_params_process2) =====\n    print(\"\\n--- METHOD 1: Current Implementation (extract_camera_params_process2) ---\")\n\n    cameras_dict_new, pts3d_new, confidence_new = extract_camera_params_process2(\n        scene=scene,\n        image_paths=image_paths,\n        conf_threshold=conf_threshold\n    )\n\n    # 画像サイズを取得\n    first_img = Image.open(image_paths[0])\n    image_size = (first_img.width, first_img.height)\n    first_img.close()\n\n    # 新方式のBIN保存\n    sparse_dir_new = os.path.join(output_dir, \"sparse_new/0\")\n    os.makedirs(sparse_dir_new, exist_ok=True)\n\n    export_colmap_binary(\n        cameras_dict=cameras_dict_new,\n        pts3d=pts3d_new,\n        confidence=confidence_new,\n        image_size=image_size,\n        output_dir=sparse_dir_new\n    )\n\n    \n    # ===== METHOD 2: 従来法 (extract_colmap_data_traditional) =====\n    print(\"\\n--- METHOD 2: Traditional Implementation (extract_colmap_data) ---\")\n\n    pts3d_trad, colors_trad, cameras_trad, poses_trad = extract_colmap_data_traditional(\n        scene=scene,\n        image_paths=image_paths,\n        max_points=max_points\n    )\n\n    # 従来法のBIN保存\n    sparse_dir_trad = save_colmap_reconstruction_traditional(\n        pts3d=pts3d_trad,\n        colors=colors_trad,\n        cameras=cameras_trad,\n        poses=poses_trad,\n        image_paths=image_paths,\n        output_dir=output_dir\n    )\n\n    # ===== CSVに変換 =====\n    print(\"\\n\" + \"=\"*70)\n    print(\"Converting to CSV for comparison\")\n    print(\"=\"*70)\n\n    csv_prefix_new = os.path.join(output_dir, \"comparison_new\")\n    csv_prefix_trad = os.path.join(output_dir, \"comparison_traditional\")\n\n    cam_new, img_new, pts_new = convert_colmap_bins_to_csv(\n        sparse_dir_new,\n        csv_prefix_new\n    )\n\n    cam_trad, img_trad, pts_trad = convert_colmap_bins_to_csv(\n        str(sparse_dir_trad),\n        csv_prefix_trad\n    )\n\n    # ===== 比較サマリー =====\n    print(\"\\n\" + \"=\"*70)\n    print(\"COMPARISON SUMMARY\")\n    print(\"=\"*70)\n\n    comparison_results = {\n        'cameras': {\n            'new_count': len(cam_new),\n            'trad_count': len(cam_trad),\n            'new_focal': float(cam_new.iloc[0]['fx']) if len(cam_new) > 0 else None,\n            'trad_focal': float(cam_trad.iloc[0]['fx']) if len(cam_trad) > 0 else None,\n        },\n        'images': {\n            'new_count': len(img_new),\n            'trad_count': len(img_trad),\n            'new_tvec': [float(img_new.iloc[0]['tx']), float(img_new.iloc[0]['ty']), float(img_new.iloc[0]['tz'])] if len(img_new) > 0 else None,\n            'trad_tvec': [float(img_trad.iloc[0]['tx']), float(img_trad.iloc[0]['ty']), float(img_trad.iloc[0]['tz'])] if len(img_trad) > 0 else None,\n        },\n        'points': {\n            'new_count': len(pts_new),\n            'trad_count': len(pts_trad),\n            'new_center': [float(pts_new['x'].mean()), float(pts_new['y'].mean()), float(pts_new['z'].mean())] if len(pts_new) > 0 else None,\n            'trad_center': [float(pts_trad['x'].mean()), float(pts_trad['y'].mean()), float(pts_trad['z'].mean())] if len(pts_trad) > 0 else None,\n        }\n    }\n\n    # 結果を表示\n    print(\"\\nCAMERAS:\")\n    print(f\"  New method:         {comparison_results['cameras']['new_count']} cameras\")\n    print(f\"  Traditional method: {comparison_results['cameras']['trad_count']} cameras\")\n    if comparison_results['cameras']['new_focal'] and comparison_results['cameras']['trad_focal']:\n        print(f\"\\n  Sample focal lengths:\")\n        print(f\"    New:         fx={comparison_results['cameras']['new_focal']:.2f}\")\n        print(f\"    Traditional: fx={comparison_results['cameras']['trad_focal']:.2f}\")\n        focal_diff = abs(comparison_results['cameras']['new_focal'] - comparison_results['cameras']['trad_focal'])\n        print(f\"    Difference:  {focal_diff:.2f}\")\n\n    print(\"\\nIMAGES:\")\n    print(f\"  New method:         {comparison_results['images']['new_count']} images\")\n    print(f\"  Traditional method: {comparison_results['images']['trad_count']} images\")\n    if comparison_results['images']['new_tvec'] and comparison_results['images']['trad_tvec']:\n        print(f\"\\n  Sample translation (first image):\")\n        print(f\"    New:         {comparison_results['images']['new_tvec']}\")\n        print(f\"    Traditional: {comparison_results['images']['trad_tvec']}\")\n        tvec_diff = np.linalg.norm(\n            np.array(comparison_results['images']['new_tvec']) -\n            np.array(comparison_results['images']['trad_tvec'])\n        )\n        print(f\"    Distance:    {tvec_diff:.3f}\")\n\n    print(\"\\nPOINTS3D:\")\n    print(f\"  New method:         {comparison_results['points']['new_count']} points (sampled)\")\n    print(f\"  Traditional method: {comparison_results['points']['trad_count']} points (sampled)\")\n    if comparison_results['points']['new_center'] and comparison_results['points']['trad_center']:\n        print(f\"\\n  Center of points:\")\n        print(f\"    New:         {comparison_results['points']['new_center']}\")\n        print(f\"    Traditional: {comparison_results['points']['trad_center']}\")\n        center_diff = np.linalg.norm(\n            np.array(comparison_results['points']['new_center']) -\n            np.array(comparison_results['points']['trad_center'])\n        )\n        print(f\"    Distance:    {center_diff:.3f}\")\n\n    print(\"\\n\" + \"=\"*70)\n    print(\"CSV FILES SAVED:\")\n    print(\"=\"*70)\n    print(f\"  New method:\")\n    print(f\"    - {csv_prefix_new}_cameras.csv\")\n    print(f\"    - {csv_prefix_new}_images.csv\")\n    print(f\"    - {csv_prefix_new}_points3d.csv\")\n    print(f\"  Traditional method:\")\n    print(f\"    - {csv_prefix_trad}_cameras.csv\")\n    print(f\"    - {csv_prefix_trad}_images.csv\")\n    print(f\"    - {csv_prefix_trad}_points3d.csv\")\n\n    print(\"\\n✓ Comparison complete! Review CSV files for detailed analysis.\")\n\n    return comparison_results","metadata":{"id":"SN1a_CbWEkIg","trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:17:30.435858Z","iopub.execute_input":"2026-02-01T07:17:30.436059Z","iopub.status.idle":"2026-02-01T07:17:30.455587Z","shell.execute_reply.started":"2026-02-01T07:17:30.436040Z","shell.execute_reply":"2026-02-01T07:17:30.454623Z"}},"outputs":[],"execution_count":6},{"cell_type":"code","source":"","metadata":{"id":"lHdqGcsaDLfb","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================================================================\n# CELL 13: Gaussian Splatting Runner\n# =====================================================================\ndef run_gaussian_splatting(source_dir, output_dir, iterations=30000):\n    \"\"\"Gaussian Splattingを実行\"\"\"\n    print(\"\\n=== Running Gaussian Splatting ===\")\n\n    os.makedirs(output_dir, exist_ok=True)\n\n    cmd = [\n        \"python\", \"/kaggle/working/gaussian-splatting/train.py\",\n        \"-s\", source_dir,\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    result = subprocess.run(cmd, capture_output=False, text=True)\n\n    if result.returncode == 0:\n        print(f\"\\n✓ Gaussian Splatting complete\")\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            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\"  ✓ {item}/point_cloud.ply ({file_size:.2f} MB)\")\n    else:\n        print(f\"\\n✗ Gaussian Splatting failed with return code {result.returncode}\")\n\n    return output_dir","metadata":{"id":"o0n2RL3Ep5_Y","trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:17:30.456737Z","iopub.execute_input":"2026-02-01T07:17:30.457095Z","iopub.status.idle":"2026-02-01T07:17:30.473231Z","shell.execute_reply.started":"2026-02-01T07:17:30.457059Z","shell.execute_reply":"2026-02-01T07:17:30.472331Z"}},"outputs":[],"execution_count":7},{"cell_type":"code","source":"# =====================================================================\n# FIXED: Main Pipeline with Color Extraction\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.001, preprocess_mode='none'):\n    \"\"\"メインパイプライン(色抽出対応版)\"\"\"\n\n\n    # STEP 0: Image Preprocessing\n    if preprocess_mode == 'biplet':\n        print(\"=\"*70)\n        print(\"STEP 0: Image Preprocessing (Biplet Crops)\")\n        print(\"=\"*70)\n\n        temp_biplet_dir = os.path.join(output_dir, \"temp_biplet\")\n        biplet_dir = normalize_image_sizes_biplet(image_dir, temp_biplet_dir, size=square_size)\n\n        images_dir = os.path.join(output_dir, \"images\")\n        os.makedirs(images_dir, exist_ok=True)\n\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        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        shutil.rmtree(temp_biplet_dir)\n        image_dir = images_dir\n        clear_memory()\n    else:\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    # STEP 1: Loading Images\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    # STEP 2: Image Pair Selection (DINO)\n    print(\"\\n\" + \"=\"*70)\n    print(\"STEP 2: Image Pair Selection (DINO)\")\n    print(\"=\"*70)\n\n    max_pairs = min(max_pairs, 50)\n    pairs = get_image_pairs_dino(image_paths, max_pairs=max_pairs)\n    print(f\"Selected {len(pairs)} image pairs\")\n    clear_memory()\n\n    # STEP 3: MASt3R 3D Reconstruction\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    scene, mast3r_images = run_mast3r_pairs(model, image_paths, pairs, device)\n\n    del model\n    clear_memory()\n    # ...\n\n    # STEP 4: Converting to COLMAP (CELL 11/12使用)\n    print(\"\\n\" + \"=\"*70)\n    print(\"STEP 4: Converting to COLMAP (PINHOLE) WITH COLORS\")\n    print(\"=\"*70)\n\n    # 🔧 FIX: カメラパラメータと色を一度に抽出\n    cameras_dict, pts3d, confidence = extract_camera_params_process2(\n        scene=scene,\n        image_paths=image_paths,\n        conf_threshold=conf_threshold\n    )\n    \n    print(f\"Extracted {len(cameras_dict)} cameras with conf >= {conf_threshold}\")\n    print(f\"Extracted {len(pts3d):,} 3D points\")\n\n    # 🔧 FIX: 色を抽出\n    print(\"\\n[Extracting colors from images...]\")\n    colors = extract_colors_from_images(\n        scene=scene,\n        image_paths=image_paths,\n        pts3d=pts3d,\n        confidence=confidence,\n        conf_threshold=conf_threshold\n    )\n    \n    print(f\"✓ Extracted {len(colors):,} colors\")\n\n    # 画像サイズを取得\n    from PIL import Image\n    first_img = Image.open(image_paths[0])\n    image_size = (first_img.width, first_img.height)\n    first_img.close()\n\n    # COLMAP出力ディレクトリ\n    colmap_dir = os.path.join(output_dir, \"sparse/0\")\n    os.makedirs(colmap_dir, exist_ok=True)\n\n    # 🔧 FIX: 色付きでエクスポート\n    print(\"\\n[Exporting COLMAP files with colors...]\")\n    export_colmap_binary_with_colors(\n        cameras_dict=cameras_dict,\n        pts3d=pts3d,\n        confidence=confidence,\n        colors=colors,  # ← 色を渡す!\n        image_size=image_size,\n        output_dir=colmap_dir\n    )\n\n    # メモリクリア\n    clear_memory()\n\n    # STEP 5: Running Gaussian Splatting\n    print(\"\\n\" + \"=\"*70)\n    print(\"STEP 5: Running Gaussian Splatting\")\n    print(\"=\"*70)\n\n    source_dir = output_dir\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    # STEP 6: Verify Output\n    print(\"\\n\" + \"=\"*70)\n    print(\"PIPELINE COMPLETE\")\n    print(\"=\"*70)\n\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\n    # 🔧 色の検証\n    print(\"\\n[Verifying colors in points3D.bin...]\")\n    verify_points3d_colors(os.path.join(colmap_dir, 'points3D.bin'))\n\n    print(f\"\\nOutput directory structure:\")\n    print(f\"  {output_dir}/\")\n    print(f\"  ├── images/              (processed images)\")\n    if preprocess_mode == 'biplet':\n        print(f\"  ├── original_images/     (original source images)\")\n    print(f\"  ├── sparse/0/            (COLMAP data WITH COLORS)\")\n    print(f\"  │   ├── cameras.bin\")\n    print(f\"  │   ├── images.bin\")\n    print(f\"  │   └── points3D.bin     (✓ WITH ACTUAL COLORS)\")\n    print(f\"  └── gaussian_splatting/  (GS output)\")\n\n    return gs_output\n\n\n# =====================================================================\n# 検証関数: points3D.binの色を確認\n# =====================================================================\n\ndef verify_points3d_colors(points3d_path):\n    \"\"\"\n    points3D.binの色を確認する\n    \"\"\"\n    import struct\n    \n    with open(points3d_path, 'rb') as f:\n        num_points = struct.unpack('Q', f.read(8))[0]\n        \n        colors = []\n        for _ in range(min(num_points, 10000)):  # 最初の1万点をチェック\n            f.read(8)  # point_id\n            f.read(24)  # xyz\n            rgb = struct.unpack('BBB', f.read(3))\n            colors.append(rgb)\n            f.read(8)  # error\n            track_length = struct.unpack('Q', f.read(8))[0]\n            f.read(track_length * 8)  # track\n    \n    colors = np.array(colors)\n    unique_colors = len(np.unique(colors, axis=0))\n    \n    print(f\"  Total points: {num_points:,}\")\n    print(f\"  Sampled: {len(colors):,} points\")\n    print(f\"  Mean RGB: [{colors.mean(axis=0)[0]:.1f}, {colors.mean(axis=0)[1]:.1f}, {colors.mean(axis=0)[2]:.1f}]\")\n    print(f\"  Std RGB:  [{colors.std(axis=0)[0]:.1f}, {colors.std(axis=0)[1]:.1f}, {colors.std(axis=0)[2]:.1f}]\")\n    print(f\"  Unique colors: {unique_colors:,}\")\n    \n    if unique_colors == 1 and colors[0][0] == 128:\n        print(\"  ❌ All points are GRAY (128, 128, 128)\")\n        print(\"  ⚠️  Colors were NOT applied!\")\n        return False\n    else:\n        print(\"  ✓ Points have ACTUAL colors!\")\n        return True\n\n","metadata":{"trusted":true,"id":"U7Lk41hLTKyF","execution":{"iopub.status.busy":"2026-02-01T07:17:30.474200Z","iopub.execute_input":"2026-02-01T07:17:30.474486Z","iopub.status.idle":"2026-02-01T07:17:30.495931Z","shell.execute_reply.started":"2026-02-01T07:17:30.474430Z","shell.execute_reply":"2026-02-01T07:17:30.495114Z"}},"outputs":[],"execution_count":8},{"cell_type":"code","source":"# =====================================================================\n# CELL 15: Run Pipeline\n# =====================================================================\nif __name__ == \"__main__\":\n    IMAGE_DIR = \"/kaggle/input/two-dogs/bike15\"\n    OUTPUT_DIR = \"/kaggle/working/output\"\n\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=30,\n        max_pairs=1000,\n        max_points=1000000,\n        conf_threshold=1.5,   \n        preprocess_mode='biplet'  # or 'none'\n    )\n\n    print(\"\\n\" + \"=\"*70)\n    print(\"PIPELINE COMPLETE\")\n    print(\"=\"*70)\n    print(f\"Output directory: {gs_output}\")","metadata":{"trusted":true,"id":"_-8kDLieTKyG","outputId":"beafd1de-a25c-4273-dfcb-10ca5301abb7","execution":{"iopub.status.busy":"2026-02-01T07:17:30.496932Z","iopub.execute_input":"2026-02-01T07:17:30.497858Z","iopub.status.idle":"2026-02-01T07:20:30.898387Z","shell.execute_reply.started":"2026-02-01T07:17:30.497833Z","shell.execute_reply":"2026-02-01T07:20:30.897574Z"}},"outputs":[{"name":"stdout","text":"======================================================================\nSTEP 0: Image Preprocessing (Biplet Crops)\n======================================================================\n\n=== Generating Biplet Crops (1024x1024) ===\n","output_type":"stream"},{"name":"stderr","text":"Creating biplets: 100%|██████████| 15/15 [00:02<00:00,  7.33it/s]\n","output_type":"stream"},{"name":"stdout","text":"\n✓ Biplet generation complete:\n  Source images: 15\n  Biplet crops generated: 30\n  Original size distribution: {'1440x1920': 15}\n✓ Copied 30 biplet images to /kaggle/working/output/images\n✓ Saved 15 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✓ Found 30 images\nLoaded 30 images\n\n======================================================================\nSTEP 2: Image Pair Selection (DINO)\n======================================================================\n\n=== Extracting DINO Global Features ===\nInitial memory state:\nGPU Memory - Allocated: 0.00GB, Reserved: 0.00GB\nCPU Memory Usage: 5.8%\n","output_type":"stream"},{"name":"stderr","text":"/usr/local/lib/python3.12/dist-packages/huggingface_hub/file_download.py:942: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n  warnings.warn(\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"preprocessor_config.json:   0%|          | 0.00/436 [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"5a2d6a2a21d24bf79d43a75106447ea4"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"config.json:   0%|          | 0.00/548 [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"01ac7c5469fc4234b62daedc71bf74bc"}},"metadata":{}},{"name":"stderr","text":"/usr/local/lib/python3.12/dist-packages/huggingface_hub/file_download.py:942: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n  warnings.warn(\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"model.safetensors:   0%|          | 0.00/346M [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"1f639ae63dac4a6db3536e36ddf6801c"}},"metadata":{}},{"name":"stderr","text":"DINO extraction: 100%|██████████| 8/8 [00:10<00:00,  1.34s/it]\n","output_type":"stream"},{"name":"stdout","text":"After DINO extraction:\nGPU Memory - Allocated: 0.03GB, Reserved: 0.06GB\nCPU Memory Usage: 7.9%\nInitial pairs from DINO: 290\nSelecting 50 diverse pairs from 290 candidates...\nSelected pairs cover 30 / 30 images (100.0%)\nSelected 50 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","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"config.json:   0%|          | 0.00/546 [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"6fbe229c6c8d4cf28e87cb463acc1170"}},"metadata":{}},{"name":"stdout","text":"⚠️  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","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"config.json:   0%|          | 0.00/450 [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"f3a0dd313bc240048d47e1e21ed42074"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"model.safetensors:   0%|          | 0.00/2.28G [00:00<?, ?B/s]","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"deb773553b9749f0b341e04e2b968f3d"}},"metadata":{}},{"name":"stdout","text":"✓ Loaded DUSt3R model as fallback\n✓ Model loaded on cuda\n\n=== Running MASt3R Reconstruction ===\nInitial memory state:\nGPU Memory - Allocated: 2.14GB, Reserved: 2.14GB\nCPU Memory Usage: 15.3%\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":"Processing 50 pairs...\nLoading 30 images at 224x224...\n>> Loading a list of 30 images\n - adding /kaggle/working/output/images/image_004_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_004_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_029_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_029_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_038_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_038_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_049_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_049_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_062_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_062_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_076_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_076_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_088_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_088_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_094_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_094_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_101_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_101_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_115_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_115_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_119_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_119_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_128_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_128_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_137_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_137_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_139_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_139_top.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_150_bottom.jpeg with resolution 1024x1024 --> 224x224\n - adding /kaggle/working/output/images/image_150_top.jpeg with resolution 1024x1024 --> 224x224\n (Found 30 images)\nLoaded 30 images\nAfter loading images:\nGPU Memory - Allocated: 2.14GB, Reserved: 2.14GB\nCPU Memory Usage: 15.4%\nCreating 50 image pairs...\n","output_type":"stream"},{"name":"stderr","text":"Preparing pairs: 100%|██████████| 50/50 [00:00<00:00, 322638.77it/s]\n","output_type":"stream"},{"name":"stdout","text":"Running MASt3R inference on 50 pairs...\n>> Inference with model on 50 image pairs\n","output_type":"stream"},{"name":"stderr","text":"  0%|          | 0/50 [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%|██████████| 50/50 [00:09<00:00,  5.24it/s]\n","output_type":"stream"},{"name":"stdout","text":"✓ MASt3R inference complete\nAfter inference:\nGPU Memory - Allocated: 2.14GB, Reserved: 2.14GB\nCPU Memory Usage: 15.7%\nRunning global alignment...\nComputing global alignment...\n init edge (4*,22*) score=61.01396942138672\n init edge (8*,22) score=50.93975830078125\n init edge (8,24*) score=24.73683738708496\n init edge (6*,22) score=23.54641342163086\n init edge (8,20*) score=23.08745002746582\n init edge (18*,24) score=22.09931755065918\n init edge (0*,22) score=18.92777442932129\n init edge (24,25*) score=16.81424331665039\n init edge (5*,22) score=16.769275665283203\n init edge (12*,22) score=16.5622501373291\n init edge (0,14*) score=13.714292526245117\n init edge (19*,25) score=11.434065818786621\n init edge (22,23*) score=11.384899139404297\n init edge (1*,22) score=10.828630447387695\n init edge (11*,25) score=8.875144004821777\n init edge (4,7*) score=8.490281105041504\n init edge (2*,22) score=8.216402053833008\n init edge (12,29*) score=6.481838703155518\n init edge (15*,22) score=6.353991508483887\n init edge (10*,24) score=6.015658855438232\n init edge (17*,24) score=5.83776330947876\n init edge (13*,19) score=3.9419987201690674\n init edge (21*,25) score=23.639514923095703\n init edge (20,26*) score=23.604904174804688\n init edge (12,16*) score=16.978376388549805\n init edge (3*,16) score=9.270556449890137\n init edge (9*,26) score=7.399363040924072\n init edge (26,28*) score=7.344329357147217\n init edge (26,27*) score=27.2646541595459\n init loss = 0.027633165940642357\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:02<00:00, 19.75it/s, lr=1.08654e-05 loss=0.0141021]\n","output_type":"stream"},{"name":"stdout","text":"✓ Global alignment complete (final loss: 0.014102)\nFinal memory state:\nGPU Memory - Allocated: 2.32GB, Reserved: 2.70GB\nCPU Memory Usage: 16.1%\n\n======================================================================\nSTEP 4: Converting to COLMAP (PINHOLE) WITH COLORS\n======================================================================\n\n=== Extracting Camera Parameters ===\n\nExample camera 0:\n  Original size: 1024x1024\n  MASt3R size: 224.0\n  Scale factor: 4.571\n  focals.shape: torch.Size([30, 1])\n  MASt3R focal: 289.39\n  Scaled focal: fx = fy = 1322.93\n  MASt3R pp: [112.00, 112.00]\n  Scaled pp: [512.00, 512.00]\n✓ Extracted parameters for 30 cameras\n✓ Total 3D points: 1505280\n✓ Points after confidence filtering (>1.5): 1179674\nExtracted 30 cameras with conf >= 1.5\nExtracted 1,179,674 3D points\n\n[Extracting colors from images...]\n\n=== Extracting Colors from Images ===\nExtracting colors from 30 images...\n  Example image 0:\n    Original size: 1024x1024\n    Resized to: 224x224\n    Colors shape: (50176, 3)\n✓ Total colors extracted: 1,505,280\n✓ Colors after confidence filtering (>1.5): 1,179,674\n✓ Colors match points: 1,179,674 colors for 1,179,674 points\n✓ Unique colors: 110,634\n✓ Good color diversity\n✓ Extracted 1,179,674 colors\n\n[Exporting COLMAP files with colors...]\nCOLMAP cameras.bin saved to /kaggle/working/output/sparse/0/cameras.bin\nCOLMAP images.bin saved to /kaggle/working/output/sparse/0/images.bin\nCOLMAP points3D.bin saved to /kaggle/working/output/sparse/0/points3D.bin\n  ✓ With actual RGB colors from images!\n\n✓ COLMAP binary files exported to /kaggle/working/output/sparse/0/\n  - cameras.bin: 30 cameras (PINHOLE model)\n  - images.bin: 30 images\n  - points3D.bin: 1179674 points WITH COLORS\n\n======================================================================\nSTEP 5: Running Gaussian Splatting\n======================================================================\n\n=== Running Gaussian Splatting ===\nCommand: python /kaggle/working/gaussian-splatting/train.py -s /kaggle/working/output -m /kaggle/working/output/gaussian_splatting --iterations 1000 --eval\n  Source: /kaggle/working/output\n  Output: /kaggle/working/output/gaussian_splatting\n","output_type":"stream"},{"name":"stderr","text":"2026-02-01 07:18:49.282970: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\nWARNING: All log messages before absl::InitializeLog() is called are written to STDERR\nE0000 00:00:1769930329.304553     766 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\nE0000 00:00:1769930329.311187     766 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\nW0000 00:00:1769930329.328184     766 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\nW0000 00:00:1769930329.328217     766 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\nW0000 00:00:1769930329.328220     766 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\nW0000 00:00:1769930329.328223     766 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","output_type":"stream"},{"name":"stdout","text":"Optimizing /kaggle/working/output/gaussian_splatting\nOutput folder: /kaggle/working/output/gaussian_splatting [01/02 07:18:53]\n------------LLFF HOLD------------- [01/02 07:18:53]\nReading camera 30/30 [01/02 07:18:53]\nConverting point3d.bin to .ply, will happen only the first time you open the scene. [01/02 07:18:53]\nLoading Training Cameras [01/02 07:19:00]\nLoading Test Cameras [01/02 07:19:02]\nNumber of points at initialisation :  1179674 [01/02 07:19:02]\n","output_type":"stream"},{"name":"stderr","text":"Training progress: 100%|██████████| 1000/1000 [01:12<00:00, 13.79it/s, Loss=0.2473092, Depth Loss=0.0000000]\n","output_type":"stream"},{"name":"stdout","text":"\n[ITER 1000] Saving Gaussians [01/02 07:20:17]\n\nTraining complete. [01/02 07:20:29]\n\n✓ Gaussian Splatting complete\n\n✓ Point cloud directory found: /kaggle/working/output/gaussian_splatting/point_cloud\n  ✓ iteration_1000/point_cloud.ply (296.52 MB)\n\n======================================================================\nPIPELINE COMPLETE\n======================================================================\n✓ Point cloud generated: /kaggle/working/output/gaussian_splatting/point_cloud/iteration_1000/point_cloud.ply\n  Size: 296.52 MB\n\n[Verifying colors in points3D.bin...]\n  Total points: 1,179,674\n  Sampled: 10,000 points\n  Mean RGB: [124.7, 120.5, 115.1]\n  Std RGB:  [64.8, 60.7, 57.4]\n  Unique colors: 7,437\n  ✓ Points have ACTUAL colors!\n\nOutput directory structure:\n  /kaggle/working/output/\n  ├── images/              (processed images)\n  ├── original_images/     (original source images)\n  ├── sparse/0/            (COLMAP data WITH COLORS)\n  │   ├── cameras.bin\n  │   ├── images.bin\n  │   └── points3D.bin     (✓ WITH ACTUAL COLORS)\n  └── gaussian_splatting/  (GS output)\n\n======================================================================\nPIPELINE COMPLETE\n======================================================================\nOutput directory: /kaggle/working/output/gaussian_splatting\n","output_type":"stream"}],"execution_count":9},{"cell_type":"code","source":"def convert_colmap_bins_to_csv(sparse_dir, output_prefix):\n    \"\"\"Convert all COLMAP binary files in a directory to CSV format.\"\"\"\n    print(f\"\\n=== Converting {sparse_dir} to CSV ===\")\n\n    cameras_df = bin_to_csv_cameras(\n        os.path.join(sparse_dir, 'cameras.bin'),\n        f\"{output_prefix}_cameras.csv\"\n    )\n\n    images_df = bin_to_csv_images(\n        os.path.join(sparse_dir, 'images.bin'),\n        f\"{output_prefix}_images.csv\"\n    )\n\n    points_df = bin_to_csv_points3d(\n        os.path.join(sparse_dir, 'points3D.bin'),\n        f\"{output_prefix}_points3d.csv\",\n        max_rows=10000\n    )\n\n    return cameras_df, images_df, points_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:20:30.899479Z","iopub.execute_input":"2026-02-01T07:20:30.900402Z","iopub.status.idle":"2026-02-01T07:20:30.905729Z","shell.execute_reply.started":"2026-02-01T07:20:30.900373Z","shell.execute_reply":"2026-02-01T07:20:30.904951Z"}},"outputs":[],"execution_count":10},{"cell_type":"code","source":"convert_colmap_bins_to_csv('/kaggle/working/output/sparse/0', 'output')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-01T07:20:30.906717Z","iopub.execute_input":"2026-02-01T07:20:30.907383Z","iopub.status.idle":"2026-02-01T07:20:32.142689Z","shell.execute_reply.started":"2026-02-01T07:20:30.907356Z","shell.execute_reply":"2026-02-01T07:20:32.141939Z"}},"outputs":[{"name":"stdout","text":"\n=== Converting /kaggle/working/output/sparse/0 to CSV ===\n✓ Cameras CSV saved: output_cameras.csv\n✓ Images CSV saved: output_images.csv\n✓ Points3D CSV saved: output_points3d.csv (sampled 10083 / 1179674 points)\n","output_type":"stream"},{"execution_count":11,"output_type":"execute_result","data":{"text/plain":"(    camera_id  model_id  width  height           fx           fy     cx     cy\n 0           1         1   1024    1024  1322.931920  1322.931920  512.0  512.0\n 1           2         1   1024    1024  1484.335938  1484.335938  512.0  512.0\n 2           3         1   1024    1024  1107.123884  1107.123884  512.0  512.0\n 3           4         1   1024    1024   971.500488   971.500488  512.0  512.0\n 4           5         1   1024    1024   988.139369   988.139369  512.0  512.0\n 5           6         1   1024    1024  2137.385603  2137.385603  512.0  512.0\n 6           7         1   1024    1024  1162.021554  1162.021554  512.0  512.0\n 7           8         1   1024    1024  1359.039621  1359.039621  512.0  512.0\n 8           9         1   1024    1024   980.173898   980.173898  512.0  512.0\n 9          10         1   1024    1024  1605.229911  1605.229911  512.0  512.0\n 10         11         1   1024    1024  1376.408343  1376.408343  512.0  512.0\n 11         12         1   1024    1024   972.693569   972.693569  512.0  512.0\n 12         13         1   1024    1024  1045.688825  1045.688825  512.0  512.0\n 13         14         1   1024    1024  1337.419224  1337.419224  512.0  512.0\n 14         15         1   1024    1024  1313.158901  1313.158901  512.0  512.0\n 15         16         1   1024    1024  1146.235561  1146.235561  512.0  512.0\n 16         17         1   1024    1024  1058.092704  1058.092704  512.0  512.0\n 17         18         1   1024    1024  1334.102818  1334.102818  512.0  512.0\n 18         19         1   1024    1024  1132.095215  1132.095215  512.0  512.0\n 19         20         1   1024    1024  1064.045759  1064.045759  512.0  512.0\n 20         21         1   1024    1024  1181.065569  1181.065569  512.0  512.0\n 21         22         1   1024    1024  1183.370675  1183.370675  512.0  512.0\n 22         23         1   1024    1024  1373.632254  1373.632254  512.0  512.0\n 23         24         1   1024    1024  1494.968750  1494.968750  512.0  512.0\n 24         25         1   1024    1024  1050.758998  1050.758998  512.0  512.0\n 25         26         1   1024    1024  1034.205148  1034.205148  512.0  512.0\n 26         27         1   1024    1024  1032.725237  1032.725237  512.0  512.0\n 27         28         1   1024    1024  1986.463728  1986.463728  512.0  512.0\n 28         29         1   1024    1024  1145.189872  1145.189872  512.0  512.0\n 29         30         1   1024    1024  1058.677037  1058.677037  512.0  512.0,\n     image_id        qw        qx        qy        qz        tx        ty  \\\n 0          1  0.927881 -0.072171 -0.275087 -0.241155  0.070648 -0.055844   \n 1          2  0.901012 -0.213078 -0.306379 -0.221150  0.065354 -0.048409   \n 2          3  0.975904 -0.183692 -0.070888 -0.094046  0.017266 -0.065307   \n 3          4  0.931620 -0.338329 -0.101396 -0.085652  0.020074 -0.037644   \n 4          5  0.999971  0.007519  0.001142 -0.000494  0.000000  0.000000   \n 5          6  0.976464 -0.213400  0.002227 -0.031195 -0.004513 -0.032888   \n 6          7  0.937563 -0.091922  0.305402  0.138763 -0.034499 -0.040977   \n 7          8  0.925227 -0.220974  0.285658  0.116298 -0.024236 -0.027639   \n 8          9  0.455139  0.042332  0.686274  0.565759 -0.066975 -0.071841   \n 9         10  0.461329 -0.053338  0.784942  0.410117 -0.063074 -0.046496   \n 10        11 -0.323792  0.054836  0.751358  0.572375  0.062037 -0.116881   \n 11        12 -0.341530  0.061126  0.769578  0.536070  0.061409 -0.062090   \n 12        13  0.743379 -0.100693 -0.534237 -0.389665  0.066534 -0.077246   \n 13        14  0.719731 -0.192419 -0.582786 -0.324535  0.058070 -0.041754   \n 14        15  0.795386 -0.146187 -0.499929 -0.309939  0.070590 -0.101209   \n 15        16  0.772093 -0.239315 -0.535441 -0.244753  0.069395 -0.056762   \n 16        17  0.641013  0.038547 -0.515508 -0.567334  0.069671 -0.069802   \n 17        18  0.654595 -0.048367 -0.591290 -0.468553  0.068984 -0.040825   \n 18        19 -0.253873 -0.029941  0.854300  0.452575  0.038126 -0.110592   \n 19        20 -0.247055  0.030679  0.892992  0.374950  0.031066 -0.049462   \n 20        21  0.115099  0.009068  0.835608  0.537056 -0.053340 -0.116988   \n 21        22  0.148318 -0.023712  0.879064  0.452422 -0.054064 -0.055615   \n 22        23  0.746056  0.001660  0.564887  0.352562 -0.107388 -0.066273   \n 23        24  0.728594 -0.097467  0.625235  0.262170 -0.109616 -0.029967   \n 24        25  0.187544 -0.019760  0.695446  0.693391 -0.032679 -0.039008   \n 25        26  0.244687 -0.132188  0.848541  0.450148 -0.013684 -0.053263   \n 26        27 -0.058081  0.018830  0.686333  0.724720  0.007058 -0.129410   \n 27        28 -0.048744  0.010848  0.794787  0.604831  0.011557 -0.078974   \n 28        29 -0.397708  0.106902  0.751044  0.516074  0.050834 -0.109185   \n 29        30 -0.426805  0.171233  0.790533  0.404443  0.055331 -0.055592   \n \n           tz  camera_id                   name  \n 0   0.062959          1  image_004_bottom.jpeg  \n 1   0.073141          2     image_004_top.jpeg  \n 2   0.103272          3  image_029_bottom.jpeg  \n 3   0.087217          4     image_029_top.jpeg  \n 4   0.000000          5  image_038_bottom.jpeg  \n 5   0.043278          6     image_038_top.jpeg  \n 6   0.017817          7  image_049_bottom.jpeg  \n 7   0.077299          8     image_049_top.jpeg  \n 8   0.113223          9  image_062_bottom.jpeg  \n 9   0.168308         10     image_062_top.jpeg  \n 10  0.168626         11  image_076_bottom.jpeg  \n 11  0.143139         12     image_076_top.jpeg  \n 12  0.089899         13  image_088_bottom.jpeg  \n 13  0.145371         14     image_088_top.jpeg  \n 14  0.153376         15  image_094_bottom.jpeg  \n 15  0.161768         16     image_094_top.jpeg  \n 16  0.078398         17  image_101_bottom.jpeg  \n 17  0.120976         18     image_101_top.jpeg  \n 18  0.193647         19  image_115_bottom.jpeg  \n 19  0.216639         20     image_115_top.jpeg  \n 20  0.201523         21  image_119_bottom.jpeg  \n 21  0.212228         22     image_119_top.jpeg  \n 22  0.147423         23  image_128_bottom.jpeg  \n 23  0.175961         24     image_128_top.jpeg  \n 24  0.197837         25  image_137_bottom.jpeg  \n 25  0.070437         26     image_137_top.jpeg  \n 26  0.132166         27  image_139_bottom.jpeg  \n 27  0.301035         28     image_139_top.jpeg  \n 28  0.158028         29  image_150_bottom.jpeg  \n 29  0.167978         30     image_150_top.jpeg  ,\n        point_id         x         y         z    r    g    b     error\n 0             1 -0.029637 -0.037321  0.098506   43   47   52  0.648973\n 1           118 -0.028862 -0.034588  0.097750   35   40   44  0.380816\n 2           235 -0.032865 -0.036781  0.101978   56   59   62  0.451116\n 3           352  0.120412 -0.070081  0.213010   60   56   50  0.593942\n 4           469  0.119345 -0.069761  0.215893  106  102   90  0.587462\n ...         ...       ...       ...       ...  ...  ...  ...       ...\n 10078   1179127 -0.022655  0.006154  0.131004   56   56   54  0.400867\n 10079   1179244  0.035582 -0.011458  0.167491  172  162  153  0.252837\n 10080   1179361 -0.023425  0.012970  0.128365  116  121  126  0.384711\n 10081   1179478  0.029623 -0.007577  0.163603   79   70   65  0.268693\n 10082   1179595 -0.022451  0.025236  0.124421  189  180  171  0.167128\n \n [10083 rows x 8 columns])"},"metadata":{}}],"execution_count":11},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}