4
0
mirror of https://github.com/nerfstudio-project/nerfstudio.git synced 2026-11-11 18:44:21 +08:00
nerfstudio/nerfactory/dataloaders/image_sampler.py
Ethan Weber 0b042be956
Pipeline v2 (#258)
* Model class done, pipeline class still needs more visualization stuffs

* Renaming the BaseDataContainer to DataloaderOutputs and adding documentation

* Pushing more documentation, removing some trivial functions

* Updating dict typing

* Removing config dicts for collider

* Passing tests

* Pushing shell new dataloader

* Saving work, need to fix NGP model's get_loss_dict and Pipeline

* V1 of the ngp pipeline should be done. Need train script and debugging

* Updating with latest instant-ngp code

* Syntax updates from latest ngp graph code

* Linter, removing unneeded code in new NGP graph code

* Style

* Should be good now. Linter is happy and the code is verbatum current instant-ngp

* Everything done except novel view testing code

* Fixing some nitpicks

* Debugging dataloader

* merged master

* WOP. integrating pipeline with configs and notebook demo

* removing model folder

* a lot of name changing from Graph to Model

* in progress... changing trainer to use pipeline... broken right now

* pipeline code runs

* switched to val dataset

* makes run_eval.py work

* updated configs for pipeline change

* fixing test_run_train script

* fixing black and linting

* fix docs

* small updates to trainer

Co-authored-by: Jake Austin <jake-austin@berkeley.edu>
2022-08-10 14:59:45 -07:00

117 lines
4.1 KiB
Python

# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# 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
#
# http://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.
"""
Code for sampling images from a dataset of images.
"""
import random
from abc import abstractmethod
from typing import Union
import torch
from torch.utils.data import IterableDataset, default_collate
from nerfactory.dataloaders.image_dataset import ImageDataset
from nerfactory.utils.misc import get_dict_to_torch
class ImageSampler(IterableDataset):
"""Samples image_batch's.
Attributes:
dataset (torch.utils.data.Dataset): Dataset to sample from.
"""
# dataset: ImageDataset
def __init__(self, dataset: ImageDataset):
super().__init__()
self.dataset = dataset
@abstractmethod
def __getitem__(self, idx):
raise NotImplementedError()
@abstractmethod
def __iter__(self):
raise NotImplementedError()
class CacheImageSampler(ImageSampler):
"""Collated image dataset that implements caching of images.
Creates batches of the ImageDataset return type.
Args:
dataset (torch.utils.data.Dataset): Dataset to sample from.
num_samples_to_collate (int, optional): How many images to sample rays for each batch. Defaults to all images.
num_times_to_repeat_images (int): How often to collate new images. Defaults to every iteration.
device (Union[torch.device, str]): Device to perform computation. Defaults to "cpu".
"""
def __init__(
self,
dataset: ImageDataset,
num_images_to_sample_from: int = -1,
num_times_to_repeat_images: int = 0,
device: Union[torch.device, str] = "cpu",
):
super().__init__(dataset=dataset)
self.dataset = dataset
self.cache_all_images = num_images_to_sample_from == -1
self.num_images_to_sample_from = len(self.dataset) if self.cache_all_images else num_images_to_sample_from
self.num_times_to_repeat_images = num_times_to_repeat_images
self.device = device
self.num_repeated = self.num_times_to_repeat_images # starting value
self.first_time = True
self.cached_collated_batch = None
if self.cache_all_images:
self.cached_collated_batch = self._get_collated_batch()
def __getitem__(self, idx):
return self.dataset.__getitem__(idx)
def _get_batch_list(self):
"""Returns a list of batches from the dataset attribute."""
indices = random.sample(range(len(self.dataset)), k=self.num_images_to_sample_from)
batch_list = [self.dataset.__getitem__(idx) for idx in indices]
return batch_list
def _get_collated_batch(self):
"""Returns a collated batch."""
batch_list = self._get_batch_list()
collated_batch = default_collate(batch_list)
collated_batch = get_dict_to_torch(collated_batch, device=self.device)
return collated_batch
def __iter__(self):
while True:
if self.cache_all_images:
collated_batch = self.cached_collated_batch
elif self.first_time or (
self.num_times_to_repeat_images != -1 and self.num_repeated >= self.num_times_to_repeat_images
):
# trigger a reset
self.num_repeated = 0
collated_batch = self._get_collated_batch()
# possibly save a cached item
self.cached_collated_batch = collated_batch if self.num_times_to_repeat_images != 0 else None
self.first_time = False
else:
collated_batch = self.cached_collated_batch
self.num_repeated += 1
yield collated_batch