File size: 11,263 Bytes
25a49bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: kmaninis@google.com (Kevis-Kokitsi Maninis)
"""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:  # Mesh loading is optional for lightweight data access.
  trimesh = None

try:
  import mediapy as media
except ImportError:  # Loading video.mp4 is optional; image frames are primary.
  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)
  # Don't change the scale_factor.
  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)

  # Load the 3D mesh.
  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)

  # Load the images.
  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))

  # Load the video, for video scenes.
  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