extrinterp 1.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
extrinterp/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .abc import Extrinsic, ExtrinsicDataset, Extrinsic2CameraDataset
2
+ from .interp import interpolation, smooth_interpolation
3
+ from .dataset import ExtrinsicInterpolator, ExtrinsicInterpolationDataset
extrinterp/abc.py ADDED
@@ -0,0 +1,86 @@
1
+ from abc import abstractmethod
2
+ from typing import NamedTuple
3
+
4
+ import torch
5
+ from torch.utils.data import Dataset
6
+
7
+ from gaussian_splatting import Camera
8
+ from gaussian_splatting.dataset import CameraDataset
9
+ from gaussian_splatting.camera import build_camera
10
+
11
+
12
+ class Extrinsic(NamedTuple):
13
+ R: torch.Tensor
14
+ T: torch.Tensor
15
+
16
+ @classmethod
17
+ def from_camera(cls, camera: Camera) -> 'Extrinsic':
18
+ return cls(
19
+ R=camera.R,
20
+ T=camera.T,
21
+ )
22
+
23
+ def to_camera(
24
+ self,
25
+ image_height: int, image_width: int,
26
+ FoVx: float, FoVy: float,
27
+ *args, **kwargs
28
+ ) -> Camera:
29
+ return build_camera(
30
+ image_width=image_width,
31
+ image_height=image_height,
32
+ FoVx=FoVx,
33
+ FoVy=FoVy,
34
+ R=self.R,
35
+ T=self.T,
36
+ *args, **kwargs
37
+ )
38
+
39
+ def to(self, device):
40
+ return Extrinsic(
41
+ R=self.R.to(device),
42
+ T=self.T.to(device),
43
+ )
44
+
45
+
46
+ class ExtrinsicDataset(Dataset):
47
+ @abstractmethod
48
+ def to(self, device) -> 'ExtrinsicDataset':
49
+ return self
50
+
51
+ @abstractmethod
52
+ def __len__(self) -> int:
53
+ raise NotImplementedError
54
+
55
+ @abstractmethod
56
+ def __getitem__(self, idx) -> Extrinsic:
57
+ raise NotImplementedError
58
+
59
+
60
+ class Extrinsic2CameraDataset(CameraDataset):
61
+ def __init__(
62
+ self,
63
+ dataset: ExtrinsicDataset,
64
+ image_height: int = 1000, image_width: int = 1000,
65
+ FoVx: float = 90.0*torch.pi/180, FoVy: float = 90.0*torch.pi/180):
66
+ self.cameras = dataset
67
+ self.image_height = image_height
68
+ self.image_width = image_width
69
+ self.FoVx = FoVx
70
+ self.FoVy = FoVy
71
+
72
+ def __len__(self):
73
+ return len(self.cameras)
74
+
75
+ def __getitem__(self, idx) -> Camera:
76
+ return self.cameras[idx].to_camera(
77
+ image_height=self.image_height,
78
+ image_width=self.image_width,
79
+ FoVx=self.FoVx,
80
+ FoVy=self.FoVy,
81
+ device=self.cameras[idx].R.device
82
+ )
83
+
84
+ def to(self, device):
85
+ self.cameras = self.cameras.to(device)
86
+ return self
extrinterp/dataset.py ADDED
@@ -0,0 +1,26 @@
1
+ from gaussian_splatting.dataset import CameraDataset
2
+ from .abc import Extrinsic, ExtrinsicDataset, Extrinsic2CameraDataset
3
+ from .interp import smooth_interpolation
4
+
5
+
6
+ class ExtrinsicInterpolator(ExtrinsicDataset):
7
+
8
+ def __init__(self, dataset: CameraDataset, n: int, window_size: int = 3):
9
+ self.cameras = smooth_interpolation(dataset=dataset, n=n, window_size=window_size)
10
+
11
+ def __len__(self):
12
+ return len(self.cameras)
13
+
14
+ def __getitem__(self, idx) -> Extrinsic:
15
+ return self.cameras[idx]
16
+
17
+ def to(self, device):
18
+ self.cameras = [camera.to(device) for camera in self.cameras]
19
+ return self
20
+
21
+
22
+ def ExtrinsicInterpolationDataset(dataset: CameraDataset, n: int, *args, window_size: int = 3, **kwargs) -> Extrinsic2CameraDataset:
23
+ return Extrinsic2CameraDataset(
24
+ dataset=ExtrinsicInterpolator(dataset=dataset, n=n, window_size=window_size),
25
+ *args, **kwargs
26
+ )
extrinterp/interp.py ADDED
@@ -0,0 +1,64 @@
1
+ from typing import List
2
+ import torch
3
+ from gaussian_splatting.utils import matrix_to_quaternion, quaternion_to_matrix
4
+ from .abc import Extrinsic
5
+
6
+
7
+ def linspace_cameras(start: Extrinsic, end: Extrinsic, n: int) -> List[Extrinsic]:
8
+ ratio = torch.linspace(0, 1, n, device=start.R.device).unsqueeze(-1)
9
+ Ts = start.T.unsqueeze(0) + ratio * (end.T.unsqueeze(0) - start.T.unsqueeze(0))
10
+ q_start, q_end = matrix_to_quaternion(start.R), matrix_to_quaternion(end.R)
11
+ qs = q_start.unsqueeze(0) + ratio * (q_end.unsqueeze(0) - q_start.unsqueeze(0))
12
+ Rs = quaternion_to_matrix(qs)
13
+ return [Extrinsic(R=R, T=T) for R, T in zip(Rs, Ts)]
14
+
15
+
16
+ def sort_cameras(cameras: List[Extrinsic]) -> List[Extrinsic]:
17
+ Ts = torch.stack([camera.T for camera in cameras])
18
+ distances = torch.cdist(Ts, Ts)
19
+ next_idx = distances.mean(0).argmax()
20
+ sorted_cameras = [cameras.pop(next_idx)]
21
+ while cameras:
22
+ distances = torch.cdist(sorted_cameras[-1].T.unsqueeze(0), torch.stack([camera.T for camera in cameras])).squeeze(0)
23
+ next_idx = distances.argmin()
24
+ sorted_cameras.append(cameras.pop(next_idx))
25
+ return sorted_cameras
26
+
27
+
28
+ def interpolation(cameras: List[Extrinsic], n: int) -> List[Extrinsic]:
29
+ cameras = sort_cameras(cameras)
30
+ new_cameras = []
31
+ for i in range(len(cameras) - 1):
32
+ k = round((n - 1) / (len(cameras) - 1 - i))
33
+ new_cameras.extend(linspace_cameras(cameras[i], cameras[i + 1], k + 1)[:-1])
34
+ n -= k
35
+ new_cameras.append(cameras[-1])
36
+ return new_cameras
37
+
38
+
39
+ def smooth_1d(inputs: torch.Tensor, window_size: int = 3) -> torch.Tensor:
40
+ shape = inputs.shape
41
+ inputs = inputs.view(shape[0], -1).T.unsqueeze(1)
42
+ if window_size % 2 == 0:
43
+ raise ValueError("Window size must be odd.")
44
+ kernel = torch.ones((1, 1, window_size), device=inputs.device) / window_size
45
+ outputs = torch.nn.functional.conv1d(inputs, kernel, stride=1, padding=0)
46
+ return outputs.squeeze(1).T.view(shape[0] - window_size//2*2, *shape[1:]).contiguous()
47
+
48
+
49
+ def smooth(cameras: List[Extrinsic], window_size: int = 3) -> List[Extrinsic]:
50
+ Ts = smooth_1d(torch.stack([camera.T for camera in cameras]), window_size=window_size)
51
+ Rs = quaternion_to_matrix(smooth_1d(matrix_to_quaternion(torch.stack([camera.R for camera in cameras])), window_size=window_size))
52
+ return [
53
+ cameras[i]._replace(R=R, T=T)
54
+ for i, (R, T) in enumerate(zip(Rs, Ts))
55
+ ]
56
+
57
+
58
+ def smooth_interpolation(dataset: List[Extrinsic], n: int, window_size: int = 3) -> List[Extrinsic]:
59
+ if window_size % 2 == 0:
60
+ raise ValueError("Window size must be odd.")
61
+ cameras = [Extrinsic.from_camera(camera) for camera in dataset]
62
+ if len(cameras) == (n + window_size // 2 * 2):
63
+ return smooth(cameras, window_size=window_size)
64
+ return smooth(interpolation(cameras, n + window_size // 2 * 2), window_size=window_size)
extrinterp/render.py ADDED
@@ -0,0 +1,70 @@
1
+ from typing import Tuple
2
+ import torch
3
+ import os
4
+ from tqdm import tqdm
5
+ from os import makedirs
6
+ import torchvision
7
+ import tifffile
8
+ from gaussian_splatting import GaussianModel
9
+ from gaussian_splatting.dataset import CameraDataset
10
+ from gaussian_splatting.prepare import prepare_dataset, prepare_gaussians
11
+ from extrinterp import ExtrinsicInterpolationDataset
12
+
13
+
14
+ def prepare_rendering(
15
+ sh_degree: int, source: str, device: str, n: int, window_size: int,
16
+ trainable_camera: bool = False, load_ply: str = None, load_camera: str = None,
17
+ use_intrinsics: int | dict = 0
18
+ ) -> Tuple[CameraDataset, GaussianModel]:
19
+ dataset = prepare_dataset(source=source, device=device, trainable_camera=trainable_camera, load_camera=load_camera, load_depth=False)
20
+ if isinstance(use_intrinsics, int):
21
+ i = use_intrinsics
22
+ use_intrinsics = dict(
23
+ image_height=dataset[i].image_height, image_width=dataset[i].image_width,
24
+ FoVx=dataset[i].FoVx, FoVy=dataset[i].FoVy)
25
+ elif not isinstance(use_intrinsics, dict):
26
+ raise ValueError("Invalid use_intrinsics format")
27
+ dataset = ExtrinsicInterpolationDataset(dataset=dataset, n=n, window_size=window_size, **use_intrinsics)
28
+ gaussians = prepare_gaussians(sh_degree=sh_degree, source=source, device=device, trainable_camera=trainable_camera, load_ply=load_ply)
29
+ return dataset, gaussians
30
+
31
+
32
+ def rendering(dataset: CameraDataset, gaussians: GaussianModel, save: str) -> None:
33
+ os.makedirs(save, exist_ok=True)
34
+ dataset.save_cameras(os.path.join(save, "cameras.json"))
35
+ render_path = os.path.join(save, "renders")
36
+ makedirs(render_path, exist_ok=True)
37
+ pbar = tqdm(dataset, desc="Rendering progress")
38
+ for idx, camera in enumerate(pbar):
39
+ out = gaussians(camera)
40
+ rendering = out["render"]
41
+ torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + ".png"))
42
+ depth = out["depth"].squeeze(0)
43
+ tifffile.imwrite(os.path.join(render_path, '{0:05d}'.format(idx) + "_depth.tiff"), depth.cpu().numpy())
44
+
45
+
46
+ if __name__ == "__main__":
47
+ from argparse import ArgumentParser
48
+ parser = ArgumentParser()
49
+ parser.add_argument("--sh_degree", default=3, type=int)
50
+ parser.add_argument("-s", "--source", required=True, type=str)
51
+ parser.add_argument("-d", "--destination", required=True, type=str)
52
+ parser.add_argument("-i", "--iteration", required=True, type=int)
53
+ parser.add_argument("--load_camera", default=None, type=str)
54
+ parser.add_argument("--mode", choices=["base", "camera"], default="base")
55
+ parser.add_argument("--device", default="cuda", type=str)
56
+ parser.add_argument("--interp_n", required=True, type=int)
57
+ parser.add_argument("--interp_window_size", type=int, default=3)
58
+ parser.add_argument("--use_intrinsics", type=str, default="0", help="Use intrinsics for rendering, can be an integer index or a dict with keys: image_height, image_width, FoVx, FoVy")
59
+ args = parser.parse_args()
60
+ load_ply = os.path.join(args.destination, "point_cloud", "iteration_" + str(args.iteration), "point_cloud.ply")
61
+ save = os.path.join(args.destination, "ours_{}".format(args.iteration))
62
+ with torch.no_grad():
63
+ dataset, gaussians = prepare_rendering(
64
+ sh_degree=args.sh_degree, source=args.source, device=args.device,
65
+ n=args.interp_n, window_size=args.interp_window_size,
66
+ trainable_camera=args.mode == "camera",
67
+ load_ply=load_ply, load_camera=args.load_camera,
68
+ use_intrinsics=eval(args.use_intrinsics)
69
+ )
70
+ rendering(dataset, gaussians, save)
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: extrinterp
3
+ Version: 1.1.2
4
+ Summary: Just a simple camera interpolator for Gaussian Splatting framework.
5
+ Author-email: yindaheng98 <yindaheng98@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 Project VVStreams
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/yindaheng98/ExtrinsicInterpolator
29
+ Classifier: Programming Language :: Python :: 3
30
+ Requires-Python: >=3
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Requires-Dist: gaussian-splatting
34
+ Dynamic: license-file
35
+
36
+ # Extrinsic Interpolator
37
+
38
+ Just a simple camera interpolator for [Gaussian Splatting](https://github.com/yindaheng98/gaussian-splatting) framework.
39
+
40
+ ```sh
41
+ pip install --upgrade --target . --no-deps git+https://github.com/yindaheng98/gaussian-splatting.git@master
42
+ pip install --upgrade --target . --no-deps .
43
+ python -m extrinterp.render -s data/truck -d output/truck -i 30000 --load_camera output/truck/cameras.json --interp_n 300 --interp_window_size 3 --use_intrinsics dict(image_width=1600,FoVx=1.4749,image_height=1200,FoVy=1.1990)
44
+ ```
@@ -0,0 +1,10 @@
1
+ extrinterp/__init__.py,sha256=ShIep0YB1E-tWyRaUZ_IlQ1Ye1APVshEiNE9vrN49kY,200
2
+ extrinterp/abc.py,sha256=UNMEtUCjPHmRR7a0fBlL6hfy0yKLOkIY7GPkANjm82c,2161
3
+ extrinterp/dataset.py,sha256=_sJsAIB_sYEKoKBAsoYSB0KdrmuSs22VG9nDeMDbLF4,923
4
+ extrinterp/interp.py,sha256=byj6-8NnUAoJJPqCJaYFwP3PSHWdUxjjHE_A5yOQnpU,2878
5
+ extrinterp/render.py,sha256=Huw1E55AjGJi6TME-sPoM7qIgCGTzOqT2aaXjQparaQ,3628
6
+ extrinterp-1.1.2.dist-info/licenses/LICENSE,sha256=mMREImYT8k6UlMUEljpDQbd1WwJXRikZPYkknaRf-Vw,1074
7
+ extrinterp-1.1.2.dist-info/METADATA,sha256=ZKYTOjJbLhHNZUsBYWiIEGmT4WjP4f7dGhIub3YD1FM,2235
8
+ extrinterp-1.1.2.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
9
+ extrinterp-1.1.2.dist-info/top_level.txt,sha256=DIbpXDRMsq8slCQwd9C1R-lEAP2LvIy9mtOahxe-b78,11
10
+ extrinterp-1.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Project VVStreams
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ extrinterp