diff --git a/nerfstudio/scripts/exporter.py b/nerfstudio/scripts/exporter.py index b6985b2c9..3cdc818aa 100644 --- a/nerfstudio/scripts/exporter.py +++ b/nerfstudio/scripts/exporter.py @@ -584,13 +584,16 @@ class ExportGaussianSplat(Exporter): positions = model.means.cpu().numpy() quats = model.quats.data.cpu().numpy() + count = positions.shape[0] + n = count + if self.save_world_frame: assert isinstance(pipeline.datamanager, FullImageDatamanager) # ns gplat uses quaternions in [w,x,y,z] format while scipy uses [x, y, z, w] rot_ns = ScR.from_quat(quats[:, [1, 2, 3, 0]]).as_matrix() # apply the inverse dataparser transform to the splat - poses = np.eye(4, dtype=np.float32)[None, ...].repeat(positions.shape[0], axis=0)[:, :3, :] + poses = np.zeros((n, 3, 4), dtype=np.float32) poses[:, :3, :3] = rot_ns poses[:, :3, 3] = positions poses = pipeline.datamanager.train_dataparser_outputs.transform_poses_to_original_space( @@ -601,8 +604,6 @@ class ExportGaussianSplat(Exporter): quats = rot_world.as_quat()[:, [3, 0, 1, 2]] # convert back to [w,x,y,z] format positions = poses[:, :3, 3].cpu().numpy() - count = positions.shape[0] - n = count map_to_tensors["x"] = positions[:, 0] map_to_tensors["y"] = positions[:, 1] map_to_tensors["z"] = positions[:, 2] @@ -632,10 +633,11 @@ class ExportGaussianSplat(Exporter): if self.save_world_frame: # The 0th order coefficients (l=0) are constant and invariant to rotation. # They don't affect the rotation of the rest of the SH. - shs_coeffs_all = torch.zeros((n, 3, shs_rest.shape[-1] + 1), device=shs_rest.device) + dim_sh_all = shs_rest.shape[-1] + 1 + shs_coeffs_all = torch.zeros((n, 3, dim_sh_all), device=shs_rest.device) shs_coeffs_all[:, :, 1:] = shs_rest output_rotation = pipeline.datamanager.train_dataparser_outputs.dataparser_transform[:3, :3].T - shs_rest = rotate_spherical_harmonics(shs_coeffs_all, output_rotation)[:, :, 1:] + shs_rest = rotate_spherical_harmonics(output_rotation, shs_coeffs_all)[:, :, 1:] shs_rest = shs_rest.cpu().numpy().reshape((n, -1)) @@ -647,7 +649,7 @@ class ExportGaussianSplat(Exporter): # Note that scales are in log space! scales = model.scales.data.cpu().numpy() if self.save_world_frame: - scales += np.log(pipeline.datamanager.train_dataparser_outputs.dataparser_scale) + scales += np.log(1 / pipeline.datamanager.train_dataparser_outputs.dataparser_scale) for i in range(3): map_to_tensors[f"scale_{i}"] = scales[:, i, None] diff --git a/nerfstudio/utils/spherical_harmonics.py b/nerfstudio/utils/spherical_harmonics.py index a4b97479b..4fc7f7178 100644 --- a/nerfstudio/utils/spherical_harmonics.py +++ b/nerfstudio/utils/spherical_harmonics.py @@ -115,14 +115,14 @@ def SH2RGB(sh): def rotate_spherical_harmonics( - coeffs: Float[Tensor, "*batch dim_sh"], rotation_matrix: Float[Tensor, "3 3"], + coeffs: Float[Tensor, "*batch dim_sh"], ) -> Float[Tensor, "*batch dim_sh"]: - """Rotates real spherical harmonic coefficients of degree l using given 3x3 rotation matrix. + """Rotates real spherical harmonic coefficients using a given 3x3 rotation matrix. Args: - coeffs : SH coefficients rotation_matrix : A 3x3 rotation matrix. + coeffs : SH coefficients Returns: The rotated SH coefficients @@ -131,8 +131,13 @@ def rotate_spherical_harmonics( assert math.isqrt(dim_sh) ** 2 == dim_sh, "dim_sh must be a perfect square (l+1)^2" sh_degree = int(math.sqrt(dim_sh)) - 1 - rotation_matrix = rotation_matrix.cpu() + # e3nn uses the xyz ordering instead of the standard yzx used in ns, equivalent to a change of basis + R_yzx_to_xyz = torch.tensor([[0, 0, 1], [1, 0, 0], [0, 1, 0]], dtype=torch.float32) + R_total = (R_yzx_to_xyz.T @ rotation_matrix @ R_yzx_to_xyz).cpu() + irreps = Irreps(" + ".join([f"{i}e" for i in range(sh_degree + 1)])) # Even parity spherical harmonics of degree l - D_matrix = irreps.D_from_matrix(rotation_matrix).to(coeffs.device) # Construct Wigner D-matrix - rotated_coeffs = torch.einsum("ij,...j->...i", D_matrix, coeffs) + D_matrix = irreps.D_from_matrix(R_total).to(coeffs.device) # Construct Wigner D-matrix + + # Multiply last dimension of coeffs (..., dim_sh) with the Wigner D-matrix (dim_sh, dim_sh) + rotated_coeffs = coeffs @ D_matrix.T return rotated_coeffs diff --git a/pyproject.toml b/pyproject.toml index 2deda4fd3..26efa97e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,7 +69,8 @@ dependencies = [ "pathos", "packaging", "fpsample", - "tensorly" + "tensorly", + "e3nn>=0.5.1" ] [project.urls] diff --git a/tests/utils/test_spherical_harmonics.py b/tests/utils/test_spherical_harmonics.py index b2e98ea1c..562d60a5b 100644 --- a/tests/utils/test_spherical_harmonics.py +++ b/tests/utils/test_spherical_harmonics.py @@ -11,7 +11,7 @@ from nerfstudio.utils.spherical_harmonics import ( @pytest.mark.parametrize("degree", list(range(0, 5))) -def test_spherical_harmonics(degree): +def test_spherical_harmonics_components(degree): torch.manual_seed(0) N = 1000000 @@ -23,30 +23,55 @@ def test_spherical_harmonics(degree): @pytest.mark.parametrize("sh_degree", list(range(0, 4))) -def test_rotate_spherical_harmonics(sh_degree): +def test_spherical_harmonics_rotation(sh_degree): + """Test if rotating both the view direction and SH coefficients by the same rotation + produces the same color output as the original. + + In other words, for any rotation R: + color(dir, coeffs) = color(R @ dir, rotate_sh(R, coeffs)) + """ torch.manual_seed(0) np.random.seed(0) + N = 1000 num_coeffs = (sh_degree + 1) ** 2 - coeffs = torch.rand(1000, 3, num_coeffs) + sh_coeffs = torch.rand(N, 3, num_coeffs) + dirs = torch.rand(N, 3) + dirs = dirs / torch.linalg.norm(dirs, dim=-1, keepdim=True) + + y_lm = components_from_spherical_harmonics(sh_degree, dirs) + color_original = (sh_coeffs * y_lm[..., None, :]).sum(dim=-1) rot_matrix = torch.tensor(ScR.random().as_matrix(), dtype=torch.float32) - rotated_coeffs = rotate_spherical_harmonics(coeffs, rot_matrix) + sh_coeffs_rotated = rotate_spherical_harmonics(rot_matrix, sh_coeffs) + dirs_rotated = (rot_matrix @ dirs.T).T + y_lm_rotated = components_from_spherical_harmonics(sh_degree, dirs_rotated) + color_rotated = (sh_coeffs_rotated * y_lm_rotated[..., None, :]).sum(dim=-1) - # Norm Preservation - norm_original = torch.norm(coeffs, dim=-1) - norm_rotated = torch.norm(rotated_coeffs, dim=-1) + torch.testing.assert_close(color_original, color_rotated, rtol=0, atol=1e-5) + + +@pytest.mark.parametrize("sh_degree", list(range(0, 4))) +def test_spherical_harmonics_rotation_properties(sh_degree): + """Test properties of the SH rotation""" + torch.manual_seed(0) + np.random.seed(0) + + N = 1000 + num_coeffs = (sh_degree + 1) ** 2 + sh_coeffs = torch.rand(N, 3, num_coeffs) + rot_matrix = torch.tensor(ScR.random().as_matrix(), dtype=torch.float32) + sh_coeffs_rotated = rotate_spherical_harmonics(rot_matrix, sh_coeffs) + + # Norm preserving + norm_original = torch.norm(sh_coeffs, dim=-1) + norm_rotated = torch.norm(sh_coeffs_rotated, dim=-1) torch.testing.assert_close(norm_original, norm_rotated, rtol=0, atol=1e-5) - # 0th order coeffs are invariant to rotation - torch.testing.assert_close(coeffs[..., 0], rotated_coeffs[..., 0], rtol=0, atol=1e-6) + # 0th degree coeffs are invariant to rotation + torch.testing.assert_close(sh_coeffs[..., 0], sh_coeffs_rotated[..., 0], rtol=0, atol=1e-6) - # 1st order coeffs undergo simple rotation - if sh_degree > 0: - act_1st_order = torch.einsum("ij,...j->...i", rot_matrix, coeffs[..., 1:4]) - torch.testing.assert_close(act_1st_order, rotated_coeffs[..., 1:4], rtol=0, atol=1e-5) - - # Identity Rotation + # Identity rotation rot_matrix = torch.eye(3) - rotated_coeffs = rotate_spherical_harmonics(coeffs, rot_matrix) - torch.testing.assert_close(coeffs, rotated_coeffs, rtol=0, atol=1e-6) + sh_coeffs_rotated = rotate_spherical_harmonics(rot_matrix, sh_coeffs) + torch.testing.assert_close(sh_coeffs, sh_coeffs_rotated, rtol=0, atol=1e-6)