Download utils/vggt_to_controlwave.py from SignerX/SignerX-inference-webui: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/datasets/SignerX/SignerX-inference-webui/resolve/main/utils/vggt_to_controlwave.py
- Command line
-
hf download hf://datasets/SignerX/SignerX-inference-webui/utils/vggt_to_controlwave.py
-
curl -L -o vggt_to_controlwave.py https://huggingface.co/datasets/SignerX/SignerX-inference-webui/resolve/main/utils/vggt_to_controlwave.py
12.1 kB
| """ | |
| Convert VGGT/COLMAP output to ControlWave format | |
| Handles conversion of cameras.bin and images.bin to formats used by ControlWave | |
| """ | |
| import numpy as np | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Tuple | |
| import json | |
| import shutil | |
| from .colmap_reader import COLMAPReader | |
| class VGGTToControlWaveConverter: | |
| """Convert VGGT sparse reconstruction to ControlWave format.""" | |
| def __init__(self, vggt_output_dir: str, output_dir: Optional[str] = None): | |
| """Initialize converter. | |
| Args: | |
| vggt_output_dir: Directory containing VGGT sparse reconstruction | |
| output_dir: Output directory for ControlWave files (default: same as input) | |
| """ | |
| self.vggt_dir = Path(vggt_output_dir) | |
| self.output_dir = Path(output_dir) if output_dir else self.vggt_dir.parent | |
| self.reader = COLMAPReader(vggt_output_dir) | |
| # Sample name from parent directory | |
| self.sample_name = self.vggt_dir.parent.name | |
| def convert_to_controlwave_format(self) -> Dict[str, str]: | |
| """Convert VGGT output to ControlWave format. | |
| Returns: | |
| Dictionary with paths to generated files | |
| """ | |
| print(f"Converting VGGT output to ControlWave format...") | |
| print(f"Input: {self.vggt_dir}") | |
| print(f"Output: {self.output_dir}") | |
| # Read COLMAP data | |
| cameras, images, points3D = self.reader.read_all() | |
| # Get poses and intrinsics | |
| poses = self.reader.get_camera_poses() | |
| intrinsics = self.reader.get_intrinsics() | |
| # Generate output files | |
| output_files = {} | |
| # 1. Save camera poses in ControlWave format | |
| cameras_file = self._save_cameras_bin(cameras, images, poses, intrinsics) | |
| output_files['cameras'] = str(cameras_file) | |
| # 2. Save images metadata | |
| images_file = self._save_images_bin(images) | |
| output_files['images'] = str(images_file) | |
| # 3. Copy PLY file if exists | |
| ply_src = self.vggt_dir / "points.ply" | |
| if ply_src.exists(): | |
| ply_dst = self.output_dir / f"{self.sample_name}_points.ply" | |
| shutil.copy2(ply_src, ply_dst) | |
| output_files['ply'] = str(ply_dst) | |
| # 4. Save camera metadata as JSON for easy access | |
| metadata_file = self._save_metadata(cameras, images, poses, intrinsics) | |
| output_files['metadata'] = str(metadata_file) | |
| print(f"\n✓ Conversion complete!") | |
| print(f"Generated files:") | |
| for key, path in output_files.items(): | |
| print(f" - {key}: {path}") | |
| return output_files | |
| def _save_cameras_bin(self, cameras: Dict, images: Dict, | |
| poses: List[np.ndarray], intrinsics: List[np.ndarray]) -> Path: | |
| """Save camera data in binary format compatible with ControlWave. | |
| Format: Custom binary format storing camera poses and parameters | |
| """ | |
| output_file = self.output_dir / f"{self.sample_name}_cameras.bin" | |
| # Prepare camera data | |
| camera_data = [] | |
| for i, (img_id, image) in enumerate(sorted(images.items())): | |
| camera = cameras[image.camera_id] | |
| pose = poses[i] | |
| K = intrinsics[i] | |
| # Extract camera parameters | |
| fx = K[0, 0] | |
| fy = K[1, 1] | |
| cx = K[0, 2] | |
| cy = K[1, 2] | |
| # Calculate FOV | |
| fov_x = 2 * np.arctan(camera.width / (2 * fx)) * 180 / np.pi | |
| fov_y = 2 * np.arctan(camera.height / (2 * fy)) * 180 / np.pi | |
| # Flatten pose matrix (4x4 = 16 values) | |
| pose_flat = pose.flatten() | |
| # Camera entry: pose (16 floats) + intrinsics (4 floats) + resolution (2 ints) + fov (2 floats) | |
| entry = { | |
| 'pose': pose_flat, | |
| 'intrinsics': np.array([fx, fy, cx, cy]), | |
| 'resolution': np.array([camera.width, camera.height], dtype=np.int32), | |
| 'fov': np.array([fov_x, fov_y]) | |
| } | |
| camera_data.append(entry) | |
| # Write binary file | |
| with open(output_file, 'wb') as f: | |
| # Header: number of cameras | |
| f.write(np.array([len(camera_data)], dtype=np.int32).tobytes()) | |
| # Write each camera | |
| for entry in camera_data: | |
| f.write(entry['pose'].astype(np.float32).tobytes()) | |
| f.write(entry['intrinsics'].astype(np.float32).tobytes()) | |
| f.write(entry['resolution'].tobytes()) | |
| f.write(entry['fov'].astype(np.float32).tobytes()) | |
| print(f"✓ Saved {len(camera_data)} cameras to {output_file}") | |
| return output_file | |
| def _save_images_bin(self, images: Dict) -> Path: | |
| """Save image metadata in binary format. | |
| Format: Simple list of image names with their IDs | |
| """ | |
| output_file = self.output_dir / f"{self.sample_name}_images.bin" | |
| # Sort by image ID | |
| sorted_images = sorted(images.items()) | |
| with open(output_file, 'wb') as f: | |
| # Header: number of images | |
| f.write(np.array([len(sorted_images)], dtype=np.int32).tobytes()) | |
| # Write each image entry | |
| for img_id, image in sorted_images: | |
| # Image ID (int32) | |
| f.write(np.array([img_id], dtype=np.int32).tobytes()) | |
| # Image name length (int32) | |
| name_bytes = image.name.encode('utf-8') | |
| f.write(np.array([len(name_bytes)], dtype=np.int32).tobytes()) | |
| # Image name (bytes) | |
| f.write(name_bytes) | |
| # Camera ID (int32) | |
| f.write(np.array([image.camera_id], dtype=np.int32).tobytes()) | |
| print(f"✓ Saved {len(sorted_images)} image entries to {output_file}") | |
| return output_file | |
| def _save_metadata(self, cameras: Dict, images: Dict, | |
| poses: List[np.ndarray], intrinsics: List[np.ndarray]) -> Path: | |
| """Save human-readable metadata as JSON.""" | |
| output_file = self.output_dir / f"{self.sample_name}_camera_metadata.json" | |
| metadata = { | |
| "source": "VGGT", | |
| "num_cameras": len(cameras), | |
| "num_images": len(images), | |
| "cameras": [], | |
| "images": [] | |
| } | |
| # Add camera info | |
| for cam_id, camera in cameras.items(): | |
| metadata["cameras"].append({ | |
| "id": cam_id, | |
| "model": camera.model, | |
| "width": camera.width, | |
| "height": camera.height, | |
| "params": camera.params.tolist() | |
| }) | |
| # Add image info with poses | |
| for i, (img_id, image) in enumerate(sorted(images.items())): | |
| pose = poses[i] | |
| K = intrinsics[i] | |
| metadata["images"].append({ | |
| "id": img_id, | |
| "name": image.name, | |
| "camera_id": image.camera_id, | |
| "quaternion": image.qvec.tolist(), | |
| "translation": image.tvec.tolist(), | |
| "pose_matrix": pose.tolist(), | |
| "intrinsic_matrix": K.tolist() | |
| }) | |
| with open(output_file, 'w') as f: | |
| json.dump(metadata, f, indent=2) | |
| print(f"✓ Saved metadata to {output_file}") | |
| return output_file | |
| def read_controlwave_cameras(cameras_bin_path: str) -> Tuple[List[np.ndarray], List[np.ndarray], List[Tuple[int, int]], List[Tuple[float, float]]]: | |
| """Read cameras from ControlWave binary format. | |
| Args: | |
| cameras_bin_path: Path to cameras.bin file | |
| Returns: | |
| Tuple of (poses, intrinsics, resolutions, fovs) | |
| """ | |
| poses = [] | |
| intrinsics = [] | |
| resolutions = [] | |
| fovs = [] | |
| with open(cameras_bin_path, 'rb') as f: | |
| # Read header | |
| num_cameras = np.frombuffer(f.read(4), dtype=np.int32)[0] | |
| # Read each camera | |
| for _ in range(num_cameras): | |
| # Pose matrix (16 floats) | |
| pose = np.frombuffer(f.read(64), dtype=np.float32).reshape(4, 4) | |
| poses.append(pose) | |
| # Intrinsics (4 floats: fx, fy, cx, cy) | |
| intrinsic_params = np.frombuffer(f.read(16), dtype=np.float32) | |
| K = np.eye(3) | |
| K[0, 0] = intrinsic_params[0] # fx | |
| K[1, 1] = intrinsic_params[1] # fy | |
| K[0, 2] = intrinsic_params[2] # cx | |
| K[1, 2] = intrinsic_params[3] # cy | |
| intrinsics.append(K) | |
| # Resolution (2 ints) | |
| resolution = np.frombuffer(f.read(8), dtype=np.int32) | |
| resolutions.append((resolution[0], resolution[1])) | |
| # FOV (2 floats) | |
| fov = np.frombuffer(f.read(8), dtype=np.float32) | |
| fovs.append((fov[0], fov[1])) | |
| return poses, intrinsics, resolutions, fovs | |
| def read_controlwave_images(images_bin_path: str) -> List[Dict]: | |
| """Read image metadata from ControlWave binary format. | |
| Args: | |
| images_bin_path: Path to images.bin file | |
| Returns: | |
| List of image metadata dictionaries | |
| """ | |
| images = [] | |
| with open(images_bin_path, 'rb') as f: | |
| # Read header | |
| num_images = np.frombuffer(f.read(4), dtype=np.int32)[0] | |
| # Read each image | |
| for _ in range(num_images): | |
| # Image ID | |
| img_id = np.frombuffer(f.read(4), dtype=np.int32)[0] | |
| # Image name length | |
| name_length = np.frombuffer(f.read(4), dtype=np.int32)[0] | |
| # Image name | |
| name = f.read(name_length).decode('utf-8') | |
| # Camera ID | |
| camera_id = np.frombuffer(f.read(4), dtype=np.int32)[0] | |
| images.append({ | |
| 'id': img_id, | |
| 'name': name, | |
| 'camera_id': camera_id | |
| }) | |
| return images | |
| # Convenience function | |
| def convert_vggt_to_controlwave(vggt_sparse_dir: str, output_dir: Optional[str] = None) -> Dict[str, str]: | |
| """Convert VGGT sparse reconstruction to ControlWave format. | |
| Args: | |
| vggt_sparse_dir: Path to VGGT results_vggt_sparse directory | |
| output_dir: Optional output directory (default: parent of vggt_sparse_dir) | |
| Returns: | |
| Dictionary with paths to generated files | |
| """ | |
| converter = VGGTToControlWaveConverter(vggt_sparse_dir, output_dir) | |
| return converter.convert_to_controlwave_format() | |
| if __name__ == "__main__": | |
| import sys | |
| if len(sys.argv) < 2: | |
| print("Usage: python vggt_to_controlwave.py /path/to/results_vggt_sparse [output_dir]") | |
| sys.exit(1) | |
| vggt_dir = sys.argv[1] | |
| output_dir = sys.argv[2] if len(sys.argv) > 2 else None | |
| try: | |
| output_files = convert_vggt_to_controlwave(vggt_dir, output_dir) | |
| print("\n✅ Conversion successful!") | |
| except Exception as e: | |
| print(f"\n❌ Conversion failed: {e}") | |
| import traceback | |
| traceback.print_exc() |