| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """Useful functions for interfacing NAVI data.""" |
|
|
| import json |
| import os |
| from pathlib import Path |
| from typing import Any, Dict, Iterable, List, Optional, Text |
|
|
| import numpy as np |
| from PIL import Image |
| from PIL import ImageOps |
| import transformations |
|
|
| try: |
| import trimesh |
| except ImportError: |
| trimesh = None |
|
|
| try: |
| import mediapy as media |
| except ImportError: |
| media = None |
|
|
|
|
| def read_image(image_path: Text) -> Image.Image: |
| """Reads a NAVI image (and rotates it according to the metadata).""" |
| return ImageOps.exif_transpose(Image.open(image_path)) |
|
|
|
|
| def decode_depth(depth_encoded: Image.Image, scale_factor: float = 10.): |
| """Decodes depth (disparity) from an encoded image (with encode_depth). |
| |
| Args: |
| depth_encoded: The encoded PIL uint16 image of the depth |
| scale_factor: float, factor to reduce quantization error. MUST BE THE SAME |
| as the value used to encode the depth. |
| |
| Returns: |
| depth: float[h, w] image with decoded depth values. |
| """ |
| max_val = (2**16) - 1 |
| disparity = np.array(depth_encoded).astype('uint16') |
| disparity = disparity.astype(np.float32) / (max_val * scale_factor) |
| disparity[disparity == 0] = np.inf |
| depth = 1 / disparity |
| return depth |
|
|
|
|
| def read_depth_from_png(depth_image_path: str) -> np.ndarray: |
| """Reads encoded depth image from an uint16 png file.""" |
| if not depth_image_path.endswith('.png'): |
| raise ValueError(f'Path {depth_image_path} is not a valid png image path.') |
|
|
| depth_image = Image.open(depth_image_path) |
| |
| depth = decode_depth(depth_image, scale_factor=10) |
| return depth |
|
|
|
|
| def convert_to_triangles(vertices: np.ndarray, faces: np.ndarray) -> np.ndarray: |
| """Converts vertices and faces to triangle format float32[N, 3, 3].""" |
| faces = faces.reshape([-1]) |
| tri_flat = vertices[faces, :] |
| return tri_flat.reshape((-1, 3, 3)).astype(np.float32) |
|
|
|
|
| def camera_matrices_from_annotation(annotation): |
| """Convert camera pose and intrinsics to 4x4 matrices.""" |
| translation = transformations.translate(annotation['camera']['t']) |
| rotation = transformations.quaternion_to_rotation_matrix( |
| annotation['camera']['q']) |
| object_to_world = translation @ rotation |
| h, w = annotation['image_size'] |
| focal_length_pixels = annotation['camera']['focal_length'] |
| intrinsics = transformations.gl_projection_matrix_from_intrinsics( |
| w, h, focal_length_pixels, focal_length_pixels, w//2, h//2, zfar=1000) |
| return object_to_world, intrinsics |
|
|
|
|
| def frame_png_name(image_filename: Text) -> str: |
| """Returns the PNG filename for a frame image filename.""" |
| return str(image_filename).rsplit('.', 1)[0] + '.png' |
|
|
|
|
| def frame_index_from_filename(filename: Text) -> int: |
| """Extracts the numeric frame index from `frame_XXXXX.jpg` style names.""" |
| stem = Path(filename).stem |
| if stem.startswith('frame_'): |
| return int(stem.replace('frame_', '', 1)) |
| return int(stem) |
|
|
|
|
| def sort_annotations_by_frame(annotations: Iterable[Dict[str, Any]] |
| ) -> List[Dict[str, Any]]: |
| """Sorts annotations by their video frame number.""" |
| return sorted(annotations, key=lambda anno: frame_index_from_filename( |
| anno['filename'])) |
|
|
|
|
| def _require_optional_dependency(module, package_name: str): |
| if module is None: |
| raise ImportError( |
| f'`{package_name}` is required for this operation. Install the NAVI ' |
| 'code requirements with `pip install -r requirements.txt`.') |
|
|
|
|
| def _read_json(path: Path): |
| with open(path, 'r') as f: |
| return json.load(f) |
|
|
|
|
| def load_eval_subset_info(navi_eval_root: Text, subset: str) -> Dict[str, Any]: |
| """Loads `subset_info.json` for a navi_eval subset. |
| |
| Args: |
| navi_eval_root: Path to `/root/autodl-tmp/data/navi/navi_eval`. |
| subset: `normal` or `cheat`. |
| |
| Returns: |
| The parsed subset metadata dictionary. |
| """ |
| subset_info_path = Path(navi_eval_root) / subset / 'subset_info.json' |
| return _read_json(subset_info_path) |
|
|
|
|
| def list_eval_objects(navi_eval_root: Text, subset: str) -> List[str]: |
| """Returns object ids in the stable benchmark order.""" |
| subset_info = load_eval_subset_info(navi_eval_root, subset) |
| return [record['object_id'] for record in subset_info['objects']] |
|
|
|
|
| def _select_eval_record(subset_info: Dict[str, Any], |
| object_id: Optional[str] = None, |
| index: Optional[int] = None) -> Dict[str, Any]: |
| if object_id is None and index is None: |
| index = 0 |
| if object_id is not None and index is not None: |
| raise ValueError('Pass either `object_id` or `index`, not both.') |
| if object_id is not None: |
| for record in subset_info['objects']: |
| if record['object_id'] == object_id: |
| return record |
| raise KeyError(f'Object `{object_id}` is not in subset_info.') |
| records = subset_info['objects'] |
| if index < 0 or index >= len(records): |
| raise IndexError(f'Index {index} is out of range for {len(records)} ' |
| 'objects.') |
| return records[index] |
|
|
|
|
| def load_eval_object(navi_eval_root: Text, |
| subset: str, |
| object_id: Optional[str] = None, |
| index: Optional[int] = None, |
| max_num_images: Optional[int] = None, |
| load_images: bool = True, |
| load_depths: bool = False, |
| load_masks: bool = False, |
| load_mesh: bool = False, |
| load_video: bool = False, |
| sort_frames: bool = True) -> Dict[str, Any]: |
| """Loads one object from the curated `navi_eval` dataset. |
| |
| The expected folder layout is: |
| |
| ``` |
| navi_eval/{subset}/{object_id}/ |
| model.glb |
| info.json |
| video/ |
| annotations.json |
| images/ |
| masks/ |
| depth/ |
| video.mp4 |
| ``` |
| |
| Args: |
| navi_eval_root: Path to the `navi_eval` root. |
| subset: `normal` or `cheat`. |
| object_id: Object id to load. If omitted, `index` is used. |
| index: Object index in `subset_info.json`. Defaults to 0. |
| max_num_images: Optional cap on loaded annotations/images. |
| load_images: Whether to load PIL images from `video/images`. |
| load_depths: Whether to decode depth PNGs from `video/depth`. |
| load_masks: Whether to load mask PNGs from `video/masks`. |
| load_mesh: Whether to load `model.glb` with trimesh. |
| load_video: Whether to load `video/video.mp4` with mediapy. |
| sort_frames: Whether to sort annotations by numeric frame id. |
| |
| Returns: |
| A dictionary with paths, metadata, annotations, and requested payloads. |
| """ |
| navi_eval_root = Path(navi_eval_root) |
| subset_info = load_eval_subset_info(navi_eval_root, subset) |
| record = _select_eval_record(subset_info, object_id=object_id, index=index) |
| object_id = record['object_id'] |
|
|
| object_root = navi_eval_root / subset / object_id |
| video_root = object_root / 'video' |
| model_path = object_root / 'model.glb' |
| info_path = object_root / 'info.json' |
| annotations_path = video_root / 'annotations.json' |
|
|
| info = _read_json(info_path) |
| annotations = _read_json(annotations_path) |
| if sort_frames: |
| annotations = sort_annotations_by_frame(annotations) |
| if max_num_images is not None: |
| annotations = annotations[:max_num_images] |
|
|
| images = [] |
| if load_images: |
| for anno in annotations: |
| images.append(read_image(video_root / 'images' / anno['filename'])) |
|
|
| depths = [] |
| if load_depths: |
| for anno in annotations: |
| depths.append(read_depth_from_png( |
| str(video_root / 'depth' / frame_png_name(anno['filename'])))) |
|
|
| masks = [] |
| if load_masks: |
| for anno in annotations: |
| masks.append(Image.open( |
| video_root / 'masks' / frame_png_name(anno['filename']))) |
|
|
| mesh = None |
| if load_mesh: |
| _require_optional_dependency(trimesh, 'trimesh') |
| mesh = trimesh.load(model_path) |
|
|
| video = None |
| if load_video: |
| _require_optional_dependency(media, 'mediapy') |
| video = media.read_video(video_root / 'video.mp4') |
|
|
| camera_matrices = [ |
| camera_matrices_from_annotation(anno) for anno in annotations |
| ] |
|
|
| return { |
| 'subset': subset, |
| 'object_id': object_id, |
| 'index': record['index'], |
| 'record': record, |
| 'subset_info': subset_info, |
| 'object_root': object_root, |
| 'video_root': video_root, |
| 'model_path': model_path, |
| 'info_path': info_path, |
| 'annotations_path': annotations_path, |
| 'info': info, |
| 'annotations': annotations, |
| 'camera_matrices': camera_matrices, |
| 'images': images, |
| 'depths': depths, |
| 'masks': masks, |
| 'mesh': mesh, |
| 'video': video, |
| } |
|
|
|
|
| def iter_eval_subset(navi_eval_root: Text, subset: str, **load_kwargs): |
| """Yields `load_eval_object(...)` for every object in benchmark order.""" |
| subset_info = load_eval_subset_info(navi_eval_root, subset) |
| for record in subset_info['objects']: |
| yield load_eval_object( |
| navi_eval_root, |
| subset, |
| object_id=record['object_id'], |
| **load_kwargs) |
|
|
|
|
| def load_scene_data(query: str, navi_release_root: str, |
| max_num_images: Optional[int] = None, load_video: bool = False): |
| """Loads the data of a certain scene from a query.""" |
| query_data = query.split('-') |
| video_id = None |
| if len(query_data) == 5: |
| object_id, scene_type, scene_idx, camera_model, video_id = query_data |
| scene_name = f'{scene_type}-{scene_idx}' |
| scene = f'{scene_name}-{camera_model}-{video_id}' |
| elif len(query_data) == 4: |
| object_id, scene_type, scene_idx, camera_model = query_data |
| scene_name = f'{scene_type}-{scene_idx}' |
| scene = f'{scene_name}-{camera_model}' |
| elif len(query_data) == 2: |
| object_id, scene_name = query_data |
| scene = scene_name |
| assert scene_name == 'wild_set' |
| else: |
| raise ValueError(f'Query {query} is not valid.') |
|
|
| annotation_json_path = os.path.join( |
| navi_release_root, object_id, scene, |
| 'annotations.json') |
| with open(annotation_json_path, 'r') as f: |
| annotations = json.load(f) |
|
|
| |
| mesh_path = os.path.join( |
| navi_release_root, object_id, '3d_scan', f'{object_id}.obj') |
| _require_optional_dependency(trimesh, 'trimesh') |
| mesh = trimesh.load(mesh_path) |
|
|
| |
| images = [] |
| for i_anno, anno in enumerate(annotations): |
| if max_num_images is not None and i_anno >=max_num_images: |
| break |
| image_path = os.path.join( |
| navi_release_root, object_id, scene, 'images', anno['filename']) |
| images.append(read_image(image_path)) |
|
|
| |
| video = None |
| if video_id and load_video: |
| _require_optional_dependency(media, 'mediapy') |
| video_path = os.path.join( |
| navi_release_root, object_id, scene, 'video.mp4') |
| video = media.read_video(video_path) |
| return annotations, mesh, images, video |
|
|