Skip to contents

Optimizes 3D Gaussian Splatting parameters (positions, anisotropic scales, rotations, opacities, and spherical-harmonics colors) directly from a collection of calibrated multi-view photos and camera poses (COLMAP or Agisoft Metashape), following Kerbl et al. (2023).

Each iteration renders one training view with a differentiable tile rasterizer, computes the photometric loss \((1-\lambda) L_1 + \lambda (1 - \mathrm{SSIM})\) against the photo, backpropagates exact analytical gradients and applies Adam. Adaptive density control periodically clones small and splits large Gaussians in under-reconstructed regions (high screen-space positional gradient), prunes transparent or oversized ones and resets opacities to remove floaters.

When a colmap_sfm object (or a splat derived from one, e.g. via gs_filter_outliers()) is supplied and the camera model contains lens distortion (e.g. "OPENCV"), the photos are first undistorted with COLMAP's image_undistorter, because Gaussian splatting assumes an ideal pinhole camera. Point clouds that have not been optimized yet are re-initialized as in the reference implementation (opacity 0.1, isotropic scale equal to the RMS distance to the 3 nearest neighbours).

Two back ends are available: a CUDA back end (Python + PyTorch + CuPy, runtime-compiled rasterization kernels) and a native multithreaded C++ (OpenMP) back end. The CPU back end optimizes base colors only (SH degree 0), uses an \(L_1\) loss and is intended for small scenes. Speed-ups of the GPU back end depend on the available NVIDIA hardware; low-memory GPUs may need a larger downsample or a lower max_gaussians. See the section Back ends and requirements (Python) below.

Distance-like thresholds (scale_threshold, max_scale) and the position learning rate are expressed relative to the scene extent (1.1 x the radius of the camera rig), so the same defaults work for any reconstruction scale.

Usage

gs_fit(
  images,
  cameras = NULL,
  splat = NULL,
  iterations = 7000,
  lr_pos = 0.00016,
  lr_scale = 0.005,
  lr_opac = 0.05,
  lr_sh = 0.0025,
  densify_interval = 100,
  densify_until = round(iterations * 0.5),
  grad_threshold = 2e-04,
  scale_threshold = 0.01,
  min_opacity = 0.005,
  max_scale = 0.1,
  max_gaussians = 5e+05,
  downsample = 4,
  device = c("auto", "gpu", "cpu"),
  verbose = TRUE,
  sh_degree = 3,
  lr_rot = 0.001,
  lambda_dssim = 0.2,
  densify_from = NULL,
  opacity_reset_interval = 3000,
  undistort = TRUE,
  reinit = c("auto", "always", "never"),
  white_background = FALSE,
  seed = 42,
  as_job = FALSE
)

Arguments

images

Character path to directory with photos, character vector of image file paths, a list of loaded Image objects, a colmap_sfm object, or a gaussian_splat carrying cameras and images (e.g. from gs_filter_outliers()).

cameras

Named list of camera specifications (from gs_import_cameras_colmap()).

splat

Optional initial gaussian_splat object (e.g., from gs_import_metashape() sparse tie points). If NULL, initialized automatically from camera bounding volume.

iterations

Integer. Total number of optimization steps. Defaults to 7000 (the "7k" quality checkpoint of the original paper; 30000 gives the full-quality result).

lr_pos

Double. Initial learning rate for 3D Gaussian positions, relative to the scene extent. Decays exponentially to lr_pos / 100. Defaults to 0.00016.

lr_scale

Double. Learning rate for log-scales. Defaults to 0.005.

lr_opac

Double. Learning rate for opacity logits. Defaults to 0.05.

lr_sh

Double. Learning rate for base colors (SH band 0). Higher bands use lr_sh / 20. Defaults to 0.0025.

densify_interval

Integer. Iteration frequency for adaptive densification and pruning. Defaults to 100.

densify_until

Integer. Iteration after which densification stops. Defaults to round(iterations * 0.5).

grad_threshold

Double. Average screen-space (NDC) positional gradient that triggers split/clone. Defaults to 0.0002. Lower values produce more Gaussians and finer detail.

scale_threshold

Double. Fraction of the scene extent separating clone (smaller) from split (larger) Gaussians ("percent dense"). Defaults to 0.01.

min_opacity

Double. Minimum opacity below which Gaussians are pruned. Defaults to 0.005.

max_scale

Double. Gaussians larger than max_scale x scene extent (or covering more than 20 pixels after the first opacity reset) are pruned. Defaults to 0.1.

max_gaussians

Integer. Maximum number of Gaussians allowed during adaptive densification. Defaults to 500000.

downsample

