mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-06 07:48:50 +08:00
Merge branch 'master' into Data-Refactoring
This commit is contained in:
55 files changed
+3295
-30047
No files matched your search
@@ -56,6 +56,7 @@ class TrainerConfig:
|
||||
steps_per_save: int = MISSING
|
||||
steps_per_test: int = MISSING
|
||||
max_num_iterations: int = MISSING
|
||||
mixed_precision: bool = MISSING
|
||||
resume_train: ResumeTrainConfig = MISSING
|
||||
|
||||
|
||||
|
||||
@@ -45,6 +45,18 @@ def check_profiler_enabled(func: Callable) -> Callable:
|
||||
return wrapper
|
||||
|
||||
|
||||
def check_visualizer_enabled(func: Callable) -> Callable:
|
||||
"""Decorator: check if visualizer is enabled"""
|
||||
|
||||
def wrapper(self, *args, **kwargs):
|
||||
ret = None
|
||||
if self.vis:
|
||||
ret = func(self, *args, **kwargs)
|
||||
return ret
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def check_main_thread(func: Callable) -> Callable:
|
||||
"""Decorator: check if you are on main thread"""
|
||||
|
||||
|
||||
+35
-15
@@ -19,10 +19,15 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import pickle
|
||||
from typing import Any, Tuple, Optional
|
||||
|
||||
|
||||
def load_from_json(filename: str):
|
||||
"""Load a dictionary from a JSON filename."""
|
||||
"""Load a dictionary from a JSON filename.
|
||||
|
||||
Args:
|
||||
filename: The filename to load from.
|
||||
"""
|
||||
assert filename.endswith(".json")
|
||||
with open(filename, "r", encoding="UTF-8") as file:
|
||||
return json.load(file)
|
||||
@@ -32,8 +37,8 @@ def write_to_json(filename: str, content: dict):
|
||||
"""Write data to a JSON file.
|
||||
|
||||
Args:
|
||||
filename (str): The filename to write to.
|
||||
content (dict): The dictionary data to write.
|
||||
filename: The filename to write to.
|
||||
content: The dictionary data to write.
|
||||
"""
|
||||
assert filename.endswith(".json")
|
||||
with open(filename, "w", encoding="UTF-8") as file:
|
||||
@@ -41,30 +46,39 @@ def write_to_json(filename: str, content: dict):
|
||||
|
||||
|
||||
def load_from_pkl(filename: str):
|
||||
"""Load from a pickle file."""
|
||||
"""Load from a pickle file.
|
||||
|
||||
Args:
|
||||
filename: The filename to load from.
|
||||
"""
|
||||
assert filename.endswith(".pkl")
|
||||
with open(filename, "rb") as f:
|
||||
return pickle.load(f)
|
||||
|
||||
|
||||
def write_to_pkl(filename: str, content):
|
||||
"Write to a pickle file."
|
||||
def write_to_pkl(filename: str, content: Any):
|
||||
"""Write to a pickle file.
|
||||
|
||||
Args:
|
||||
filename (str): The filename to write to.
|
||||
content (Any): The data to write.
|
||||
"""
|
||||
assert filename.endswith(".pkl")
|
||||
with open(filename, "wb") as f:
|
||||
pickle.dump(content, f)
|
||||
|
||||
|
||||
def get_git_root(path, dirs=(".git",), default=None):
|
||||
"""_summary_
|
||||
"https://stackoverflow.com/questions/22081209/find-the-root-of-the-git-repository-where-the-file-lives
|
||||
def get_git_root(path: str, dirs: Tuple[str] = (".git",), default=None) -> Optional[str]:
|
||||
"""Find the root of the git repository.
|
||||
'https://stackoverflow.com/questions/22081209/find-the-root-of-the-git-repository-where-the-file-lives'
|
||||
|
||||
Args:
|
||||
path (_type_): _description_
|
||||
dirs (tuple, optional): _description_. Defaults to (".git",).
|
||||
default (_type_, optional): _description_. Defaults to None.
|
||||
path: The path to start from.
|
||||
dirs: The directories to look for. Defaults to (".git",).
|
||||
default: The default value to return if no git root is found.
|
||||
|
||||
Returns:
|
||||
_type_: _description_
|
||||
The root of the git repository. Returns None if not found.
|
||||
"""
|
||||
prev, test = None, os.path.abspath(path)
|
||||
while prev != test:
|
||||
@@ -74,9 +88,12 @@ def get_git_root(path, dirs=(".git",), default=None):
|
||||
return default
|
||||
|
||||
|
||||
def get_project_root(path):
|
||||
def get_project_root(path: str):
|
||||
"""Return the project root directory from an environment variable.
|
||||
# TODO: handle this better and report user error
|
||||
|
||||
Args:
|
||||
path: The path to start from.
|
||||
"""
|
||||
project_root = os.getenv("PROJECT_ROOT")
|
||||
if project_root is None:
|
||||
@@ -103,9 +120,12 @@ def get_absolute_path(path, proj_root_func=get_project_root):
|
||||
return absolute_path
|
||||
|
||||
|
||||
def make_dir(filename_or_folder):
|
||||
def make_dir(filename_or_folder: str) -> str:
|
||||
"""Make the directory for either the filename or folder.
|
||||
Note that filename_or_folder currently needs to end in / for it to be recognized as a folder.
|
||||
|
||||
Args:
|
||||
filename_or_folder (str): The filename or folder to make.
|
||||
"""
|
||||
if filename_or_folder[-1] != "/" and filename_or_folder.find(".") < 0:
|
||||
folder = os.path.dirname(filename_or_folder + "/")
|
||||
|
||||
@@ -21,6 +21,7 @@ import json
|
||||
from pydoc import locate
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from math import floor, log
|
||||
import torch
|
||||
from omegaconf import DictConfig
|
||||
|
||||
@@ -117,3 +118,11 @@ class IterableWrapper: # pylint: disable=too-few-public-methods
|
||||
|
||||
def __next__(self):
|
||||
return self.new_next(self.instance)
|
||||
|
||||
|
||||
def human_format(num):
|
||||
"""Format a number in a more human readable way"""
|
||||
units = ["", "K", "M", "B", "T", "P"]
|
||||
k = 1000.0
|
||||
magnitude = int(floor(log(num, k)))
|
||||
return f"{(num / k**magnitude):.2f} {units[magnitude]}"
|
||||
+67
-59
@@ -42,30 +42,30 @@ def color_str(color):
|
||||
|
||||
|
||||
def get_line_segments_from_lines(
|
||||
lines,
|
||||
color=color_str((1, 0, 0)),
|
||||
marker_color=color_str((1, 0, 0)),
|
||||
colors=None,
|
||||
draw_marker=True,
|
||||
draw_line=True,
|
||||
marker_size=4,
|
||||
line_width=10,
|
||||
):
|
||||
lines: TensorType["num_rays", 2, 3],
|
||||
color: str = color_str((1, 0, 0)),
|
||||
marker_color: str = color_str((1, 0, 0)),
|
||||
colors: List[str] = None,
|
||||
draw_marker: bool = True,
|
||||
draw_line: bool = True,
|
||||
marker_size: float = 4,
|
||||
line_width: float = 10,
|
||||
) -> go.Scatter3d:
|
||||
"""Returns a list of Scatter3D objects for creating lines with plotly.
|
||||
# TODO(ethan): make this function more efficient instead of having a list of objects.
|
||||
|
||||
Args:
|
||||
lines (_type_): list of [np.array(2, 3), ...], line is defined by a (2, 3) array
|
||||
color (_type_, optional): _description_. Defaults to color_str((1, 0, 0)).
|
||||
marker_color (_type_, optional): _description_. Defaults to color_str((1, 0, 0)).
|
||||
colors (_type_, optional): _description_. Defaults to None.
|
||||
draw_marker (bool, optional): _description_. Defaults to True.
|
||||
draw_line (bool, optional): _description_. Defaults to True.
|
||||
marker_size (int, optional): _description_. Defaults to 4.
|
||||
line_width (int, optional): _description_. Defaults to 10.
|
||||
lines: Tensor of lines.
|
||||
color: Color of the lines. Defaults to red.
|
||||
marker_color: Color of the markers. Defaults to red.
|
||||
colors: List of colors for each line. Defaults to None.
|
||||
draw_marker: Whether to draw markers. Defaults to True.
|
||||
draw_line: Whether to draw lines. Defaults to True.
|
||||
marker_size: Size of the markers. Defaults to 4.
|
||||
line_width: Width of the lines. Defaults to 10.
|
||||
|
||||
Returns:
|
||||
_type_: _description_
|
||||
Scatter3D object on lines.
|
||||
"""
|
||||
data = []
|
||||
for idx, line in enumerate(lines):
|
||||
@@ -92,8 +92,16 @@ def get_line_segments_from_lines(
|
||||
return data
|
||||
|
||||
|
||||
def visualize_dataset(camera_origins, ray_bundle: RayBundle):
|
||||
"""Visualize a dataset with plotly using our cameras and generated rays."""
|
||||
def visualize_dataset(camera_origins: TensorType["num_cameras", 3], ray_bundle: RayBundle) -> go.FigureWidget:
|
||||
"""Visualize a dataset with plotly using our cameras and generated rays.
|
||||
|
||||
Args:
|
||||
camera_origins: Tensor of camera origins.
|
||||
ray_bundle: Ray bundle.
|
||||
|
||||
Returns:
|
||||
plotly figure.
|
||||
"""
|
||||
|
||||
skip = 1
|
||||
size = 8
|
||||
@@ -136,11 +144,11 @@ def get_random_color(colormap: List[str] = None, idx: int = None) -> str:
|
||||
"""Get a random color from a colormap.
|
||||
|
||||
Args:
|
||||
colormap (List[str], optional): List of colors. Defaults to Plotly colors.
|
||||
idx (int, optional): Index of color to return. Defaults to None.
|
||||
colormap: List of colors. Defaults to Plotly colors.
|
||||
idx: Index of color to return. Defaults to None.
|
||||
|
||||
Returns:
|
||||
str: random color string
|
||||
random color string
|
||||
"""
|
||||
if colormap is None:
|
||||
colormap = ex.colors.qualitative.Plotly
|
||||
@@ -155,14 +163,14 @@ def get_sphere(
|
||||
"""Returns a sphere object for plotting with plotly.
|
||||
|
||||
Args:
|
||||
radius (float): radius of sphere.
|
||||
center (TensorType[3], optional): center of sphere. Defaults to origin.
|
||||
color (str, optional): color of sphere. Defaults to "black".
|
||||
opacity (float, optional): opacity of sphere. Defaults to 1.0.
|
||||
resolution (int, optional): resolution of sphere. Defaults to 32.
|
||||
radius: radius of sphere.
|
||||
center: center of sphere. Defaults to origin.
|
||||
color: color of sphere. Defaults to "black".
|
||||
opacity: opacity of sphere. Defaults to 1.0.
|
||||
resolution: resolution of sphere. Defaults to 32.
|
||||
|
||||
Returns:
|
||||
go.Mesh3d: sphere object.
|
||||
sphere object.
|
||||
"""
|
||||
phi = torch.linspace(0, 2 * torch.pi, resolution)
|
||||
theta = torch.linspace(-torch.pi / 2, torch.pi / 2, resolution)
|
||||
@@ -201,16 +209,16 @@ def get_gaussian_ellipsiod(
|
||||
"""Get a plotly ellipsoid for a Gaussian.
|
||||
|
||||
Args:
|
||||
mean (TensorType[3]): mean of the Gaussian.
|
||||
cov: (TesnorType[3]): covariance of the Gaussian.
|
||||
n_std (int, optional): Standard devation to visualize. Defaults to 2 (95% confidence).
|
||||
color (str, optional): Color of the ellipsoid. Defaults to None.
|
||||
opacity (float, optional): Opacity of the ellipsoid. Defaults to 0.5.
|
||||
resolution (int, optional): Resolution of the ellipsoid. Defaults to 20.
|
||||
name (str, optional): Name of the ellipsoid. Defaults to "ellipse".
|
||||
mean: mean of the Gaussian.
|
||||
cov: covariance of the Gaussian.
|
||||
n_std: Standard devation to visualize. Defaults to 2 (95% confidence).
|
||||
color: Color of the ellipsoid. Defaults to None.
|
||||
opacity: Opacity of the ellipsoid. Defaults to 0.5.
|
||||
resolution: Resolution of the ellipsoid. Defaults to 20.
|
||||
name: Name of the ellipsoid. Defaults to "ellipse".
|
||||
|
||||
Returns:
|
||||
go.Mesh3d: ellipsoid object.
|
||||
ellipsoid object.
|
||||
"""
|
||||
|
||||
phi = torch.linspace(0, 2 * torch.pi, resolution)
|
||||
@@ -257,10 +265,10 @@ def get_gaussian_ellipsoids_list(
|
||||
gaussians (Gaussians): Gaussians to visualize.
|
||||
opacity (float, optional): Opacity of the mesh. Defaults to 0.3.
|
||||
color (str, optional): Color of the mesh. Defaults to "random".
|
||||
resolution (int, optional): Resolution of the mesh. Defaults to 20.
|
||||
resolution: Resolution of the mesh. Defaults to 20.
|
||||
|
||||
Returns:
|
||||
List[go.Mesh3d]: List of plotly meshes
|
||||
List of plotly meshes
|
||||
"""
|
||||
data = []
|
||||
|
||||
@@ -297,13 +305,13 @@ def get_frustum_mesh(
|
||||
"""Get a plotly mesh for a single frustum.
|
||||
|
||||
Args:
|
||||
frustum (Frustum): Single frustum
|
||||
opacity (float, optional): Opacity of the mesh. Defaults to 0.3.
|
||||
color (str, optional): Color of the mesh. Defaults to "#DC203C".
|
||||
resolution (int, optional): Resolution of the mesh. Defaults to 20.
|
||||
frustum: Single frustum
|
||||
opacity: Opacity of the mesh. Defaults to 0.3.
|
||||
color: Color of the mesh. Defaults to "#DC203C".
|
||||
resolution: Resolution of the mesh. Defaults to 20.
|
||||
|
||||
Returns:
|
||||
go.Mesh3d: Plotly mesh
|
||||
Plotly mesh
|
||||
"""
|
||||
|
||||
if frustum.ndim > 1:
|
||||
@@ -348,13 +356,13 @@ def get_frustums_mesh_list(
|
||||
"""Get a list of plotly meshes for a list of frustums.
|
||||
|
||||
Args:
|
||||
frustums (Frustum): List of frustums
|
||||
opacity (float, optional): Opacity of the mesh. Defaults to 0.3.
|
||||
color (str, optional): Color of the mesh. Defaults to "random".
|
||||
resolution (int, optional): Resolution of the mesh. Defaults to 20.
|
||||
frustums: List of frustums
|
||||
opacity: Opacity of the mesh. Defaults to 0.3.
|
||||
color: Color of the mesh. Defaults to "random".
|
||||
resolution: Resolution of the mesh. Defaults to 20.
|
||||
|
||||
Returns:
|
||||
List[go.Mesh3d]: List of plotly meshes
|
||||
List of plotly meshes
|
||||
"""
|
||||
data = []
|
||||
for i, frustum in enumerate(frustums.flatten()):
|
||||
@@ -372,13 +380,13 @@ def get_frustum_points(
|
||||
"""Get a set plotly points for frustums centers.
|
||||
|
||||
Args:
|
||||
frustum (Frustum): Frustums to visualize.
|
||||
opacity (float, optional): Opacity of the points. Defaults to 0.3.
|
||||
color (str, optional): Color of the poinst. Defaults to "forestgreen".
|
||||
size (float, optional): Size of points. Defaults to 10.
|
||||
frustum: Frustums to visualize.
|
||||
opacity: Opacity of the points. Defaults to 0.3.
|
||||
color: Color of the poinst. Defaults to "forestgreen".
|
||||
size: Size of points. Defaults to 10.
|
||||
|
||||
Returns:
|
||||
go.Scatter3d: Plotly points
|
||||
Plotly points
|
||||
"""
|
||||
|
||||
frustum = frustum.flatten()
|
||||
@@ -404,13 +412,13 @@ def get_ray_bundle_lines(
|
||||
"""Get a plotly line for a ray bundle.
|
||||
|
||||
Args:
|
||||
ray_bundle (RayBundle): Ray bundle
|
||||
length (float, optional): Length of the line. Defaults to 1.0.
|
||||
color (str, optional): Color of the line.
|
||||
width (float, optional): Width of the line. Defaults to 1.
|
||||
ray_bundle: Ray bundle
|
||||
length: Length of the line. Defaults to 1.0.
|
||||
color: Color of the line.
|
||||
width: Width of the line. Defaults to 1.
|
||||
|
||||
Returns:
|
||||
go.Scatter3d: Plotly lines
|
||||
Plotly lines
|
||||
"""
|
||||
|
||||
origins = ray_bundle.origins.view(-1, 3)
|
||||
|
||||
@@ -15,11 +15,13 @@
|
||||
"""Tensor dataclass"""
|
||||
|
||||
import dataclasses
|
||||
from typing import Tuple, Union
|
||||
from typing import Callable, NoReturn, Optional, Tuple, TypeVar, Union
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
TensorDataclassT = TypeVar("TensorDataclassT", bound="TensorDataclass")
|
||||
|
||||
|
||||
class TensorDataclass:
|
||||
"""Data class of tensors with the same size batch. Allows indexing and standard tensor ops.
|
||||
@@ -78,7 +80,7 @@ class TensorDataclass:
|
||||
|
||||
self.__setattr__("_shape", batch_shape)
|
||||
|
||||
def __getitem__(self, indices) -> "TensorDataclass":
|
||||
def __getitem__(self: TensorDataclassT, indices) -> TensorDataclassT:
|
||||
if isinstance(indices, torch.Tensor):
|
||||
return self._apply_fn_to_fields(lambda x: x[indices])
|
||||
if isinstance(indices, (int, slice)):
|
||||
@@ -87,7 +89,7 @@ class TensorDataclass:
|
||||
dataclass_fn = lambda x: x[indices]
|
||||
return self._apply_fn_to_fields(tensor_fn, dataclass_fn)
|
||||
|
||||
def __setitem__(self, indices, value) -> "TensorDataclass":
|
||||
def __setitem__(self, indices, value) -> NoReturn:
|
||||
raise RuntimeError("Index assignment is not supported for TensorDataclass")
|
||||
|
||||
def __len__(self) -> int:
|
||||
@@ -102,7 +104,7 @@ class TensorDataclass:
|
||||
return True
|
||||
|
||||
@property
|
||||
def shape(self) -> tuple:
|
||||
def shape(self) -> Tuple[int, ...]:
|
||||
"""Returns the batch shape of the tensor dataclass."""
|
||||
return self._shape
|
||||
|
||||
@@ -118,11 +120,11 @@ class TensorDataclass:
|
||||
"""Returns the number of dimensions of the tensor dataclass."""
|
||||
return len(self._shape)
|
||||
|
||||
def reshape(self, shape: Tuple[int, ...]) -> "TensorDataclass":
|
||||
def reshape(self: TensorDataclassT, shape: Tuple[int, ...]) -> TensorDataclassT:
|
||||
"""Returns a new TensorDataclass with the same data but with a new shape.
|
||||
|
||||
Args:
|
||||
shape (Tuple[int]): The new shape of the tensor dataclass.
|
||||
shape (Tuple[int, ...]): The new shape of the tensor dataclass.
|
||||
|
||||
Returns:
|
||||
TensorDataclass: A new TensorDataclass with the same data but with a new shape.
|
||||
@@ -133,7 +135,7 @@ class TensorDataclass:
|
||||
dataclass_fn = lambda x: x.reshape(shape)
|
||||
return self._apply_fn_to_fields(tensor_fn, dataclass_fn)
|
||||
|
||||
def flatten(self) -> "TensorDataclass":
|
||||
def flatten(self: TensorDataclassT) -> TensorDataclassT:
|
||||
"""Returns a new TensorDataclass with flattened batch dimensions
|
||||
|
||||
Returns:
|
||||
@@ -141,18 +143,18 @@ class TensorDataclass:
|
||||
"""
|
||||
return self.reshape((-1,))
|
||||
|
||||
def broadcast_to(self, shape: Union[torch.Size, Tuple[int]]) -> "TensorDataclass":
|
||||
def broadcast_to(self: TensorDataclassT, shape: Union[torch.Size, Tuple[int, ...]]) -> TensorDataclassT:
|
||||
"""Returns a new TensorDataclass broadcast to new shape.
|
||||
|
||||
Args:
|
||||
shape (Tuple[int]): The new shape of the tensor dataclass.
|
||||
shape (Tuple[int, ...]): The new shape of the tensor dataclass.
|
||||
|
||||
Returns:
|
||||
TensorDataclass: A new TensorDataclass with the same data but with a new shape.
|
||||
"""
|
||||
return self._apply_fn_to_fields(lambda x: x.broadcast_to((*shape, x.shape[-1])))
|
||||
|
||||
def to(self, device) -> "TensorDataclass":
|
||||
def to(self: TensorDataclassT, device) -> TensorDataclassT:
|
||||
"""Returns a new TensorDataclass with the same data but on the specified device.
|
||||
|
||||
Args:
|
||||
@@ -163,12 +165,14 @@ class TensorDataclass:
|
||||
"""
|
||||
return self._apply_fn_to_fields(lambda x: x.to(device))
|
||||
|
||||
def _apply_fn_to_fields(self, fn: callable, dataclass_fn: callable = None) -> "TensorDataclass":
|
||||
def _apply_fn_to_fields(
|
||||
self: TensorDataclassT, fn: Callable, dataclass_fn: Optional[Callable] = None
|
||||
) -> TensorDataclassT:
|
||||
"""Applies a function to all fields of the tensor dataclass.
|
||||
|
||||
Args:
|
||||
fn (callable): The function to apply to tensor fields.
|
||||
dataclass_fn (callable): The function to apply to TensorDataclass fields. Else use fn.
|
||||
fn (Callable): The function to apply to tensor fields.
|
||||
dataclass_fn (Optional[Callable]): The function to apply to TensorDataclass fields. Else use fn.
|
||||
|
||||
Returns:
|
||||
TensorDataclass: A new TensorDataclass with the same data but with a new shape.
|
||||
|
||||
@@ -27,12 +27,12 @@ from typing import Dict
|
||||
import imageio
|
||||
import numpy as np
|
||||
import torch
|
||||
import wandb
|
||||
from omegaconf import ListConfig
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from torchtyping import TensorType
|
||||
from pyrad.utils.config import LoggingConfig
|
||||
|
||||
import wandb
|
||||
from pyrad.utils.config import LoggingConfig
|
||||
from pyrad.utils.decorators import check_main_thread, decorate_all
|
||||
|
||||
to8b = lambda x: (255 * torch.clamp(x, min=0, max=1)).to(torch.uint8)
|
||||
|
||||
Reference in new issue
Block a user