Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

NeRF Implementation (#1911)

Yaniv Hollandercc6b9868945c
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 7a9863a7a..b8d2394ab 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -1,3 +1,3 @@
-from ._backend import Module, Parameter, Tensor, as_tensor, concatenate, normalize, rand, stack
+from ._backend import Device, Module, Parameter, Tensor, as_tensor, concatenate, normalize, rand, stack
-__all__ = ["concatenate", "Module", "Tensor", "Parameter", "normalize", "stack", "as_tensor", "rand"]
+__all__ = ["concatenate", "Device", "Module", "Tensor", "Parameter", "normalize", "stack", "as_tensor", "rand"]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index d5226ad49..146ddee17 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -1,5 +1,8 @@
+from typing import Union
+
import torch
import torch.nn.functional as F
+from torch import device
# classes
Tensor = torch.Tensor
@@ -16,3 +19,6 @@ as_tensor = torch.as_tensor
# random
rand = torch.rand
+
+# device
+Device = Union[str, device]
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
new file mode 100755
index 000000000..dd6a7c669
--- /dev/null
+++ b/kornia/nerf/camera_utils.py
@@ -0,0 +1,156 @@
+import math
+from typing import List, Tuple
+
+import torch
+
+from kornia.core import Device, Tensor
+from kornia.geometry.camera import PinholeCamera
+from kornia.geometry.conversions import QuaternionCoeffOrder, quaternion_to_rotation_matrix
+
+
+def parse_colmap_output(
+ cameras_path: str, images_path: str, device: Device, dtype: torch.dtype
+) -> Tuple[List[str], PinholeCamera]:
+ r"""Parses colmap output to create an PinholeCamera for aligned scene cameras.
+
+ Args:
+ cameras_path: Path to camera.txt Colmap file with camera intrinsics: str
+ images_path: Path to images.txt Colmap file with camera extrinsics for each image: str
+ device: device for created camera object: Union[str, torch.device]
+
+ Returns:
+ image names: List[str]
+ scene camera object: PinholeCamera
+ """
+
+ # Parse camera intrinsics
+ with open(cameras_path) as f:
+ lines = f.readlines()
+
+ class CameraParams:
+ def __init__(self, line: str) -> None:
+ split_line = line.split(' ')
+ model = split_line[1]
+ if model == 'SIMPLE_PINHOLE':
+ self._width = int(split_line[2])
+ self._height = int(split_line[3])
+ self._fx = float(split_line[4])
+ self._fy = self._fx
+ self._cx = int(split_line[5])
+ self._cy = int(split_line[6])
+ elif model == 'PINHOLE':
+ self._width = int(split_line[2])
+ self._height = int(split_line[3])
+ self._fx = float(split_line[4])
+ self._fy = float(split_line[5])
+ self._cx = int(split_line[6])
+ self._cy = int(split_line[7])
+
+ cameras_params: List[CameraParams] = []
+ for line in lines:
+ if line.startswith('#'):
+ continue
+ camera_params = CameraParams(line)
+ cameras_params.append(camera_params)
+
+ # Parse camera quaternions and translation vectors
+ with open(images_path) as f:
+ lines = f.readlines()
+ intrinsics: List[Tensor] = []
+ extrinsics: List[Tensor] = []
+ heights: List[int] = []
+ widths: List[int] = []
+ img_names: List[str] = []
+ for line in lines:
+ if line.startswith('#'):
+ continue
+
+ # Read line with camera quaternion
+ line = line.strip()
+ if line.endswith('png') or line.endswith('jpg\n'):
+ split_line = line.split(' ')
+ qw = float(split_line[1])
+ qx = float(split_line[2])
+ qy = float(split_line[3])
+ qz = float(split_line[4])
+ tx = float(split_line[5])
+ ty = float(split_line[6])
+ tz = float(split_line[7])
+ camera_ind = int(split_line[8]) - 1
+ img_name = split_line[9]
+ img_names.append(img_name)
+
+ # Intrinsic
+ camera_params = cameras_params[camera_ind]
+ intrinsic = torch.eye(4, device=device, dtype=dtype)
+ intrinsic[0, 0] = camera_params._fx
+ intrinsic[1, 1] = camera_params._fy
+ intrinsic[0, 2] = camera_params._cx
+ intrinsic[1, 2] = camera_params._cy
+ intrinsics.append(intrinsic)
+
+ heights.append(camera_params._height)
+ widths.append(camera_params._width)
+
+ # Extrinsic
+ q = torch.tensor([qw, qx, qy, qz], device=device)
+ R = quaternion_to_rotation_matrix(q, order=QuaternionCoeffOrder.WXYZ)
+ t = torch.tensor([tx, ty, tz], device=device)
+ extrinsic = torch.eye(4, device=device, dtype=dtype)
+ extrinsic[:3, :3] = R
+ extrinsic[:3, 3] = t
+ extrinsics.append(extrinsic)
+
+ cameras = PinholeCamera(
+ torch.stack(intrinsics),
+ torch.stack(extrinsics),
+ torch.tensor(heights, device=device),
+ torch.tensor(widths, device=device),
+ )
+ return img_names, cameras
+
+
+def cameras_for_ids(cameras: PinholeCamera, camera_ids: List[int]) -> PinholeCamera:
+ r"""Takes a PinholeCamera camera object and a set of camera indices and creates a new PinholeCamera object for
+ the requested cameras.
+
+ Args:
+ cameras: Scene camera object: PinholeCamera
+ camera_ids: List of camera indices to copy: List[int]
+
+ Return:
+ A new PinholeCamera object with a sub-set of cameras: PinholeCamera
+ """
+ intrinsics = cameras.intrinsics[camera_ids]
+ extrinsics = cameras.extrinsics[camera_ids]
+ height = cameras.height[camera_ids]
+ width = cameras.width[camera_ids]
+ return PinholeCamera(intrinsics, extrinsics, height, width)
+
+
+def create_spiral_path(cameras: PinholeCamera, rad: float, num_views: int, num_circles: int) -> PinholeCamera:
+ r"""Creates a PinholeCamera object with cameras that follow a spiral path. Used for novel view synthesis for
+ face facing models.
+
+ Args:
+ cameras: Scene cameras used to train the NeRF model: PinholeCamera
+ rad: Spiral radius: float
+ num_views: Number of created cameras: int
+ num_circles: Number of spiral circles: int
+ """
+
+ # Average locations over all cameras
+ mean_center = cameras.translation_vector.mean(0, False).squeeze(-1)
+ device = cameras.intrinsics.device
+ t = torch.linspace(0, 2 * math.pi * num_circles, num_views, device=device)
+ cos_t = torch.cos(t) * rad
+ sin_t = -torch.sin(t) * rad
+ sin_05t = -torch.sin(0.5 * t) * rad
+ translation_vector = torch.unsqueeze(mean_center, dim=0) + torch.stack((cos_t, sin_t, sin_05t)).permute((1, 0))
+ mean_intrinsics = cameras.intrinsics.mean(0, True).repeat(num_views, 1, 1)
+ mean_extrinsics = cameras.extrinsics.mean(0, True).repeat(num_views, 1, 1)
+ extrinsics = mean_extrinsics
+ extrinsics[:, :3, 3] = translation_vector
+ height = torch.tensor([cameras.height[0]] * num_views, device=device)
+ width = torch.tensor([cameras.width[0]] * num_views, device=device)
+ return PinholeCamera(mean_intrinsics, extrinsics, height, width)
diff --git a/kornia/nerf/core.py b/kornia/nerf/core.py
new file mode 100755
index 000000000..c56b45c97
--- /dev/null
+++ b/kornia/nerf/core.py
@@ -0,0 +1,7 @@
+from typing import List, Union
+
+from kornia.core import Tensor
+
+ImagePaths = List[str]
+ImageTensors = List[Tensor]
+Images = Union[ImagePaths, ImageTensors]
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
new file mode 100755
index 000000000..b2fe7ddb6
--- /dev/null
+++ b/kornia/nerf/data_utils.py
@@ -0,0 +1,157 @@
+from typing import List, Optional, Tuple, Union
+
+import torch
+from torch.utils.data import BatchSampler, DataLoader, Dataset, RandomSampler, SequentialSampler
+
+from kornia.core import Device, Tensor
+from kornia.geometry.camera import PinholeCamera
+from kornia.io import ImageLoadType, load_image
+from kornia.nerf.core import Images, ImageTensors
+from kornia.nerf.rays import RandomRaySampler, RaySampler, UniformRaySampler
+
+RayGroup = Tuple[Tensor, Tensor, Optional[Tensor]]
+
+
+class RayDataset(Dataset):
+ r"""Class to represent a dataset of rays.
+
+ Args:
+ cameras: scene cameras: PinholeCamera
+ min_depth: sampled rays minimal depth from cameras: float
+ max_depth: sampled rays maximal depth from cameras: float
+ ndc: convert ray parameters to normalized device coordinates: bool
+ device: device for ray tensors: Union[str, torch.device]
+ dtype: type of ray tensors: torch.dtype
+ """
+
+ def __init__(
+ self, cameras: PinholeCamera, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype
+ ) -> None:
+ super().__init__()
+ self._ray_sampler: Optional[RaySampler] = None
+ self._imgs: Optional[List[Tensor]] = None
+ self._cameras = cameras
+ self._min_depth = min_depth
+ self._max_depth = max_depth
+ self._ndc = ndc
+ self._device = device
+ self._dtype = dtype
+
+ def init_ray_dataset(self, num_img_rays: Optional[Tensor] = None) -> None:
+ r"""Initializes a ray dataset.
+
+ Args:
+ num_img_rays: If not None, number of rays to randomly cast from each camera: math: `(B)`.
+ """
+ if num_img_rays is None:
+ self._init_uniform_ray_dataset()
+ else:
+ self._init_random_ray_dataset(num_img_rays)
+
+ def init_images_for_training(self, imgs: Images) -> None:
+ r"""Initializes images for training. Images can be either a list of tensors, or a list of paths to image
+ disk locations.
+
+ Args:
+ imgs: List of image tensors or image paths: Images
+ """
+ self._check_image_type_consistency(imgs)
+ if isinstance(imgs[0], str): # Load images from disk
+ self._imgs = self._load_images(imgs)
+ else:
+ self._imgs = imgs # Take images provided on input
+ self._check_dimensions(self._imgs)
+
+ # Move images to defined device
+ self._imgs = [img.to(self._device) for img in self._imgs]
+
+ def _init_random_ray_dataset(self, num_img_rays: Tensor) -> None:
+ r"""Initializes a random ray sampler and calculates dataset ray parameters.
+
+ Args:
+ num_img_rays: If not None, number of rays to randomly cast from each camers: math: `(B)`.
+ """
+ self._ray_sampler = RandomRaySampler(
+ self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
+ )
+ self._ray_sampler.calc_ray_params(self._cameras, num_img_rays)
+
+ def _init_uniform_ray_dataset(self) -> None:
+ r"""Initializes a uniform ray sampler and calculates dataset ray parameters."""
+ self._ray_sampler = UniformRaySampler(
+ self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
+ )
+ self._ray_sampler.calc_ray_params(self._cameras)
+
+ def _check_image_type_consistency(self, imgs: Images) -> None:
+ if not all(isinstance(img, str) for img in imgs) and not all(isinstance(img, Tensor) for img in imgs):
+ raise ValueError('The list of input images can only be all paths or tensors')
+
+ def _check_dimensions(self, imgs: ImageTensors) -> None:
+ if len(imgs) != self._cameras.batch_size:
+ raise ValueError(
+ f'Number of images {len(imgs)} does not match number of cameras {self._cameras.batch_size}'
+ )
+ if not all(img.shape[0] == 3 for img in imgs):
+ raise ValueError('Not all input images have 3 channels')
+ for i, (img, height, width) in enumerate(zip(imgs, self._cameras.height, self._cameras.width)):
+ if img.shape[1:] != (height, width):
+ raise ValueError(
+ f'Image index {i} dimensions {(img.shape[1], img.shape[2])} are inconsistent with equivalent '
+ f'camera dimensions {(height.item(), width.item())}'
+ )
+
+ @staticmethod
+ def _load_images(img_paths: List[str]) -> List[Tensor]:
+ imgs: List[Tensor] = []
+ for img_path in img_paths:
+ imgs.append(load_image(img_path, ImageLoadType.UNCHANGED))
+ return imgs
+
+ def __len__(self):
+ return len(self._ray_sampler)
+
+ def __getitem__(self, idxs: Union[int, List[int]]) -> RayGroup:
+ r"""Gets a dataset item.
+
+ Args:
+ idxs: An index or group of indices of ray parameter object: Union[int, List[int]]
+
+ Return:
+ A ray parameter object that includes ray origins, directions, and rgb values at the ray 2d pixel
+ coordinates: RayGroup
+ """
+ origins = self._ray_sampler.origins[idxs]
+ directions = self._ray_sampler.directions[idxs]
+ if self._imgs is None:
+ return origins, directions, None
+ camerd_ids = self._ray_sampler.camera_ids[idxs]
+ points_2d = self._ray_sampler.points_2d[idxs]
+ rgbs = None
+ imgs_for_ids = [self._imgs[i] for i in camerd_ids]
+ rgbs = torch.stack(
+ [img[:, point2d[1].item(), point2d[0].item()] for img, point2d in zip(imgs_for_ids, points_2d)]
+ )
+ rgbs = rgbs.to(dtype=self._dtype) / 255.0
+ return origins, directions, rgbs
+
+
+def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> None:
+ r"""Initializes a dataloader to manage a ray dataset.
+
+ Args:
+ dataset: A ray dataset: RayDataset
+ batch_size: Number of rays to sample in a batch: int
+ shuffle: Whether to shuffle rays or sample then sequentially: bool
+ """
+
+ def collate_rays(items: List[RayGroup]) -> RayGroup:
+ return items[0]
+
+ return DataLoader(
+ dataset,
+ sampler=BatchSampler(
+ RandomSampler(dataset) if shuffle else SequentialSampler(dataset), batch_size, drop_last=False
+ ),
+ collate_fn=collate_rays,
+ )
diff --git a/kornia/nerf/nerf_model.py b/kornia/nerf/nerf_model.py
new file mode 100755
index 000000000..16c5fab40
--- /dev/null
+++ b/kornia/nerf/nerf_model.py
@@ -0,0 +1,125 @@
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from kornia.core import Tensor
+from kornia.nerf.positional_encoder import PositionalEncoder
+from kornia.nerf.rays import sample_lengths, sample_ray_points
+from kornia.nerf.renderer import IrregularRenderer, RegularRenderer
+
+
+class MLP(nn.Module):
+ r"""Class to represent a multi-layer perceptron. The MLP represents a deep NN of fully connected layers. The
+ network is build of user defined sub-units, each with a user defined number of layers. Skip connections span
+ between the sub-units. The model follows: Ben Mildenhall et el. (2020) at https://arxiv.org/abs/2003.08934.
+
+ Args:
+ num_dims: Number of input dimensions (channels)
+ num_units: Number of sub-units: int
+ num_unit_layers: Number of fully connected layers in each sub-unit
+ num_hidden: Layer hidden dimensions: int
+ """
+
+ def __init__(self, num_dims, num_units: int = 2, num_unit_layers: int = 4, num_hidden: int = 128):
+ super().__init__()
+ self._num_unit_layers = num_unit_layers
+ layers = []
+ for i in range(num_units):
+ num_unit_inp_dims = num_dims if i == 0 else num_hidden + num_dims
+ for j in range(num_unit_layers):
+ num_layer_inp_dims = num_unit_inp_dims if j == 0 else num_hidden
+ layer = nn.Linear(num_layer_inp_dims, num_hidden)
+ layers.append(nn.Sequential(layer, nn.ReLU()))
+ self._mlp = nn.ModuleList(layers)
+
+ def forward(self, inp: Tensor) -> Tensor:
+ out = inp
+ inp_skip = inp
+ for i, layer in enumerate(self._mlp):
+ if i > 0 and i % self._num_unit_layers == 0:
+ out = torch.cat((out, inp_skip), dim=-1)
+ out = layer(out)
+ return out
+
+
+class NerfModel(nn.Module):
+ r"""Class to represent NeRF model.
+
+ Args:
+ num_ray_points: Number of points to sample along rays: int
+ irregular_ray_sampling: Whether to sample ray points irregularly: bool
+ num_pos_freqs: Number of frequencies for positional encoding: int
+ num_dir_freqs: Number of frequencies for directional encoding: int
+ num_units: Number of sub-units: int
+ num_unit_layers: Number of fully connected layers in each sub-unit
+ num_hidden: Layer hidden dimensions: int
+ log_space_encoding: Whether to apply log spacing for encoding: bool
+ """
+
+ def __init__(
+ self,
+ num_ray_points: int,
+ irregular_ray_sampling: bool = True,
+ num_pos_freqs: int = 10,
+ num_dir_freqs: int = 4,
+ num_units: int = 2,
+ num_unit_layers: int = 4,
+ num_hidden: int = 128, # FIXME: add as call argument
+ log_space_encoding=True,
+ ):
+ super().__init__()
+ self._num_ray_points = num_ray_points
+ self._irregular_ray_sampling = irregular_ray_sampling
+ self._renderer = IrregularRenderer() if self._irregular_ray_sampling else RegularRenderer()
+
+ self._pos_encoder = PositionalEncoder(3, num_pos_freqs, log_space=log_space_encoding)
+ self._dir_encoder = PositionalEncoder(3, num_dir_freqs, log_space=log_space_encoding)
+ self._mlp = MLP(self._pos_encoder.num_encoded_dims, num_units, num_unit_layers, num_hidden)
+ self._fc1 = nn.Linear(num_hidden, num_hidden)
+ self._fc2 = nn.Sequential(
+ nn.Linear(num_hidden + self._dir_encoder.num_encoded_dims, num_hidden // 2), nn.ReLU()
+ )
+
+ self._sigma = nn.Linear(num_hidden, 1, bias=True)
+ torch.nn.init.xavier_uniform_(self._sigma.weight.data)
+ self._sigma.bias.data = torch.tensor([0.1]).float()
+
+ self._rgb = nn.Sequential(nn.Linear(num_hidden // 2, 3), nn.Sigmoid())
+ self._rgb[0].bias.data = torch.tensor([0.02, 0.02, 0.02]).float()
+
+ def forward(self, origins: Tensor, directions: Tensor) -> Tensor:
+
+ # Sample xyz for ray parameters
+ batch_size = origins.shape[0]
+ lengths = sample_lengths(
+ batch_size,
+ self._num_ray_points,
+ device=origins.device,
+ dtype=origins.dtype,
+ irregular=self._irregular_ray_sampling,
+ ) # FIXME: handle the case of hierarchical sampling
+ points_3d = sample_ray_points(origins, directions, lengths)
+
+ # Encode positions & directions
+ points_3d_encoded = self._pos_encoder(points_3d)
+ directions_encoded = self._dir_encoder(F.normalize(directions, dim=-1))
+
+ # Map positional encodings to latent features (MLP with skip connections)
+ y = self._mlp(points_3d_encoded)
+ y = self._fc1(y)
+
+ # Calculate ray point density values
+ densities_ray_points = self._sigma(y)
+ densities_ray_points = densities_ray_points + torch.randn_like(densities_ray_points) * 0.1
+ densities_ray_points = torch.relu(densities_ray_points) # FIXME: Revise this
+
+ # Calculate ray point rgb values
+ y = torch.cat((y, directions_encoded[..., None, :].expand(-1, self._num_ray_points, -1)), dim=-1)
+ y = self._fc2(y)
+ rgbs_ray_points = self._rgb(y)
+
+ # Rendring rgbs and densities along rays
+ rgbs = self._renderer(rgbs_ray_points, densities_ray_points, points_3d)
+
+ # Return pixel point rendered rgb
+ return rgbs
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
new file mode 100755
index 000000000..9421e2f6c
--- /dev/null
+++ b/kornia/nerf/nerf_solver.py
@@ -0,0 +1,201 @@
+from datetime import datetime
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+import torch.optim as optim
+from torch import nn
+
+from kornia.core import Device
+from kornia.geometry.camera import PinholeCamera
+from kornia.metrics import psnr
+from kornia.nerf.core import Images, ImageTensors
+from kornia.nerf.data_utils import RayDataset, instantiate_ray_dataloader
+from kornia.nerf.nerf_model import NerfModel
+from kornia.utils._compat import torch_inference_mode
+
+
+class NerfSolver:
+ r"""NeRF solver class.
+
+ Args:
+ device: device for class tensors: Union[str, torch.device]
+ dtype: type for all floating point calculations: torch.dtype
+ """
+
+ def __init__(self, device: Device, dtype: torch.dtype) -> None:
+ self._cameras: Optional[PinholeCamera] = None
+ self._min_depth: float = 0.0
+ self._max_depth: float = 0.0
+ self._ndc: bool = True
+
+ self._imgs: Optional[Images] = None
+ self._num_img_rays: Optional[int] = None
+
+ self._batch_size: int = 0
+
+ self._nerf_model: Optional[nn.Module] = None
+ self._num_ray_points: int = 0
+
+ self._nerf_optimizaer: Optional[optim.Optimizer] = None
+
+ self._opt_nerf: optim.Optimizer = None
+
+ self._device = device
+ self._dtype = dtype
+
+ def init_training(
+ self,
+ cameras: PinholeCamera,
+ min_depth: float,
+ max_depth: float,
+ ndc: bool,
+ imgs: Images,
+ num_img_rays: Optional[Union[torch.tensor, int]],
+ batch_size: int,
+ num_ray_points: int,
+ irregular_ray_sampling: bool = True,
+ log_space_encoding=True,
+ lr: float = 1.0e-3,
+ ) -> None:
+ r"""Initializes training.
+
+ Args:
+ cameras: Scene cameras in the order of input images: PinholeCamera
+ min_depth: sampled rays minimal depth from cameras: float
+ max_depth: sampled rays maximal depth from cameras: float
+ ndc: convert ray parameters to normalized device coordinates: bool
+ imgs: Scene 2D images (one for each camera): Images
+ num_img_rays: Number of rays to randomly cast from each camera: math: `(B)`
+ batch_size: Number of rays to sample in a batch: int
+ num_ray_points: Number of points to sample along rays: int
+ irregular_ray_sampling: Whether to sample ray points irregularly: bool
+ log_space: Whether frequency sampling should be log spaced: bool
+ lr: Learning rate: float
+ """
+ # self._check_camera_image_consistency(cameras, imgs) # FIXME: Check if required
+
+ self._cameras = cameras
+ self._min_depth = min_depth
+ self._max_depth = max_depth
+ self._ndc = ndc
+
+ self._imgs = imgs
+ self._num_img_rays = None
+ if isinstance(num_img_rays, int):
+ self._num_img_rays = torch.tensor([num_img_rays] * cameras.batch_size)
+ elif torch.is_tensor(num_img_rays):
+ self._num_img_rays = num_img_rays
+ elif num_img_rays is not None:
+ raise TypeError('num_img_rays can be either an int or a torch.tensor')
+
+ self._batch_size = batch_size
+
+ self._nerf_model = NerfModel(
+ num_ray_points, irregular_ray_sampling=irregular_ray_sampling, log_space_encoding=log_space_encoding
+ )
+ self._nerf_model.to(device=self._device, dtype=self._dtype)
+ self._opt_nerf = optim.Adam(self._nerf_model.parameters(), lr=lr)
+
+ @property
+ def nerf_model(self) -> nn.Module:
+ return self._nerf_model
+
+ # FIXME: Remove this function - consistency is checked in
+ @staticmethod
+ def _check_camera_image_consistency(cameras: PinholeCamera, imgs: Images):
+ if cameras is None:
+ raise ValueError('Invalid camera object')
+ if imgs is None:
+ raise ValueError('Invalid image list object')
+ if cameras.batch_size != len(imgs):
+ raise ValueError('Number of cameras must match number of input images')
+ if not all(img.shape[0] == 3 for img in imgs):
+ raise ValueError('All images must have three RGB channels')
+ if not all(height == img.shape[1] for height, img in zip(cameras.height.tolist(), imgs)):
+ raise ValueError('All image heights must match camera heights')
+ if not all(width == img.shape[2] for width, img in zip(cameras.width.tolist(), imgs)):
+ raise ValueError('All image widths must match camera widths')
+
+ def _train_one_epoch(self) -> float:
+ r"""Trains one epoch. A dataset of rays is initialized, and sent over to a data loader. The data loader
+ sample a batch of rays randomly, and runs them through the NeRF model, to predict ray associated rgb model
+ values. The model rgb is compared with the image pixel rgb, and the loss between the two is back propagated
+ to update the model weights.
+
+ Implemented steps:
+ - Create an object of class RayDataset
+ - Initialize ray dataset with group of images on disk, and number of rays to randomly sample
+ - Initialize a data loader with batch size info
+ - Iterate over data loader
+ -- Reset optimizer
+ -- Run ray batch through Nerf model
+ -- Find loss
+ -- Back propagate loss
+ -- Optimizer step
+
+ Returns:
+ Average psnr over all epoch rays
+ """
+ ray_dataset = RayDataset(
+ self._cameras, self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
+ )
+ ray_dataset.init_ray_dataset(self._num_img_rays)
+ ray_dataset.init_images_for_training(self._imgs) # FIXME: Do we need to load the same images on each Epoch?
+ ray_data_loader = instantiate_ray_dataloader(ray_dataset, self._batch_size, shuffle=True)
+ total_psnr = 0.0
+ for i_batch, (origins, directions, rgbs) in enumerate(ray_data_loader):
+ rgbs_model = self._nerf_model(origins, directions)
+ loss = F.mse_loss(rgbs_model, rgbs)
+
+ total_psnr += psnr(rgbs_model, rgbs, 1.0)
+
+ self._opt_nerf.zero_grad()
+ loss.backward()
+ self._opt_nerf.step()
+ return total_psnr / (i_batch + 1)
+
+ def run(self, num_epochs: int = 1) -> None:
+ r"""Runs training epochs.
+
+ Args:
+ num_epochs: Number of epochs to run: int
+ """
+ for i_epoch in range(num_epochs):
+ epoch_psnr = self._train_one_epoch()
+
+ if i_epoch % 10 == 0:
+ current_time = datetime.now().strftime("%H:%M:%S")
+ print(f'Epoch: {i_epoch}: epoch_psnr = {epoch_psnr}; time: {current_time}')
+
+ def render_views(self, cameras: PinholeCamera) -> ImageTensors:
+ r"""Renders a novel synthesis view of a trained NeRF model for given cameras.
+
+ Args:
+ cameras: cameras for image renderings: PinholeCamera
+
+ Returns:
+ Rendered images: ImageTensors (List[(H, W, C)]).
+ """
+ ray_dataset = RayDataset(
+ cameras, self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
+ )
+ ray_dataset.init_ray_dataset()
+ idx0 = 0
+ imgs: ImageTensors = []
+ batch_size = 4096 # FIXME: Consider exposing this value to the user
+ for height, width in zip(cameras.height.int().tolist(), cameras.width.int().tolist()):
+ bsz = batch_size if batch_size != -1 else height * width
+ img = torch.zeros((height * width, 3), dtype=torch.uint8)
+ idx0_camera = idx0
+ for idx0 in range(idx0, idx0 + height * width, bsz):
+ idxe = min(idx0 + bsz, idx0_camera + height * width)
+ idxs = list(range(idx0, idxe))
+ origins, directions, _ = ray_dataset[idxs]
+ with torch_inference_mode():
+ rgb_model = self._nerf_model(origins, directions) * 255.0
+ img[idx0 - idx0_camera : idxe - idx0_camera] = rgb_model
+ idx0 = idxe
+ img = img.reshape(height, width, -1) # (H, W, C)
+ imgs.append(img)
+ return imgs
diff --git a/kornia/nerf/positional_encoder.py b/kornia/nerf/positional_encoder.py
new file mode 100755
index 000000000..425977aef
--- /dev/null
+++ b/kornia/nerf/positional_encoder.py
@@ -0,0 +1,54 @@
+import torch
+from torch import nn
+
+from kornia.core import Tensor
+
+
+class PositionalEncoder(nn.Module):
+ r"""Sine-cosine positional encoder for input points.
+
+ Args:
+ num_dims: Number of input dimensions (channels): int
+ num_freqs: Number of frequency bands for encoding span: int
+ log_space: Whether frequency sampling should be log spaced: bool
+ """
+
+ def __init__(self, num_dims: int, num_freqs: int, log_space: bool = False) -> None:
+ super().__init__()
+ self._num_dims = num_dims
+ self._embed_fns = [lambda x: x]
+
+ # Define frequencies in either linear or log scale
+ if log_space:
+ freq_bands = 2.0 ** torch.linspace(0.0, num_freqs - 1, num_freqs)
+ else:
+ freq_bands = torch.linspace(2.0**0.0, 2.0 ** (num_freqs - 1), num_freqs)
+
+ # Alternate sin and cos
+ for freq in freq_bands:
+ self._embed_fns.append(lambda x, freq=freq: torch.sin(x * freq)) # FIXME: PI?
+ self._embed_fns.append(lambda x, freq=freq: torch.cos(x * freq))
+
+ self._num_encoded_dims = self._num_dims * len(self._embed_fns)
+
+ @property
+ def num_encoded_dims(self) -> int:
+ return self._num_encoded_dims
+
+ def forward(self, x: Tensor) -> Tensor:
+ r"""Apply positional encoding to input.
+
+ Args:
+ x: Positionsl (or directional) tensor to encode: Tensor
+
+ Returns:
+ Tensor with encoded position/direction: Tensor
+ """
+ if x.ndim < 1:
+ raise ValueError('Input tensor represents a scalar')
+ if x.shape[-1] != self._num_dims:
+ raise ValueError(
+ f'Input tensor number of dimensions {x.shape[-1]} does not match instantiated dimensionality '
+ f'{self._num_dims}'
+ )
+ return torch.cat([fn(x) for fn in self._embed_fns], dim=-1)
diff --git a/kornia/nerf/rays.py b/kornia/nerf/rays.py
new file mode 100755
index 000000000..1bbe5ba2e
--- /dev/null
+++ b/kornia/nerf/rays.py
@@ -0,0 +1,427 @@
+import math
+from typing import Dict, List, Optional, Tuple
+
+import torch
+
+from kornia.core import Device, Tensor
+from kornia.geometry.camera import PinholeCamera
+from kornia.nerf.camera_utils import cameras_for_ids
+from kornia.utils._compat import torch_meshgrid
+from kornia.utils.helpers import _torch_inverse_cast
+
+
+class RaySampler:
+ r"""Class to manage spatial ray sampling.
+
+ Args:
+ min_depth: sampled rays minimal depth from cameras: float
+ max_depth: sampled rays maximal depth from cameras: float
+ ndc: convert ray parameters to normalized device coordinates: bool
+ device: device for ray tensors: Union[str, torch.device]
+ """
+ _origins: Optional[Tensor] = None # Ray origins in world coordinates (*, 3)
+ _directions: Optional[Tensor] = None # Ray directions in world coordinates (*, 3)
+ _directions_cam: Optional[Tensor] = None # Ray directions in camera coordinates (*, 3)
+ _origins_cam: Optional[Tensor] = None # Ray origins in camera coordinates (*, 3)
+ _camera_ids: Optional[Tensor] = None # Ray camera ID
+ _points_2d: Optional[Tensor] = None # Ray intersection with image plane in camera coordinates
+
+ def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
+ self._min_depth = min_depth
+ self._max_depth = max_depth
+ self._ndc = ndc
+ self._device = torch.device(device)
+ self._dtype = dtype
+
+ @property
+ def origins(self) -> Tensor:
+ return self._origins
+
+ @property
+ def directions(self) -> Tensor:
+ return self._directions
+
+ @property
+ def camera_ids(self) -> Tensor:
+ return self._camera_ids
+
+ @property
+ def points_2d(self) -> Tensor:
+ return self._points_2d
+
+ def __len__(self) -> int:
+ if self.origins is None:
+ return 0
+ return self.origins.shape[0]
+
+ def _calc_ray_directions_cam(self, cameras: PinholeCamera, points_2d: Tensor):
+ # FIXME: This function should call perspective.unproject_points or, implement in PinholeCamera unproject to
+ # camera coordinates that will call perspective.unproject_points
+ fx = cameras.fx
+ fy = cameras.fy
+ cx = cameras.cx
+ cy = cameras.cy
+ directions_x = (points_2d[..., 0] - cx[..., None]) / fx[..., None]
+ directions_y = (points_2d[..., 1] - cy[..., None]) / fy[..., None]
+ directions_z = torch.ones_like(directions_x)
+ directions_cam = torch.stack([directions_x, directions_y, directions_z], dim=-1)
+ return directions_cam.reshape(-1, 3)
+
+ class Points2D:
+ r"""A class to hold ray 2d pixel coordinates and a camera id for each.
+
+ Args:
+ points_2d: tensor with ray pixel coordinates (the coordinates in the image plane that correspond to the
+ ray):math:`(B, 2)`
+ camera_ids: list of camera ids for each pixel coordinates: List[int]
+ """
+
+ def __init__(self, points_2d: Tensor, camera_ids: List[int]) -> None:
+ self._points_2d = points_2d # (*, N, 2)
+ self._camera_ids = camera_ids
+
+ @property
+ def points_2d(self):
+ return self._points_2d
+
+ @property
+ def camera_ids(self):
+ return self._camera_ids
+
+ def _calc_ray_params(self, cameras: PinholeCamera, points_2d_camera: Dict[int, Points2D]) -> None:
+ r"""Calculates ray parameters: origins, directions. Also stored are camera ids for each ray, and its pixel
+ coordinates.
+
+ Args:
+ cameras: scene cameras: PinholeCamera
+ points_2d_camera: a dictionary that groups Point2D objects by total number of casted rays
+ """
+
+ # Unproject 2d points in image plane to 3d world for two depths
+ origins = []
+ directions = []
+ directions_cam = []
+ origins_cam = []
+ camera_ids = []
+ points_2d = []
+ for obj in points_2d_camera.values():
+
+ # FIXME: Below both world and camera ray directions are calculated. It could be that world ray directions
+ # will not be necessary and can be removed here
+ num_cams_group, num_points_per_cam_group = obj._points_2d.shape[:2]
+ depths = (
+ torch.ones(num_cams_group, 2 * num_points_per_cam_group, 3, device=self._device, dtype=self._dtype)
+ * self._min_depth
+ )
+ depths[:, num_points_per_cam_group:] = self._max_depth
+ cams = cameras_for_ids(cameras, obj.camera_ids)
+ points_3d = cams.unproject(obj._points_2d.repeat(1, 2, 1), depths)
+ origins.append(points_3d[..., :num_points_per_cam_group, :].reshape(-1, 3))
+ directions.append(
+ (points_3d[..., num_points_per_cam_group:, :] - points_3d[..., :num_points_per_cam_group, :]).reshape(
+ -1, 3
+ )
+ )
+ directions_cam.append(self._calc_ray_directions_cam(cams, obj._points_2d))
+ origins_cam.append(directions_cam[-1] * self._min_depth)
+ camera_ids.append(
+ torch.tensor(obj.camera_ids).repeat(num_points_per_cam_group, 1).permute(1, 0).reshape(1, -1).squeeze(0)
+ )
+ points_2d.append(obj._points_2d.reshape(-1, 2).int())
+ self._origins = torch.cat(origins)
+ self._directions = torch.cat(directions)
+ self._directions_cam = torch.cat(directions_cam)
+ self._origins_cam = torch.cat(origins_cam)
+ self._camera_ids = torch.cat(camera_ids)
+ if self._ndc: # Transform ray parameters to NDC, if defined
+ self._origins, self._directions = self.transform_ray_params_world_to_ndc(cameras)
+ self._points_2d = torch.cat(points_2d)
+
+ def transform_ray_params_world_to_ndc(self, cameras: PinholeCamera) -> Tuple[Tensor, Tensor]:
+ r"""Transforms ray parameters to normalized coordinate device (camera) system (NDC)
+
+ Args:
+ cameras: scene cameras: PinholeCamera
+ """
+ cams = cameras_for_ids(cameras, self._camera_ids)
+ fx = cams.fx
+ fy = cams.fy
+ widths = cams.width
+ heights = cams.height
+ fx_widths = 2.0 * fx / (widths - 1.0)
+ fy_heights = 2.0 * fy / (heights - 1.0)
+
+ # oxoz = self._origins_cam[..., 0] / self._origins_cam[..., 2]
+ # oyoz = self._origins_cam[..., 1] / self._origins_cam[..., 2]
+
+ oxoz = self._origins[..., 0] / self._origins[..., 2]
+ oyoz = self._origins[..., 1] / self._origins[..., 2]
+
+ origins_ndc_x = fx_widths * oxoz
+ origins_ndc_y = fy_heights * oyoz
+
+ # origins_ndc_z = 1 - 2 * self._min_depth / self._origins_cam[..., 2]
+
+ origins_ndc_z = 1 - 2 * self._min_depth / self._origins[..., 2]
+
+ origins_ndc = torch.stack([origins_ndc_x, origins_ndc_y, origins_ndc_z], dim=-1)
+
+ # dxdz = self._directions_cam[..., 0] / self._directions_cam[..., 2]
+ # dydz = self._directions_cam[..., 1] / self._directions_cam[..., 2]
+
+ Rt_inv = _torch_inverse_cast(cams.rotation_matrix)
+ directions_rotated_world = (Rt_inv @ self._directions_cam[..., None]).squeeze(dim=-1)
+
+ dxdz = directions_rotated_world[..., 0] / directions_rotated_world[..., 2]
+ dydz = directions_rotated_world[..., 1] / directions_rotated_world[..., 2]
+
+ directions_ndc_x = fx_widths * dxdz - origins_ndc_x
+ directions_ndc_y = fy_heights * dydz - origins_ndc_y
+ directions_ndc_z = 1 - origins_ndc_z
+ directions_ndc = torch.stack([directions_ndc_x, directions_ndc_y, directions_ndc_z], dim=-1)
+
+ # Rt_inv = _torch_inverse_cast(cams.rotation_matrix)
+ # origins_ndc_world = (Rt_inv @ origins_ndc[..., None]).squeeze(dim=-1)
+ # directions_ndc_world = (Rt_inv @ directions_ndc[..., None]).squeeze(dim=-1)
+
+ origins_ndc_world = origins_ndc
+ directions_ndc_world = directions_ndc
+
+ return origins_ndc_world, directions_ndc_world
+
+ class Points2D_FlatTensors:
+ r"""Class to hold x/y pixel coordinates for each ray, and its scene camera id."""
+
+ def __init__(self) -> None:
+ self._x: Tensor
+ self._y: Tensor
+ self._camera_ids: List[int] = []
+
+ @staticmethod
+ def _add_points2d_as_flat_tensors_to_num_ray_dict(
+ n: int,
+ x: torch.tensor,
+ y: torch.tensor,
+ camera_id: int,
+ points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors],
+ ) -> None:
+ r"""Adds x/y pixel coordinates for all rays casted by a scene camera to dictionary of pixel coordinates
+ grouped by total number of rays."""
+ if n not in points2d_as_flat_tensors:
+ points2d_as_flat_tensors[n] = RaySampler.Points2D_FlatTensors()
+ points2d_as_flat_tensors[n]._x = x.flatten()
+ points2d_as_flat_tensors[n]._y = y.flatten()
+ else:
+ points2d_as_flat_tensors[n]._x = torch.cat((points2d_as_flat_tensors[n]._x, x.flatten()))
+ points2d_as_flat_tensors[n]._y = torch.cat((points2d_as_flat_tensors[n]._y, y.flatten()))
+ points2d_as_flat_tensors[n]._camera_ids.append(camera_id)
+
+ @staticmethod
+ def _build_num_ray_dict_of_points2d(
+ points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors]
+ ) -> Dict[int, Points2D]:
+ r"""Builds a dictionary of ray pixel points, by total number of rays as key. The dictionary groups rays by
+ the total amount of rays, which allows the case of casting different number of rays from each scene camera.
+
+ Args:
+ points2d_as_flat_tensors: dictionary of pixel coordinates grouped by total number of rays:
+ Dict[int, Points2D_FlatTensors]
+
+ Returns:
+ dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
+ id it was casted by: Dict[int, Points2D]
+ """
+ num_ray_dict_of_points2d: Dict[int, RaySampler.Points2D] = {}
+ for n, points2d_as_flat_tensor in points2d_as_flat_tensors.items():
+ num_cams = len(points2d_as_flat_tensor._camera_ids)
+ points_2d = (
+ torch.stack((points2d_as_flat_tensor._x, points2d_as_flat_tensor._y))
+ .permute(1, 0)
+ .reshape(num_cams, -1, 2)
+ )
+ num_ray_dict_of_points2d[n] = RaySampler.Points2D(points_2d, points2d_as_flat_tensor._camera_ids)
+ return num_ray_dict_of_points2d
+
+
+class RandomRaySampler(RaySampler):
+ r"""Class to manage random ray spatial sampling.
+
+ Args:
+ min_depth: sampled rays minimal depth from cameras: float
+ max_depth: sampled rays maximal depth from cameras: float
+ ndc: convert to normalized device coordinates: bool
+ device: device for ray tensors: Union[str, torch.device]
+ """
+
+ def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
+ super().__init__(min_depth, max_depth, ndc, device, dtype)
+
+ def sample_points_2d(self, heights: Tensor, widths: Tensor, num_img_rays: Tensor) -> Dict[int, RaySampler.Points2D]:
+ r"""Randomly sample pixel points in 2d.
+
+ Args:
+ heights: tensor that holds scene camera image heights (can vary between cameras): math: `(B)`.
+ widths: tensor that holds scene camera image widths (can vary between cameras): math: `(B)`.
+ num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera: math: `(B)`.
+
+ Returns:
+ dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
+ id it was casted by: Dict[int, Points2D]
+ """
+ num_img_rays = num_img_rays.int()
+ points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
+ for camera_id, (height, width, n) in enumerate(zip(heights.tolist(), widths.tolist(), num_img_rays.tolist())):
+ y_rand = torch.trunc(torch.rand(n, device=self._device, dtype=self._dtype) * height)
+ x_rand = torch.trunc(torch.rand(n, device=self._device, dtype=self._dtype) * width)
+ RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
+ n, x_rand, y_rand, camera_id, points2d_as_flat_tensors
+ )
+ return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
+
+ def calc_ray_params(self, cameras: PinholeCamera, num_img_rays: Tensor) -> None:
+ r"""Calculates ray parameters: origins, directions. Also stored are camera ids for each ray, and its pixel
+ coordinates.
+
+ Args:
+ cameras: scene cameras: PinholeCamera
+ num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera: int math: `(B)`.
+ """
+ num_cams = cameras.batch_size
+ if num_cams != num_img_rays.shape[0]:
+ raise ValueError(
+ f'Number of cameras {num_cams} does not match size of tensor to define number of rays to march from '
+ f'each camera {num_img_rays.shape[0]}'
+ )
+ points_2d_camera = self.sample_points_2d(cameras.height, cameras.width, num_img_rays)
+ self._calc_ray_params(cameras, points_2d_camera)
+
+
+class RandomGridRaySampler(RandomRaySampler):
+ r"""Class to manage random ray spatial sampling. Sampling is done on a regular grid of pixels by randomizing
+ column and row values, and casting rays for all pixels along the seleceted ones.
+
+ Args:
+ min_depth: sampled rays minimal depth from cameras: float
+ max_depth: sampled rays maximal depth from cameras: float
+ ndc: convert to normalized device coordinates: bool
+ device: device for ray tensors: Union[str, torch.device]
+ """
+
+ def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
+ super().__init__(min_depth, max_depth, ndc, device, dtype)
+
+ def sample_points_2d(self, heights: Tensor, widths: Tensor, num_img_rays: Tensor) -> Dict[int, RaySampler.Points2D]:
+ r"""Randomly sample pixel points in 2d over a regular row-column grid.
+
+ Args:
+ heights: tensor that holds scene camera image heights (can vary between cameras): math: `(B)`.
+ widths: tensor that holds scene camera image widths (can vary between cameras): math: `(B)`.
+ num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera. Number of rows
+ and columns is the square root of this value: int math: `(B)`.
+
+ Returns:
+ dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
+ id it was casted by: Dict[int, Points2D]
+ """
+ num_img_rays = num_img_rays.int()
+ points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
+ for camera_id, (height, width, n) in enumerate(zip(heights.tolist(), widths.tolist(), num_img_rays.tolist())):
+ n_sqrt = int(math.sqrt(n))
+ y_rand = torch.randperm(int(height), device=self._device, dtype=self._dtype)[: min(int(height), n_sqrt)]
+ x_rand = torch.randperm(int(width), device=self._device, dtype=self._dtype)[: min(int(width), n_sqrt)]
+ y_grid, x_grid = torch_meshgrid([y_rand, x_rand], indexing='ij')
+ RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
+ n_sqrt * n_sqrt, x_grid, y_grid, camera_id, points2d_as_flat_tensors
+ )
+ return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
+
+
+class UniformRaySampler(RaySampler):
+ r"""Class to manage uniform ray spatial sampling for all camera scene pixels.
+
+ Args:
+ min_depth: sampled rays minimal depth from cameras: float
+ max_depth: sampled rays maximal depth from cameras: float
+ ndc: convert to normalized device coordinates: bool
+ device: device for ray tensors: Union[str, torch.device]
+ """
+
+ def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
+ super().__init__(min_depth, max_depth, ndc, device, dtype)
+
+ def sample_points_2d(self, heights: Tensor, widths: Tensor, sampling_step=1) -> Dict[int, RaySampler.Points2D]:
+ r"""Uniformly sample pixel points in 2d for all scene camera pixels.
+
+ Args:
+ heights: tensor that holds scene camera image heights (can vary between cameras): math: `(B)`.
+ widths: tensor that holds scene camera image widths (can vary between cameras): math: `(B)`.
+ sampling_step: defines uniform strides between rows and columns: int.
+
+ Returns:
+ dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
+ id it was casted by: Dict[int, Points2D]
+ """
+ heights = heights.int()
+ widths = widths.int()
+ points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
+ for camera_id, (height, width) in enumerate(zip(heights.tolist(), widths.tolist())):
+ n = height * width
+ y_grid, x_grid = torch_meshgrid(
+ [
+ torch.arange(0, height, sampling_step, device=self._device, dtype=self._dtype),
+ torch.arange(0, width, sampling_step, device=self._device, dtype=self._dtype),
+ ],
+ indexing='ij',
+ )
+ RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
+ n, x_grid, y_grid, camera_id, points2d_as_flat_tensors
+ )
+ return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
+
+ def calc_ray_params(self, cameras: PinholeCamera) -> None:
+ points_2d_camera = self.sample_points_2d(cameras.height, cameras.width)
+ self._calc_ray_params(cameras, points_2d_camera)
+
+
+def sample_lengths(num_rays: int, num_ray_points: int, device: Device, dtype: torch.dtype, irregular=False) -> Tensor:
+ if num_ray_points <= 1:
+ raise ValueError('Number of ray points must be greater than 1')
+ if not irregular:
+ zero_to_one = torch.linspace(0.0, 1.0, num_ray_points, device=device, dtype=dtype)
+ lengths = zero_to_one.repeat(num_rays, 1) # FIXME: Expand instead of repeat maybe?
+ else:
+ zero_to_one = torch.linspace(0.0, 1.0, num_ray_points + 1, device=device, dtype=dtype)
+ lengths = torch.rand(num_rays, num_ray_points, device=device) / num_ray_points + zero_to_one[:-1]
+ return lengths
+
+
+# TODO: Implement hierarchical ray sampling as described in Mildenhall (2020) Sec. 5.2
+
+
+def sample_ray_points(
+ origins: Tensor, directions: Tensor, lengths: Tensor
+) -> Tensor: # FIXME: Test by projecting to points_2d and compare with sampler 2d points
+ r"""
+ Args:
+ origins: tensor containing ray origins in 3d world coordinates. Tensor shape :math:`(*, 3)`.
+ directions: tensor containing ray directions in 3d world coordinates. Tensor shape :math:`(*, 3)`.
+ lengths: tensor cotaining sampled distances along each ray. Tensor shape :math:`(*, num_ray_points)`.
+
+ Returns:
+ points_3d: Points along rays :math:`(*, num_ray_points, 3)`
+ """
+ points_3d = origins[..., None, :] + lengths[..., None] * directions[..., None, :]
+ return points_3d
+
+
+def calc_ray_t_vals(points_3d: Tensor) -> Tensor:
+ r"""Calculates t values along rays.
+
+ Args:
+ points_3d: Points along rays :math:`(*, num_ray_points, 3)`
+
+ Returns:
+ t values along rays :math:`(*, num_ray_points)`
+ """
+ t_vals = torch.linalg.norm(points_3d - points_3d[..., 0, :].unsqueeze(-2), dim=-1)
+ return t_vals
diff --git a/kornia/nerf/renderer.py b/kornia/nerf/renderer.py
new file mode 100755
index 000000000..495293ce7
--- /dev/null
+++ b/kornia/nerf/renderer.py
@@ -0,0 +1,82 @@
+import torch
+
+from kornia.core import Tensor
+from kornia.nerf.rays import calc_ray_t_vals
+
+
+class VolumeRenderer(torch.nn.Module):
+ r"""Volume renderer class. Implementation follows Ben Mildenhall et el. (2020) at
+ https://arxiv.org/abs/2003.08934.
+
+ Args:
+ shift: Size of far-field layer: int
+ """
+ _huge = 1.0e10
+ _eps = 1.0e-10
+
+ def __init__(self, shift: int = 1) -> None:
+ super().__init__()
+ self._shift = shift
+
+ def _render(self, alpha: Tensor, rgbs: Tensor) -> Tensor:
+ trans = torch.cumprod(1 - alpha + self._eps, dim=-2) # (*, N, 1)
+ trans = torch.roll(trans, shifts=self._shift, dims=-2) # (*, N, 1)
+ trans[..., : self._shift, :] = 1 # (*, N, 1)
+
+ weights = trans * alpha # (*, N, 1)
+
+ rgbs_rendered = torch.sum(weights * rgbs, dim=-2) # (*, 3)
+
+ return rgbs_rendered
+
+ def forward(self, rgbs: Tensor, densities: Tensor, points_3d: torch.tensor) -> Tensor:
+ raise NotImplementedError
+
+
+class IrregularRenderer(VolumeRenderer):
+ def __init__(self, shift: int = 1) -> None:
+ super().__init__(shift)
+
+ def forward(self, rgbs: Tensor, densities: Tensor, points_3d: torch.tensor) -> Tensor:
+ r"""Renders 3D irregularly sampled points along rays.
+
+ Args:
+ rgbs: RGB values of points along rays :math:`(*, N, 3)`
+ densities: Volume densities of points along rays :math:`(*, N)`
+ t_vals: Sampled point distances along rays :math: `(*, N)`
+
+ Returns:
+ Rendered RGB values for each ray :math:`(*, 3)`
+ """
+ t_vals = calc_ray_t_vals(points_3d)
+ deltas = t_vals[..., 1:] - t_vals[..., :-1] # (*, N - 1)
+ far = torch.empty(size=t_vals.shape[:-1], dtype=t_vals.dtype, device=t_vals.device).fill_(self._huge)
+ deltas = torch.cat([deltas, far[..., None]], dim=-1) # (*, N)
+
+ alpha = 1 - torch.exp(-1.0 * densities * deltas[..., None]) # (*, N)
+
+ return self._render(alpha, rgbs)
+
+
+class RegularRenderer(VolumeRenderer):
+ def __init__(self, shift: int = 1) -> None:
+ super().__init__(shift)
+
+ def forward(self, rgbs: Tensor, densities: Tensor, points_3d: torch.tensor) -> Tensor:
+ r"""Renders 3D regularly sampled points along rays.
+
+ Args:
+ rgbs: RGB values of points along rays :math:`(*, N, 3)`
+ densities: Volume densities of points along rays :math:`(*, N)`
+ deltas: Equispaced distance for point pairs along each ray :math: `(*)`
+
+ Returns:
+ Rendered RGB values for each ray :math:`(*, 3)`
+ """
+ num_ray_points = points_3d.shape[-2]
+ delta_3d = points_3d.reshape(-1, num_ray_points, 3)[0, 1, :] - points_3d.reshape(-1, num_ray_points, 3)[0, 0, :]
+ delta = torch.linalg.norm(delta_3d, dim=-1)
+
+ alpha = 1 - torch.exp(-1.0 * densities * delta) # (*, N)
+
+ return self._render(alpha, rgbs)
diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.py
index 28fd9c915..dad7add98 100644
--- a/kornia/utils/_compat.py
+++ b/kornia/utils/_compat.py
@@ -59,3 +59,9 @@ else:
def torch_meshgrid(tensors: List[Tensor], indexing: str):
return torch.meshgrid(tensors)
+
+
+if torch_version_ge(1, 10, 0):
+ torch_inference_mode = torch.inference_mode
+else:
+ torch_inference_mode = torch.no_grad
diff --git a/test/nerf/test_camera_utils.py b/test/nerf/test_camera_utils.py
new file mode 100755
index 000000000..8c4300b68
--- /dev/null
+++ b/test/nerf/test_camera_utils.py
@@ -0,0 +1,51 @@
+from pathlib import Path
+
+import pytest
+import torch
+
+from kornia.geometry.conversions import QuaternionCoeffOrder, quaternion_to_rotation_matrix
+from kornia.nerf.camera_utils import create_spiral_path, parse_colmap_output
+from kornia.testing import assert_close
+
+
+def colmap_cameras_path():
+ return Path(__file__).parent / './cameras.txt'
+
+
+def colmap_images_path():
+ return Path(__file__).parent / './images.txt'
+
+
+def test_parse_colmap_output(device, dtype, colmap_cameras_path, colmap_images_path) -> None:
+ img_names, cameras = parse_colmap_output(colmap_cameras_path, colmap_images_path, device, dtype)
+ assert_close(cameras.fx[0], torch.tensor(845.5654, device=device, dtype=dtype))
+ assert_close(cameras.fy[0], torch.tensor(845.5654, device=device, dtype=dtype))
+ assert_close(cameras.cx[0], torch.tensor(504, device=device, dtype=dtype))
+ assert_close(cameras.cy[0], torch.tensor(378, device=device, dtype=dtype))
+
+ qw = 0.99967420027533338
+ qx = -0.016637661896892787
+ qy = 0.012113517278577941
+ qz = 0.015097821353390602
+ tx = 3.2407154690493751
+ ty = 2.3447342819165637
+ tz = -1.0631749488011808
+
+ q = torch.tensor([qw, qx, qy, qz], device=device, dtype=dtype)
+ R = quaternion_to_rotation_matrix(q, order=QuaternionCoeffOrder.WXYZ)
+ t = torch.tensor([tx, ty, tz], device=device, dtype=dtype)
+
+ assert_close(R, cameras.rotation_matrix[2])
+ assert_close(cameras.translation_vector[2], t.unsqueeze(-1))
+
+ assert img_names[2] == 'image002.png'
+
+
+def test_create_spiral_path(device, dtype, colmap_cameras_path, colmap_images_path) -> None:
+ _, cameras = parse_colmap_output(colmap_cameras_path, colmap_images_path, device, dtype)
+ try:
+ create_spiral_path(cameras, 1, 30, 3)
+ except Exception as err:
+ assert False, err
diff --git a/test/nerf/test_data_utils.py b/test/nerf/test_data_utils.py
new file mode 100755
index 000000000..4953bfd7a
--- /dev/null
+++ b/test/nerf/test_data_utils.py
@@ -0,0 +1,52 @@
+from test.nerf.test_rays import create_four_cameras
+
+import torch
+
+from kornia.core import Device
+from kornia.geometry.camera import PinholeCamera
+from kornia.nerf.data_utils import ImageTensors, RayDataset, instantiate_ray_dataloader
+from kornia.testing import assert_close
+
+
+def create_random_images_for_cameras(cameras: PinholeCamera) -> ImageTensors:
+ torch.manual_seed(112)
+ imgs: ImageTensors = []
+ for height, width in zip(cameras.height.tolist(), cameras.width.tolist()):
+ imgs.append(torch.randint(0, 255, (3, int(height), int(width)), dtype=torch.uint8)) # (C, H, W)
+ return imgs
+
+
+def create_red_images_for_cameras(cameras: PinholeCamera, device: Device) -> ImageTensors:
+ imgs: ImageTensors = []
+ for height, width in zip(cameras.height.tolist(), cameras.width.tolist()):
+ red_img = torch.zeros(3, int(height), int(width), dtype=torch.uint8) # (C, H, W)
+ red_img[0, ...] = 255
+ imgs.append(red_img.to(device=device))
+ return imgs
+
+
+class TestDataset:
+ def test_uniform_ray_dataset(self, device, dtype):
+ cameras = create_four_cameras(device, dtype)
+ imgs = create_random_images_for_cameras(cameras)
+ dataset = RayDataset(cameras, 1, 2, False, device=device, dtype=dtype)
+ dataset.init_ray_dataset()
+ dataset.init_images_for_training(imgs)
+
+ batch_size = 32
+ data_loader = instantiate_ray_dataloader(dataset, batch_size=batch_size, shuffle=False)
+ d = next(iter(data_loader)) # First batch of 32 labeled rays
+
+ # Check dimensions
+ assert d[0].shape == (batch_size, 3) # Ray origins
+ assert d[1].shape == (batch_size, 3) # Ray directions
+ assert d[2].shape == (batch_size, 3) # Ray rgbs
+
+ # Comparing RGB values between sampled rays and original images
+ assert_close(d[2][0].cpu().to(dtype), (imgs[0][:, 0, 0] / 255.0).to(dtype))
+ assert_close(
+ d[2][1].cpu().to(dtype), (imgs[0][:, 0, 1] / 255.0).to(dtype)
+ ) # First row, second column in the image (1 sample point index)
+ assert_close(
+ d[2][9].cpu().to(dtype), (imgs[0][:, 1, 0] / 255.0).to(dtype)
+ ) # Second row, first column in the image (9 sample point index)
diff --git a/test/nerf/test_nerf_model.py b/test/nerf/test_nerf_model.py
new file mode 100755
index 000000000..955bf6482
--- /dev/null
+++ b/test/nerf/test_nerf_model.py
@@ -0,0 +1,34 @@
+import torch
+
+from kornia.nerf.nerf_model import MLP, NerfModel
+
+
+class TestNerfModel:
+ def test_mlp(self, device, dtype):
+ d_input = 63 # Input dimension after encoding
+ num_hidden = 256
+ mlp = MLP(d_input, num_units=2, num_unit_layers=4, num_hidden=num_hidden)
+ mlp.to(device=device, dtype=dtype)
+
+ num_rays = 15
+ num_ray_points = 11
+ x = torch.rand(num_rays, num_ray_points, d_input, device=device, dtype=dtype)
+ xout = mlp(x)
+ assert xout.shape == (num_rays, num_ray_points, num_hidden)
+
+ def test_nerf(self, device, dtype):
+ num_ray_points = 11
+ nerf_model = NerfModel(
+ num_ray_points=num_ray_points,
+ num_pos_freqs=10,
+ num_dir_freqs=4,
+ num_units=2,
+ num_unit_layers=4,
+ num_hidden=256,
+ )
+ nerf_model.to(device=device, dtype=dtype)
+ num_rays = 15
+ origins = torch.rand(num_rays, 3, device=device, dtype=dtype)
+ directions = torch.rand(num_rays, 3, device=device, dtype=dtype)
+ rgbs = nerf_model(origins, directions)
+ assert rgbs.shape == (num_rays, 3)
diff --git a/test/nerf/test_nerf_solver.py b/test/nerf/test_nerf_solver.py
new file mode 100755
index 000000000..d32e2f987
--- /dev/null
+++ b/test/nerf/test_nerf_solver.py
@@ -0,0 +1,62 @@
+from test.nerf.test_data_utils import create_random_images_for_cameras, create_red_images_for_cameras
+from test.nerf.test_rays import create_four_cameras, create_one_camera
+
+import torch
+
+from kornia.nerf.nerf_solver import NerfSolver
+from kornia.testing import assert_close
+
+
+class TestNerfSolver:
+ def test_parameter_change_after_one_epoch(self, device, dtype):
+ nerf_obj = NerfSolver(device, dtype)
+ cameras = create_four_cameras(device, dtype)
+ imgs = create_random_images_for_cameras(cameras)
+ nerf_obj.init_training(cameras, 1.0, 3.0, True, imgs, num_img_rays=45, batch_size=1, num_ray_points=10)
+
+ params_before_update = [torch.clone(param).detach() for param in nerf_obj.nerf_model.parameters()]
+
+ nerf_obj.run(num_epochs=5)
+
+ params_after_update = [torch.clone(param).detach() for param in nerf_obj.nerf_model.parameters()]
+
+ assert all(
+ not torch.equal(param_before_update, param_after_update)
+ for param_before_update, param_after_update in zip(params_before_update, params_after_update)
+ )
+
+ def test_only_red_uniform_sampling(self, device, dtype):
+ torch.manual_seed(1) # For reproducibility of random processes
+ camera = create_one_camera(5, 9, device, dtype)
+ img = create_red_images_for_cameras(camera, device)
+
+ nerf_obj = NerfSolver(device, dtype)
+ nerf_obj.init_training(camera, 1.0, 3.0, False, img, None, 2, 10)
+ nerf_obj.run(num_epochs=10)
+
+ img_rendered = nerf_obj.render_views(camera)[0].permute(2, 0, 1)
+
+ assert_close(img_rendered.to(dtype) / 255.0, img[0].to(dtype) / 255.0)
+
+ def test_single_ray(self, device, dtype):
+ camera = create_one_camera(5, 9, device, dtype)
+ img = create_red_images_for_cameras(camera, device)
+
+ nerf_obj = NerfSolver(device=device, dtype=dtype)
+ nerf_obj.init_training(camera, 1.0, 3.0, True, img, 1, 2, 10)
+ nerf_obj.run(num_epochs=20)
+
+ def test_only_red(self, device, dtype):
+ torch.manual_seed(0) # For reproducibility of random processes
+
+ camera = create_one_camera(5, 9, device, dtype)
+ img = create_red_images_for_cameras(camera, device)
+
+ nerf_obj = NerfSolver(device=device, dtype=dtype)
+ num_img_rays = 15
+ nerf_obj.init_training(camera, 1.0, 3.0, False, img, num_img_rays, batch_size=5, num_ray_points=10, lr=1e-2)
+ nerf_obj.run(num_epochs=10)
+
+ img_rendered = nerf_obj.render_views(camera)[0].permute(2, 0, 1)
+
+ assert_close(img_rendered.to(dtype) / 255.0, img[0].to(dtype) / 255.0)
diff --git a/test/nerf/test_positional_encoder.py b/test/nerf/test_positional_encoder.py
new file mode 100755
index 000000000..5fa7eb1ff
--- /dev/null
+++ b/test/nerf/test_positional_encoder.py
@@ -0,0 +1,15 @@
+import torch
+
+from kornia.nerf.positional_encoder import PositionalEncoder
+
+
+class TestPositionalEncoder:
+ def test_dimensions(self, device, dtype):
+ num_rays = 15
+ num_ray_points = 11
+ num_dims = 3
+ x = torch.rand(num_rays, num_ray_points, num_dims)
+ num_freqs = 10
+ pos_encoder = PositionalEncoder(num_dims, num_freqs)
+ x_encoded = pos_encoder(x)
+ assert x_encoded.shape == (num_rays, num_ray_points, pos_encoder.num_encoded_dims)
diff --git a/test/nerf/test_rays.py b/test/nerf/test_rays.py
new file mode 100755
index 000000000..a4220e8c3
--- /dev/null
+++ b/test/nerf/test_rays.py
@@ -0,0 +1,222 @@
+import math
+
+import torch
+
+from kornia.core import Device
+from kornia.geometry.camera import PinholeCamera
+from kornia.nerf.rays import (
+ RandomGridRaySampler,
+ RandomRaySampler,
+ UniformRaySampler,
+ calc_ray_t_vals,
+ cameras_for_ids,
+ sample_lengths,
+ sample_ray_points,
+)
+from kornia.testing import assert_close
+
+
+def create_camera_dimensions(device, dtype):
+ n_cams1 = 3
+ n_cams2 = 2
+ heights: torch.Tensor = torch.cat(
+ (
+ torch.tensor([200] * n_cams1, device=device, dtype=dtype),
+ torch.tensor([100] * n_cams2, device=device, dtype=dtype),
+ )
+ )
+ widths: torch.Tensor = torch.cat(
+ (
+ torch.tensor([300] * n_cams1, device=device, dtype=dtype),
+ torch.tensor([400] * n_cams2, device=device, dtype=dtype),
+ )
+ )
+ num_img_rays: torch.Tensor = torch.cat(
+ (
+ torch.tensor([10] * n_cams1, device=device, dtype=dtype),
+ torch.tensor([15] * n_cams2, device=device, dtype=dtype),
+ )
+ )
+ return heights, widths, num_img_rays
+
+
+class TestRaySampler_2DPoints:
+ def test_dimensions_random_sampler(self, device, dtype):
+ heights, widths, num_img_rays = create_camera_dimensions(device, dtype)
+ sampler = RandomRaySampler(1, 1, ndc=False, device=device, dtype=dtype)
+ points_2d_camera = sampler.sample_points_2d(heights, widths, num_img_rays)
+ assert len(points_2d_camera) == 2
+ assert points_2d_camera[10].points_2d.shape == (3, 10, 2)
+ assert points_2d_camera[15].points_2d.shape == (2, 15, 2)
+
+ def test_dimensions_uniform_sampler(self, device, dtype):
+ heights, widths, _ = create_camera_dimensions(device, dtype)
+ sampler = UniformRaySampler(1, 1, ndc=False, device=device, dtype=dtype)
+ points_2d_camera = sampler.sample_points_2d(heights, widths)
+ assert len(points_2d_camera) == 2
+ assert points_2d_camera[60000].points_2d.shape == (3, 60000, 2)
+ assert points_2d_camera[40000].points_2d.shape == (2, 40000, 2)
+
+ def test_dimensions_radom_grid_sampler(self, device, dtype):
+ heights, widths, num_img_rays = create_camera_dimensions(device, dtype)
+ sampler = RandomGridRaySampler(1, 1, True, device=device, dtype=dtype)
+ points_2d_camera = sampler.sample_points_2d(heights, widths, num_img_rays)
+ assert len(points_2d_camera) == 1
+ assert points_2d_camera[9].points_2d.shape == (5, 9, 2)
+
+
+def create_intrinsics(fxs, fys, cxs, cys, device, dtype):
+ intrinsics_batch = []
+ for fx, fy, cx, cy in zip(fxs, fys, cxs, cys):
+ intrinsics = torch.eye(4, device=device, dtype=dtype)
+ intrinsics[0, 0] = fx
+ intrinsics[1, 1] = fy
+ intrinsics[0, 2] = cx
+ intrinsics[1, 2] = cy
+ intrinsics_batch.append(intrinsics)
+ return torch.stack(intrinsics_batch)
+
+
+def create_extrinsics_with_rotation(alphas, betas, gammas, txs, tys, tzs, device, dtype):
+ extrinsics_batch = []
+ for alpha, beta, gamma, tx, ty, tz in zip(alphas, betas, gammas, txs, tys, tzs):
+ Rx = torch.eye(3, device=device, dtype=dtype)
+ Rx[1, 1] = math.cos(alpha)
+ Rx[1, 2] = math.sin(alpha)
+ Rx[2, 1] = -Rx[1, 2]
+ Rx[2, 2] = Rx[1, 1]
+
+ Ry = torch.eye(3, device=device, dtype=dtype)
+ Ry[0, 0] = math.cos(beta)
+ Ry[0, 2] = -math.sin(beta)
+ Ry[2, 0] = -Ry[0, 2]
+ Ry[2, 2] = Ry[0, 0]
+
+ Rz = torch.eye(3, device=device, dtype=dtype)
+ Rz[0, 0] = math.cos(gamma)
+ Rz[0, 1] = math.sin(gamma)
+ Rz[1, 0] = -Rz[0, 1]
+ Rz[1, 1] = Rz[0, 0]
+
+ Ryz = torch.matmul(Ry, Rz)
+ R = torch.matmul(Rx, Ryz)
+
+ extrinsics = torch.eye(4, device=device, dtype=dtype)
+ extrinsics[..., 0, -1] = tx
+ extrinsics[..., 1, -1] = ty
+ extrinsics[..., 2, -1] = tz
+ extrinsics[:3, :3] = R
+
+ extrinsics_batch.append(extrinsics)
+ return torch.stack(extrinsics_batch)
+
+
+def create_one_camera(height, width, device: Device, dtype: torch.dtype) -> PinholeCamera:
+ fx = width
+ fy = height
+ cx = (width - 1.0) / 2.0
+ cy = (height - 1.0) / 2.0
+
+ tx = 0.0
+ ty = 0.0
+ tz = 1.0
+
+ alpha = math.pi / 2.0
+ beta = 0.0
+ gamma = -math.pi / 2.0
+
+ intrinsics = create_intrinsics([fx], [fy], [cx], [cy], device=device, dtype=dtype)
+ extrinsics = create_extrinsics_with_rotation([alpha], [beta], [gamma], [tx], [ty], [tz], device=device, dtype=dtype)
+
+ return PinholeCamera(
+ intrinsics,
+ extrinsics,
+ torch.tensor([height], device=device, dtype=dtype),
+ torch.tensor([width], device=device, dtype=dtype),
+ )
+
+
+def create_four_cameras(device, dtype) -> PinholeCamera:
+ height = torch.tensor([5, 4, 4, 4], device=device, dtype=dtype)
+ width = torch.tensor([9, 7, 7, 7], device=device, dtype=dtype)
+
+ fx = width.tolist()
+ fy = height.tolist()
+
+ cx = (width - 1.0) / 2.0
+ cy = (height - 1.0) / 2.0
+
+ tx = [0.0, 0.0, 0.0, 0.0]
+ ty = [0.0, 0.0, 0.0, 0.0]
+ tz = [11.0, 11.0, 11.0, 5.0]
+
+ pi = math.pi
+ alpha = [pi / 2.0, pi / 2.0, pi / 2.0, 0.0]
+ beta = [0.0, 0.0, 0.0, pi]
+ gamma = [-pi / 2.0, 0.0, pi / 2.0, 0.0]
+
+ intrinsics = create_intrinsics(fx, fy, cx, cy, device=device, dtype=dtype)
+ extrinsics = create_extrinsics_with_rotation(alpha, beta, gamma, tx, ty, tz, device=device, dtype=dtype)
+
+ cameras = PinholeCamera(intrinsics, extrinsics, height, width)
+ return cameras
+
+
+class TestRaySampler_3DPoints:
+ def test_dimensions_uniform_sampler(self, device, dtype):
+ cameras = create_four_cameras(device, dtype)
+ uniform_sampler_four_cameras = UniformRaySampler(1, 1, False, device=device, dtype=dtype)
+ points_2d_four_cameras = uniform_sampler_four_cameras.sample_points_2d(cameras.height, cameras.width)
+ cameras_28 = cameras_for_ids(cameras, points_2d_four_cameras[28].camera_ids)
+ points_3d_28 = cameras_28.unproject(points_2d_four_cameras[28].points_2d, 1)
+ cameras_40 = cameras_for_ids(cameras, points_2d_four_cameras[45].camera_ids)
+ points_3d_40 = cameras_40.unproject(points_2d_four_cameras[45].points_2d, 1)
+ assert points_3d_28.shape == (3, 28, 3)
+ assert points_3d_40.shape == (1, 45, 3)
+
+ def test_dimensions_ray_params(self, device, dtype):
+ cameras = create_four_cameras(device, dtype)
+ uniform_sampler_four_cameras = UniformRaySampler(1, 2, False, device=device, dtype=dtype)
+ uniform_sampler_four_cameras.calc_ray_params(cameras)
+ lengths = sample_lengths(
+ uniform_sampler_four_cameras.origins.shape[0], 10, device=device, dtype=dtype, irregular=True
+ )
+ assert uniform_sampler_four_cameras.origins.shape == (3 * 28 + 45, 3)
+ assert uniform_sampler_four_cameras.directions.shape == (3 * 28 + 45, 3)
+ assert uniform_sampler_four_cameras.camera_ids.shape == (3 * 28 + 45,)
+ assert uniform_sampler_four_cameras.points_2d.shape == (3 * 28 + 45, 2)
+ assert lengths.shape == (3 * 28 + 45, 10)
+
+ def test_dimensions_sample_ray_points(self, device, dtype):
+ cameras = create_four_cameras(device, dtype)
+ uniform_sampler_four_cameras = UniformRaySampler(1, 2, False, device, dtype=dtype)
+ uniform_sampler_four_cameras.calc_ray_params(cameras)
+ lengths = sample_lengths(
+ uniform_sampler_four_cameras.origins.shape[0], 10, device=device, dtype=dtype, irregular=True
+ )
+ points_3d = sample_ray_points(
+ uniform_sampler_four_cameras.origins, uniform_sampler_four_cameras.directions, lengths
+ )
+ assert points_3d.shape == (3 * 28 + 45, 10, 3)
+
+ def test_t_vals(self, device, dtype):
+ cameras = create_four_cameras(device, dtype)
+ uniform_sampler_four_cameras = UniformRaySampler(2, 3.0, False, device=device, dtype=dtype)
+ uniform_sampler_four_cameras.calc_ray_params(cameras)
+ lengths = sample_lengths(
+ uniform_sampler_four_cameras.origins.shape[0], 10, device=device, dtype=dtype, irregular=False
+ )
+ points_3d = sample_ray_points(
+ uniform_sampler_four_cameras.origins, uniform_sampler_four_cameras.directions, lengths
+ )
+ t_vals = calc_ray_t_vals(points_3d)
+ assert t_vals.shape == (3 * 28 + 45, 10)
+ assert_close(t_vals[22, -1].item(), 1.0) # Testing middle ray
+
+ def test_dimensions_ray_params_in_ndc(self, device, dtype):
+ cameras = create_four_cameras(device, dtype)
+ uniform_sampler_four_cameras = UniformRaySampler(2, 3.5, False, device=device, dtype=dtype)
+ uniform_sampler_four_cameras.calc_ray_params(cameras)
+ origins_ndc, directions_ndc = uniform_sampler_four_cameras.transform_ray_params_world_to_ndc(cameras)
+ assert origins_ndc.shape == (3 * 28 + 45, 3)
+ assert directions_ndc.shape == (3 * 28 + 45, 3)
diff --git a/test/nerf/test_renderer.py b/test/nerf/test_renderer.py
new file mode 100755
index 000000000..951664a82
--- /dev/null
+++ b/test/nerf/test_renderer.py
@@ -0,0 +1,87 @@
+import math
+
+import torch
+
+from kornia.core import Device, Tensor
+from kornia.nerf.renderer import IrregularRenderer, RegularRenderer
+from kornia.testing import assert_close
+
+
+def _create_regular_point_cloud(
+ height: int, width: int, num_ray_points: int, device: Device, dtype: torch.dtype
+) -> Tensor:
+ x = torch.linspace(0, width, steps=width, device=device, dtype=dtype)
+ y = torch.linspace(0, height, steps=height, device=device, dtype=dtype)
+ xy = torch.meshgrid(y, x)
+ z = torch.linspace(1, 11, steps=num_ray_points, device=device, dtype=dtype)
+ points3d = torch.zeros(height, width, num_ray_points, 3, device=device, dtype=dtype)
+ points3d[..., 0] = xy[0].unsqueeze(-1)
+ points3d[..., 1] = xy[1].unsqueeze(-1)
+ points3d[..., 2] = z
+ return points3d
+
+
+class TestRenderer:
+ def test_dimensions(self, device, dtype):
+ height = 5
+ width = 4
+ num_ray_points = 7
+ rgbs = torch.rand((height, width, num_ray_points, 3), dtype=dtype, device=device)
+ densities = torch.rand((height, width, num_ray_points, 1), dtype=dtype, device=device)
+
+ points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
+
+ irreg_renderer = IrregularRenderer()
+ rgb_rendered = irreg_renderer(rgbs, densities, points3d)
+ assert rgb_rendered.shape == (height, width, 3)
+
+ def test_only_red(self, device, dtype):
+ height = 5
+ width = 4
+ num_ray_points = 7
+ rgbs = torch.zeros((height, width, num_ray_points, 3), dtype=dtype, device=device)
+ rgbs[..., 0] = 1
+ densities = torch.rand((height, width, num_ray_points, 1), dtype=dtype, device=device)
+
+ points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
+
+ irreg_renderer = IrregularRenderer()
+ rgbs_rendered = irreg_renderer(rgbs, densities, points3d)
+ only_reds = torch.zeros_like(rgbs_rendered, dtype=dtype, device=device)
+ only_reds[..., 0] = 1.0
+ assert_close(rgbs_rendered, only_reds)
+
+ def test_shell(self, device, dtype):
+ height = 5
+ width = 4
+ num_ray_points = 11
+ rgbs = torch.rand((height, width, num_ray_points, 3), dtype=dtype, device=device)
+ densities = torch.zeros((height, width, num_ray_points, 1), dtype=dtype, device=device)
+ densities[..., 0, :] = 1
+
+ points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
+
+ regular_renderer = RegularRenderer()
+ rgbs_rendered = regular_renderer(rgbs, densities, points3d)
+
+ weight = 1 - math.exp(-1.0)
+ assert_close(rgbs_rendered, weight * rgbs[..., 0, :])
+
+ def test_regular_vs_irregular(self, device, dtype):
+ height = 5
+ width = 4
+ num_ray_points = 11
+ rgbs = torch.rand((height, width, num_ray_points, 3), dtype=dtype, device=device)
+ densities = torch.zeros((height, width, num_ray_points, 1), dtype=dtype, device=device)
+ densities[..., 0, :] = 10
+
+ points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
+
+ irreg_renderer = IrregularRenderer()
+ irreg_rgb_rendered = irreg_renderer(rgbs, densities, points3d)
+
+ regular_renderer = RegularRenderer()
+ regular_rgbs_rendered = regular_renderer(rgbs, densities, points3d)
+
+ assert irreg_rgb_rendered.shape == regular_rgbs_rendered.shape
+ assert_close(irreg_rgb_rendered, regular_rgbs_rendered)