Numeric. Downsample factor for training images (e.g. 1, 2, 4) to accelerate optimization. Defaults to 4.

device

Character. Computing device for optimization: "auto" (default: automatically uses dedicated NVIDIA GPU via CUDA if available, otherwise CPU), "gpu" (forces GPU acceleration, aborting if CUDA is unavailable), or "cpu" (native C++ OpenMP). The GPU back end requires Python with PyTorch (CUDA) and CuPy; the CPU back end needs no Python. See the section Back ends and requirements (Python).

verbose

Logical. If TRUE, displays progress and training metrics. Defaults to TRUE.

sh_degree

Integer (0-3). Maximum spherical-harmonics degree for view-dependent color. One band is activated every 1000 iterations. Defaults to 3 (GPU) - the CPU back end uses 0.

lr_rot

Double. Learning rate for rotation quaternions. Defaults to 0.001.

lambda_dssim

Double. Weight of the D-SSIM term in the loss. Defaults to 0.2.

densify_from

Integer. First iteration of densification. If NULL (default), min(500, iterations / 10).

opacity_reset_interval

Integer. Opacities are reset to 0.01 every this many iterations during densification (removes floaters). 0 disables. Defaults to 3000.

undistort

Logical. If TRUE (default), photos of COLMAP reconstructions with lens distortion are undistorted (COLMAP image_undistorter) before training.

reinit

Character. Re-initialization of point-cloud Gaussians before training: "auto" (default; only when the splat has not been optimized yet), "always", or "never".

white_background

Logical. Composite renders over white instead of black. Defaults to FALSE.

seed

Integer. Random seed for view ordering and densification. Defaults to 42.

as_job

Logical. If TRUE and running inside RStudio, the optimization runs as an RStudio background job; the trained splat is assigned to splat_trained in the global environment and saved to gs_fit_result.rds in the working directory. Defaults to FALSE.

Value

A trained gaussian_splat object (with $cameras, $images, $train_history).

Back ends and requirements (Python)

gs_fit() has two training back ends with different requirements and results:

deviceEngineRequires Python?Result
"gpu"inst/python/gs_trainer.py (PyTorch + CuPy CUDA kernels)YesFull Kerbl et al. (2023) method: SH up to degree 3 (view-dependent color), L1 + D-SSIM loss. Recommended for faithful 3D models.
"cpu"Native C++ (OpenMP), bundled with plimanNoBase colors only (SH degree 0), L1 loss, much slower. For small scenes, tests or machines without an NVIDIA GPU.
"auto" (default)GPU when the requirements below are met, otherwise CPUOnly for the GPUFalls back to the CPU back end (with a console message explaining why) if Python/PyTorch/CUDA is not available.

The GPU back end runs an external Python process. The script gs_trainer.py ships with pliman (system.file("python", "gs_trainer.py", package = "pliman")); R writes the images, cameras and initial splats to temporary files, calls Python and reads the optimized splats back. To use it you need:

  • an NVIDIA GPU with an up-to-date driver;

  • Python 3 available in the PATH (python, python3 or py) or in a standard installation folder;

  • PyTorch built with CUDA, e.g. pip install torch --index-url https://download.pytorch.org/whl/cu124;

  • CuPy matching the CUDA major version of the driver, e.g. pip install cupy-cuda12x;

  • numpy and Pillow (installed together with PyTorch in most setups).

No CUDA Toolkit, nvcc or C++ compiler is needed: CuPy compiles the rasterization kernels at run time (NVRTC). The gsplat Python package is not required. Use device = "gpu" to make sure the GPU back end is used (an informative error is raised if it is not available) and device = "cpu" to run without Python at all.

Speed depends on the hardware: as a reference, 7,000 iterations on 171 photos at 1000 x 560 px (downsample = 2) took about 15 min on a GTX 1650 (4 GB). GPUs with little memory may need a larger downsample or a lower max_gaussians.

References

Kerbl, B., Kopanas, G., Leimkuehler, T., & Drettakis, G. (2023). 3D Gaussian splatting for real-time radiance field rendering. ACM Transactions on Graphics, 42(4), 1-14.

Examples

if (FALSE) { # interactive()
library(pliman)

# 1. Camera poses + sparse tie points with COLMAP
sfm <- colmap_sfm("photos/")
sfm_clean <- gs_filter_outliers(sfm, k = 5, std_ratio = 2)

# 2. Train 3D Gaussian Splats on GPU (CUDA)
splat <- gs_fit(sfm_clean, iterations = 7000, downsample = 2)

# 3. Interactive WebGL viewer with true anisotropic splat rendering
gs_viewer(splat)
gs_export_ply(splat, "plant_splat.ply")
}