sfrustum / scripts /render_official_gpnerf_replica.py
Isaac114514's picture
Add files using upload-large-folder tool
0be3110 verified
from dataclasses import dataclass, field
import importlib.util
from pathlib import Path
import sys
import time
import types
import imageio.v2 as imageio
import numpy as np
import torch
import torch.nn as nn
import tyro
from einops import rearrange
def build_label_colormap(size):
colormap = np.zeros((size, 3), dtype=np.uint8)
indices = np.arange(size, dtype=np.uint32)
for shift in range(8):
for channel in range(3):
colormap[:, channel] |= ((indices >> channel) & 1).astype(np.uint8) << (7 - shift)
indices >>= 3
return colormap
def install_import_stubs():
sys.modules['h5py'] = types.ModuleType('h5py')
transforms3d = types.ModuleType('transforms3d')
axangles = types.ModuleType('transforms3d.axangles')
euler = types.ModuleType('transforms3d.euler')
def mat2axangle(matrix):
del matrix
return np.array([1.0, 0.0, 0.0], dtype=np.float32), 0.0
def euler2mat(ai, aj, ak):
del ai, aj, ak
return np.eye(3, dtype=np.float32)
axangles.mat2axangle = mat2axangle
euler.euler2mat = euler2mat
transforms3d.axangles = axangles
transforms3d.euler = euler
sys.modules['transforms3d'] = transforms3d
sys.modules['transforms3d.axangles'] = axangles
sys.modules['transforms3d.euler'] = euler
mmcv = types.ModuleType('mmcv')
mmcv_cnn = types.ModuleType('mmcv.cnn')
class ConvModule(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
conv_cfg=None,
norm_cfg=None,
act_cfg=None,
inplace=False,
):
del conv_cfg, norm_cfg, act_cfg, inplace
super().__init__()
self.conv = nn.Conv2d(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
)
def forward(self, x):
return self.conv(x)
mmcv_cnn.ConvModule = ConvModule
mmcv.cnn = mmcv_cnn
sys.modules['mmcv'] = mmcv
sys.modules['mmcv.cnn'] = mmcv_cnn
mmengine = types.ModuleType('mmengine')
mmengine_model = types.ModuleType('mmengine.model')
class BaseModule(nn.Module):
def __init__(self, init_cfg=None):
del init_cfg
super().__init__()
mmengine_model.BaseModule = BaseModule
mmengine.model = mmengine_model
sys.modules['mmengine'] = mmengine
sys.modules['mmengine.model'] = mmengine_model
mmdet = types.ModuleType('mmdet')
mmdet_registry = types.ModuleType('mmdet.registry')
mmdet_utils = types.ModuleType('mmdet.utils')
mmdet_registry.MODELS = object()
mmdet_utils.ConfigType = dict
mmdet_utils.MultiConfig = dict
mmdet_utils.OptConfigType = dict
mmdet.registry = mmdet_registry
mmdet.utils = mmdet_utils
sys.modules['mmdet'] = mmdet
sys.modules['mmdet.registry'] = mmdet_registry
sys.modules['mmdet.utils'] = mmdet_utils
@dataclass
class Args:
official_repo: Path = Path('/mnt/public/cjw/projs/SemanticFrustum/ref/GP-NeRF')
ported_repo: Path = Path('/mnt/public/cjw/projs/sfrustum')
config_path: Path = Path('/mnt/public/cjw/projs/SemanticFrustum/ref/GP-NeRF/configs/gpnerf_replica.txt')
scene_list: Path = Path('/mnt/public/cjw/projs/SemanticFrustum/ref/GP-NeRF/configs/replica_test_split.txt')
checkpoint: Path = Path('/mnt/public/cjw/projs/SemanticFrustum/ckpts/gpnerf_replica.pth')
rootdir: Path = Path('/tmp/gpnerf_ref_root')
output_dir: Path = Path('/mnt/public/cjw/projs/SemanticFrustum/outputs/official_gpnerf_replica_stride1')
render_stride: int = 1
chunk_size: int = 8000
num_images_per_scene: int = 10
scenes: list[str] = field(default_factory=list)
def patch_official_modules(semantic_branch, replica_dataset_module):
original_sem_init = semantic_branch.NeRFSemSegFPNHead.__init__
def patched_sem_init(
self,
args,
feature_strides=[2, 4, 8, 16],
feature_channels=[128, 128, 128, 128],
num_classes=20,
):
del num_classes
return original_sem_init(
self,
args,
feature_strides=feature_strides,
feature_channels=feature_channels,
num_classes=args.num_classes,
)
semantic_branch.NeRFSemSegFPNHead.__init__ = patched_sem_init
original_getitem = replica_dataset_module.ReplicaValDataset.__getitem__
def patched_getitem(self, idx):
item = original_getitem(self, idx)
depth = item['true_depth']
depth_range = item['depth_range']
depth_mask = torch.ones_like(depth, dtype=torch.float32)
depth_mask[depth > (depth_range[1] - 0.1)] = 0.0
depth_mask[depth < (depth_range[0] + 0.1)] = 0.0
item['depth_mask'] = depth_mask
return item
replica_dataset_module.ReplicaValDataset.__getitem__ = patched_getitem
def build_official_args(config_module, args: Args):
parser = config_module.config_parser()
official_args = parser.parse_args(
[
'--config',
str(args.config_path),
'--ckpt_path',
str(args.checkpoint),
'--rootdir',
str(args.rootdir) + '/',
'--expname',
'official_gpnerf_replica_stride1',
'--local_rank',
'0',
]
)
official_args.distributed = False
official_args.no_reload = False
official_args.no_load_opt = True
official_args.no_load_scheduler = True
official_args.num_workers = 0
official_args.render_stride = args.render_stride
official_args.chunk_size = args.chunk_size
return official_args
def save_prediction_images(output_dir, sample_idx, rgb_pred, sem_pred, color_map):
rgb_path = output_dir / f'rgb_pred_{sample_idx:03d}.png'
sem_path = output_dir / f'sem_pred_{sample_idx:03d}.png'
imageio.imwrite(rgb_path, (255.0 * np.clip(rgb_pred, 0.0, 1.0)).astype(np.uint8))
sem_labels = sem_pred.argmax(axis=-1)
imageio.imwrite(sem_path, color_map[sem_labels])
return rgb_path, sem_path
def build_full_resolution_semantic_head(args: Args, official_args):
module_path = args.ported_repo / 'modules' / 'gpnerf_semantic_head.py'
spec = importlib.util.spec_from_file_location('ported_gpnerf_semantic_head', module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
checkpoint = torch.load(args.checkpoint, map_location='cpu')
sem_head = module.NeRFSemSegFPNHead(official_args.num_classes, n_p=official_args.n_p).cuda()
sem_head.load_state_dict(checkpoint['sem_seg_head'], strict=True)
sem_head.eval()
return sem_head
def render_scene(scene_name, dataset, model, full_res_sem_head, projector, official_args, color_map, output_dir):
from gpnerf.render_image import render_single_image
from gpnerf.sample_ray import RaySamplerSingleImage
output_dir.mkdir(parents=True, exist_ok=True)
scene_records = []
total_samples = min(len(dataset), official_args.num_images_per_scene if hasattr(official_args, 'num_images_per_scene') else len(dataset))
for sample_idx in range(total_samples):
start_time = time.time()
print(f'[{scene_name}] rendering sample {sample_idx + 1}/{total_samples}', flush=True)
raw = dataset[sample_idx]
batch = {}
for key, value in raw.items():
if torch.is_tensor(value):
batch[key] = value.unsqueeze(0)
else:
batch[key] = [value]
ray_sampler = RaySamplerSingleImage(batch, 'cuda:0', render_stride=official_args.render_stride)
ray_batch = ray_sampler.get_all()
with torch.no_grad():
ref_coarse_feats, _, ref_deep_semantics = model.feature_net(
rearrange(ray_batch['src_rgbs'].squeeze(0), 'v h w c -> v c h w')
)
ref_coarse_feats = ref_coarse_feats.contiguous()
ref_deep_semantics = model.feature_fpn(ref_deep_semantics).contiguous()
ret = render_single_image(
ray_sampler=ray_sampler,
ray_batch=ray_batch,
model=model,
projector=projector,
chunk_size=official_args.chunk_size,
N_samples=official_args.N_samples,
inv_uniform=official_args.inv_uniform,
det=True,
N_importance=official_args.N_importance,
white_bkgd=official_args.white_bkgd,
render_stride=official_args.render_stride,
featmaps=ref_coarse_feats,
deep_semantics=ref_deep_semantics,
ret_alpha=official_args.N_importance > 0,
single_net=official_args.single_net,
)
semantic_key = 'outputs_fine' if ret['outputs_fine'] is not None else 'outputs_coarse'
semantic_feats = ret[semantic_key]['feats_out']
semantic_feats = rearrange(semantic_feats, 'h w c -> 1 c h w')
target_feat_size = (
official_args.original_height // full_res_sem_head.common_stride,
official_args.original_width // full_res_sem_head.common_stride,
)
if semantic_feats.shape[-2:] != target_feat_size:
semantic_feats = torch.nn.functional.interpolate(
semantic_feats,
size=target_feat_size,
mode='bilinear',
align_corners=True,
)
sem_pred, _, _ = full_res_sem_head(semantic_feats.to(ref_deep_semantics.device), None, None)
sem_pred = rearrange(sem_pred[0], 'c h w -> h w c').detach().cpu().numpy()
rgb_pred = (
ret['outputs_fine']['rgb']
if ret['outputs_fine'] is not None
else ret['outputs_coarse']['rgb']
).detach().cpu().numpy()
rgb_path, sem_path = save_prediction_images(output_dir, sample_idx, rgb_pred, sem_pred, color_map)
scene_records.append(
{
'sample_idx': sample_idx,
'rgb_input_path': batch['rgb_path'][0],
'rgb_pred_path': str(rgb_path),
'sem_pred_path': str(sem_path),
'render_time_sec': time.time() - start_time,
}
)
print(
f'[{scene_name}] finished sample {sample_idx + 1}/{total_samples} in {scene_records[-1]["render_time_sec"]:.2f}s',
flush=True,
)
return {
'scene': scene_name,
'num_images': len(scene_records),
'records': scene_records,
}
def main():
args = tyro.cli(Args)
torch.backends.cudnn.enabled = False
install_import_stubs()
sys.path.insert(0, str(args.official_repo))
import config as official_config
import gpnerf.semantic_branch as semantic_branch
import gpnerf.data_loaders.replica_dataset as replica_dataset_module
from gpnerf.model import GPNeRFModel
from gpnerf.projection import Projector
patch_official_modules(semantic_branch, replica_dataset_module)
official_args = build_official_args(official_config, args)
official_args.num_images_per_scene = args.num_images_per_scene
scene_names = args.scenes
if not scene_names:
scene_names = np.loadtxt(args.scene_list, dtype=str).tolist()
if isinstance(scene_names, str):
scene_names = [scene_names]
color_map = build_label_colormap(official_args.num_classes + 1)
torch.cuda.set_device(0)
model = GPNeRFModel(official_args, load_opt=False, load_scheduler=False)
model.switch_to_eval()
full_res_sem_head = build_full_resolution_semantic_head(args, official_args)
projector = Projector(device='cuda:0')
summary = {
'render_stride': official_args.render_stride,
'chunk_size': official_args.chunk_size,
'checkpoint': str(args.checkpoint),
'scenes': [],
}
for scene_name in scene_names:
dataset = replica_dataset_module.ReplicaValDataset(official_args, is_train=False, scenes=scene_name)
scene_output_dir = args.output_dir / scene_name
summary['scenes'].append(
render_scene(
scene_name,
dataset,
model,
full_res_sem_head,
projector,
official_args,
color_map,
scene_output_dir,
)
)
args.output_dir.mkdir(parents=True, exist_ok=True)
(args.output_dir / 'summary.json').write_text(
__import__('json').dumps(summary, indent=2, ensure_ascii=False)
)
if __name__ == '__main__':
main()