AGT / code /agt /eval /method_dir.py
MRBSTUDIO's picture
Update the inference and evaluation code
2ad60ce verified
Raw History Blame Contribute Delete
3.24 kB
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
FRAMES = 20
DEPTH_SEMANTICS = 'normalized_expected_camera_z'
def png_name(k: int) -> str:
return f'frame_{k:02d}.png'
def check_positions(positions) -> list:
positions = list(range(FRAMES)) if positions is None else [int(k) for k in positions]
if not positions or positions != sorted(set(positions)) or positions[0] < 0 or positions[-1] >= FRAMES:
raise ValueError(f'Bad positions {positions}: need ascending unique values in 0..{FRAMES - 1}')
return positions
def select_scored(output, n_samples, scored_positions):
rgb = output['rgb']
positions = [int(p) for p in output.get('positions', range(n_samples))]
if len(positions) != len(rgb) or len(set(positions)) != len(positions):
raise ValueError(f'{len(rgb)} renders for positions {positions}')
missing = [p for p in scored_positions if p not in positions]
if missing:
raise ValueError(f'Prediction lacks scored protocol samples {missing}')
return rgb[[positions.index(p) for p in scored_positions]]
class MethodDirectory:
def __init__(self, root):
self.root = Path(root)
self.meta = json.loads((self.root / 'meta.json').read_text())
self.positions = check_positions(self.meta.get('positions'))
path = self.root / 'depth_meta.json'
self.depth = json.loads(path.read_text()) if path.is_file() else None
if self.depth is not None and self.depth.get('semantics') != DEPTH_SEMANTICS:
raise ValueError(f'{path}: depth semantics must be {DEPTH_SEMANTICS!r}')
def predict(self, clip: dict) -> dict:
entry = self.meta['files'].get(clip['clip_id'])
if entry is None:
raise ValueError(f'{self.root}: no renders for {clip["clip_id"]}')
directory = self.root / clip['clip_id']
if entry['format'] == 'npz':
with np.load(directory / 'frames.npz', allow_pickle=False) as f:
rgb = f['rgb']
else:
from PIL import Image
rgb = np.stack([np.asarray(Image.open(directory / png_name(k)).convert('RGB')) for k in self.positions])
if rgb.shape[0] != len(self.positions) or tuple(rgb.shape[2:0:-1]) != tuple(self.meta['native_resolution']):
raise ValueError(f'{directory}: renders {rgb.shape} != {len(self.positions)} x {self.meta["native_resolution"]}')
if rgb.dtype == np.float16:
rgb = rgb.astype(np.float32)
return {'rgb': rgb, 'positions': self.positions}
def predict_depth(self, clip: dict) -> dict | None:
if clip['clip_id'] not in self.depth['files']:
return None
path = self.root / clip['clip_id'] / 'depth.npz'
with np.load(path, allow_pickle=False) as f:
depth, alpha = f['depth'], f['alpha']
positions = check_positions(self.depth['positions'])
if depth.shape[0] != len(positions) or tuple(depth.shape[2:0:-1]) != tuple(self.depth['native_resolution']):
raise ValueError(f'{path}: depth {depth.shape} != {len(positions)} x {self.depth["native_resolution"]}')
return {'depth': depth, 'alpha': alpha, 'positions': positions}