mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-06 07:48:50 +08:00
nerf-w and semantic-nerf initial implementations (#73)
* initial nerfw code * nerfw should be implmented correctly now * semantic nerf in progress. data loader is too slow and not clean right now * added implementation of semantic nerf * mend
This commit is contained in:
1 parent
97c9fe2541
commit
1c1a58c4e5
22 files changed
+725
-92
No files matched your search
@@ -8,10 +8,13 @@ import numpy as np
|
||||
import torch
|
||||
|
||||
from mattport.nerf.dataset.colmap_utils import read_cameras_binary, read_images_binary, read_pointsTD_binary
|
||||
from mattport.nerf.dataset.structs import DatasetInputs, PointCloud
|
||||
from mattport.nerf.dataset.structs import DatasetInputs, PointCloud, Semantics
|
||||
from mattport.utils import profiler
|
||||
from mattport.utils.io import load_from_json
|
||||
|
||||
|
||||
def load_friends_data(basedir, downscale_factor=1, split="train", include_point_cloud=False):
|
||||
@profiler.time_function
|
||||
def load_friends_data(basedir, downscale_factor=1, split="train", include_semantics=True, include_point_cloud=False):
|
||||
"""_summary_
|
||||
|
||||
Args:
|
||||
@@ -40,7 +43,6 @@ def load_friends_data(basedir, downscale_factor=1, split="train", include_point_
|
||||
intrinsics = []
|
||||
for image_path in image_paths:
|
||||
cam = cameras_data[image_path_to_image_id[image_path]]
|
||||
print(cam.params)
|
||||
assert len(cam.params) == 3
|
||||
focal_length = cam.params[0] # f (fx and fy)
|
||||
cx = cam.params[1] # cx
|
||||
@@ -63,7 +65,27 @@ def load_friends_data(basedir, downscale_factor=1, split="train", include_point_
|
||||
camera_to_world[..., 1:3] *= -1
|
||||
|
||||
# --- masks to mask out things (e.g., people) ---
|
||||
# TODO:
|
||||
|
||||
# --- semantics ---
|
||||
semantics = Semantics()
|
||||
if include_semantics:
|
||||
thing_filenames = [
|
||||
image_filename.replace("/images/", "/segmentations/thing/").replace(".jpg", ".png")
|
||||
for image_filename in image_filenames
|
||||
]
|
||||
stuff_filenames = [
|
||||
image_filename.replace("/images/", "/segmentations/stuff/").replace(".jpg", ".png")
|
||||
for image_filename in image_filenames
|
||||
]
|
||||
panoptic_classes = load_from_json(os.path.join(basedir, "panoptic_classes.json"))
|
||||
stuff_classes = panoptic_classes["stuff"]
|
||||
thing_classes = panoptic_classes["thing"]
|
||||
semantics = Semantics(
|
||||
stuff_classes=stuff_classes,
|
||||
stuff_filenames=stuff_filenames,
|
||||
thing_classes=thing_classes,
|
||||
thing_filenames=thing_filenames,
|
||||
)
|
||||
|
||||
# --- possibly transform ---
|
||||
# TODO:
|
||||
@@ -73,18 +95,20 @@ def load_friends_data(basedir, downscale_factor=1, split="train", include_point_
|
||||
|
||||
# Possibly include the sparse point cloud from COLMAP in the dataset inputs.
|
||||
# NOTE(ethan): this will be common across the different splits.
|
||||
point_cloud = None
|
||||
point_cloud = PointCloud()
|
||||
if include_point_cloud:
|
||||
points_3d = read_pointsTD_binary(os.path.join(basedir, "colmap", "points3D.bin"))
|
||||
xyz = torch.tensor(np.array([p_value.xyz for p_id, p_value in points_3d.items()]))
|
||||
rgb = torch.tensor(np.array([p_value.rgb for p_id, p_value in points_3d.items()]))
|
||||
point_cloud = PointCloud(xyz=xyz, rgb=rgb)
|
||||
point_cloud.xyz = xyz
|
||||
point_cloud.rgb = rgb
|
||||
|
||||
dataset_inputs = DatasetInputs(
|
||||
image_filenames=image_filenames,
|
||||
downscale_factor=downscale_factor,
|
||||
intrinsics=intrinsics / downscale_factor,
|
||||
camera_to_world=camera_to_world,
|
||||
semantics=semantics,
|
||||
point_cloud=point_cloud,
|
||||
)
|
||||
return dataset_inputs
|
||||
@@ -12,6 +12,8 @@ from PIL import Image
|
||||
from torch.utils.data import default_collate
|
||||
from torchtyping import TensorType
|
||||
|
||||
from mattport.nerf.dataset.structs import Semantics
|
||||
|
||||
|
||||
def collate_batch(batch_list, num_rays_per_batch, keep_full_image: bool = False):
|
||||
"""_summary_
|
||||
@@ -31,6 +33,8 @@ def collate_batch(batch_list, num_rays_per_batch, keep_full_image: bool = False)
|
||||
c, y, x = [i.flatten() for i in torch.split(indices, 1, dim=-1)]
|
||||
pixels = batch["image"][c, y, x]
|
||||
mask = batch["mask"][c, y, x]
|
||||
if "stuff_image" in batch:
|
||||
stuff_image = batch["stuff_image"][c, y, x]
|
||||
assert pixels.shape == (num_rays_per_batch, 3), pixels.shape
|
||||
|
||||
# Needed to correct the random indices to their actual camera idx locations.
|
||||
@@ -42,6 +46,10 @@ def collate_batch(batch_list, num_rays_per_batch, keep_full_image: bool = False)
|
||||
"pixels": pixels,
|
||||
"mask": mask,
|
||||
}
|
||||
|
||||
if "stuff_image" in batch:
|
||||
collated_batch["stuff_image"] = stuff_image
|
||||
|
||||
if keep_full_image:
|
||||
collated_batch["image"] = batch["image"]
|
||||
|
||||
@@ -52,7 +60,12 @@ class ImageDataset(torch.utils.data.Dataset):
|
||||
"""Dataset that returns images."""
|
||||
|
||||
def __init__(
|
||||
self, image_filenames: List[str], downscale_factor: int = 1, alpha_color: Optional[TensorType[3]] = None
|
||||
self,
|
||||
image_filenames: List[str],
|
||||
downscale_factor: int = 1,
|
||||
alpha_color: Optional[TensorType[3]] = None,
|
||||
semantics: Semantics = Semantics(),
|
||||
**kwargs,
|
||||
):
|
||||
"""_summary_
|
||||
|
||||
@@ -66,6 +79,8 @@ class ImageDataset(torch.utils.data.Dataset):
|
||||
self.image_filenames = image_filenames
|
||||
self.downscale_factor = downscale_factor
|
||||
self.alpha_color = alpha_color
|
||||
self.semantics = semantics
|
||||
self.kwargs = kwargs
|
||||
|
||||
def __len__(self):
|
||||
return len(self.image_filenames)
|
||||
@@ -123,4 +138,24 @@ class ImageDataset(torch.utils.data.Dataset):
|
||||
"image": image, # the pixels
|
||||
"mask": mask,
|
||||
}
|
||||
|
||||
if self.semantics.stuff_filenames:
|
||||
stuff_image_filename = self.semantics.stuff_filenames[image_idx]
|
||||
pil_image = Image.open(stuff_image_filename)
|
||||
if self.downscale_factor != 1.0:
|
||||
image_width, image_height = pil_image.size
|
||||
if image_width % self.downscale_factor != 0:
|
||||
raise ValueError(
|
||||
f"Image width {image_width} is not divisible by downscale_factor {self.downscale_factor}"
|
||||
)
|
||||
if image_height % self.downscale_factor != 0:
|
||||
raise ValueError(
|
||||
f"Image height {image_height} is not divisible by downscale_factor {self.downscale_factor}"
|
||||
)
|
||||
# NOTE(ethan): the use of NEAREST is important for semantic classes
|
||||
pil_image = pil_image.resize(
|
||||
(image_width // self.downscale_factor, image_height // self.downscale_factor), PIL.Image.NEAREST
|
||||
)
|
||||
stuff_image = torch.from_numpy(np.array(pil_image, dtype="int32"))[..., None]
|
||||
data["stuff_image"] = stuff_image
|
||||
return data
|
||||
@@ -13,8 +13,18 @@ from torchtyping import TensorType
|
||||
class PointCloud:
|
||||
"""_summary_"""
|
||||
|
||||
xyz: None
|
||||
rgb: None
|
||||
xyz = None
|
||||
rgb = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Semantics:
|
||||
"""_summary_"""
|
||||
|
||||
stuff_classes: List[str] = None
|
||||
stuff_filenames: List[str] = None
|
||||
thing_classes: List[str] = None
|
||||
thing_filenames: List[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -31,12 +41,21 @@ class DatasetInputs:
|
||||
intrinsics: torch.tensor = None
|
||||
camera_to_world: torch.tensor = None
|
||||
bounding_box: torch.tensor = None
|
||||
mask_filenames: List[str] = None
|
||||
depth_filenames: List[str] = None
|
||||
semantic_filenames: List[str] = None
|
||||
point_cloud: PointCloud = None # TODO(ethan): specify the type here
|
||||
semantics: Semantics = Semantics()
|
||||
point_cloud: PointCloud = PointCloud()
|
||||
alpha_color: Optional[TensorType[3]] = None
|
||||
|
||||
def check_inputs(self):
|
||||
"""Check the inputs to make sure everything is okay."""
|
||||
assert self.intrinsics.dtype == torch.float32
|
||||
assert self.camera_to_world.dtype == torch.float32
|
||||
|
||||
def save_to_folder_name(self, data_directory: str):
|
||||
"""Save the dataset inputs."""
|
||||
raise NotImplementedError
|
||||
|
||||
def load_from_folder_name(self, data_directory: str):
|
||||
"""Load the saved dataset inputs."""
|
||||
raise NotImplementedError
|
||||
@@ -19,6 +19,7 @@ def get_dataset_inputs_dict(
|
||||
downscale_factor: int = 1,
|
||||
alpha_color: Optional[Union[str, list, ListConfig]] = None,
|
||||
splits: Tuple[str] = ("train", "val"),
|
||||
load_dataset_inputs_from_cache: bool = False,
|
||||
) -> Dict[str, DatasetInputs]:
|
||||
"""Returns the dataset inputs, which will be used with an ImageDataset and RayGenerator.
|
||||
# TODO: implement the `test` split, which will have depths and normals, etc.
|
||||
@@ -28,12 +29,16 @@ def get_dataset_inputs_dict(
|
||||
dataset_type (str): Name of dataset type
|
||||
downscale_factor (int, optional): How much to downscale images. Defaults to 1.0.
|
||||
alpha_color (str, list, optional): Sets transparent regions to specified color, otherwise black.
|
||||
|
||||
load_from_cache (bool)
|
||||
Returns:
|
||||
Dict[str, DatasetInputs]: The inputs needed for generating rays.
|
||||
"""
|
||||
dataset_inputs_dict = {}
|
||||
|
||||
if load_dataset_inputs_from_cache:
|
||||
print("Loading from cache.")
|
||||
return None
|
||||
|
||||
if alpha_color is not None:
|
||||
alpha_color = get_color(alpha_color)
|
||||
|
||||
@@ -47,12 +52,23 @@ def get_dataset_inputs_dict(
|
||||
)
|
||||
dataset_inputs_dict[split] = dataset_inputs
|
||||
elif dataset_type == "friends":
|
||||
# TODO(ethan): change this hack, and do proper splits for the friends dataset
|
||||
# currently we assume that there is only the training set of images
|
||||
dataset_inputs = load_friends_data(
|
||||
get_absolute_path(data_directory),
|
||||
downscale_factor=downscale_factor,
|
||||
split="train",
|
||||
include_point_cloud=False,
|
||||
)
|
||||
for split in splits:
|
||||
dataset_inputs = load_friends_data(
|
||||
get_absolute_path(data_directory), downscale_factor=downscale_factor, split=split
|
||||
)
|
||||
dataset_inputs_dict[split] = dataset_inputs
|
||||
else:
|
||||
raise NotImplementedError(f"{dataset_type} is not a valid dataset type")
|
||||
|
||||
for split in splits:
|
||||
# save the dataset inputs to cache
|
||||
# TODO:
|
||||
# dataset_inputs_dict[splits].save_to_folder_name()
|
||||
pass
|
||||
|
||||
return dataset_inputs_dict
|
||||
Reference in new issue
Block a user