{"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:convert","uri":"program://EfficientDynamic3DGaussian/module/convert#L1-L124","kind":"module","name":"convert","path":"convert.py","language":"python","start_line":1,"end_line":124,"context_start_line":1,"context_end_line":124,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use\n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nimport logging\nfrom argparse import ArgumentParser\nimport shutil\n\n# This Python script is based on the shell converter script provided in the MipNerF 360 repository.\nparser = ArgumentParser(\"Colmap converter\")\nparser.add_argument(\"--no_gpu\", action='store_true')\nparser.add_argument(\"--skip_matching\", action='store_true')\nparser.add_argument(\"--source_path\", \"-s\", required=True, type=str)\nparser.add_argument(\"--camera\", default=\"OPENCV\", type=str)\nparser.add_argument(\"--colmap_executable\", default=\"\", type=str)\nparser.add_argument(\"--resize\", action=\"store_true\")\nparser.add_argument(\"--magick_executable\", default=\"\", type=str)\nargs = parser.parse_args()\ncolmap_command = '\"{}\"'.format(args.colmap_executable) if len(args.colmap_executable) > 0 else \"colmap\"\nmagick_command = '\"{}\"'.format(args.magick_executable) if len(args.magick_executable) > 0 else \"magick\"\nuse_gpu = 1 if not args.no_gpu else 0\n\nif not args.skip_matching:\n os.makedirs(args.source_path + \"/distorted/sparse\", exist_ok=True)\n\n ## Feature extraction\n feat_extracton_cmd = colmap_command + \" feature_extractor \"\\\n \"--database_path \" + args.source_path + \"/distorted/database.db \\\n --image_path \" + args.source_path + \"/input \\\n --ImageReader.single_camera 1 \\\n --ImageReader.camera_model \" + args.camera + \" \\\n --SiftExtraction.use_gpu \" + str(use_gpu)\n exit_code = os.system(feat_extracton_cmd)\n if exit_code != 0:\n logging.error(f\"Feature extraction failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\n ## Feature matching\n feat_matching_cmd = colmap_command + \" exhaustive_matcher \\\n --database_path \" + args.source_path + \"/distorted/database.db \\\n --SiftMatching.use_gpu \" + str(use_gpu)\n exit_code = os.system(feat_matching_cmd)\n if exit_code != 0:\n logging.error(f\"Feature matching failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\n ### Bundle adjustment\n # The default Mapper tolerance is unnecessarily large,\n # decreasing it speeds up bundle adjustment steps.\n mapper_cmd = (colmap_command + \" mapper \\\n --database_path \" + args.source_path + \"/distorted/database.db \\\n --image_path \" + args.source_path + \"/input \\\n --output_path \" + args.source_path + \"/distorted/sparse \\\n --Mapper.ba_global_function_tolerance=0.000001\")\n exit_code = os.system(mapper_cmd)\n if exit_code != 0:\n logging.error(f\"Mapper failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\n### Image undistortion\n## We need to undistort our images into ideal pinhole intrinsics.\nimg_undist_cmd = (colmap_command + \" image_undistorter \\\n --image_path \" + args.source_path + \"/input \\\n --input_path \" + args.source_path + \"/distorted/sparse/0 \\\n --output_path \" + args.source_path + \"\\\n --output_type COLMAP\")\nexit_code = os.system(img_undist_cmd)\nif exit_code != 0:\n logging.error(f\"Mapper failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\nfiles = os.listdir(args.source_path + \"/sparse\")\nos.makedirs(args.source_path + \"/sparse/0\", exist_ok=True)\n# Copy each file from the source directory to the destination directory\nfor file in files:\n if file == '0':\n continue\n source_file = os.path.join(args.source_path, \"sparse\", file)\n destination_file = os.path.join(args.source_path, \"sparse\", \"0\", file)\n shutil.move(source_file, destination_file)\n\nif(args.resize):\n print(\"Copying and resizing...\")\n\n # Resize images.\n os.makedirs(args.source_path + \"/images_2\", exist_ok=True)\n os.makedirs(args.source_path + \"/images_4\", exist_ok=True)\n os.makedirs(args.source_path + \"/images_8\", exist_ok=True)\n # Get the list of files in the source directory\n files = os.listdir(args.source_path + \"/images\")\n # Copy each file from the source directory to the destination directory\n for file in files:\n source_file = os.path.join(args.source_path, \"images\", file)\n\n destination_file = os.path.join(args.source_path, \"images_2\", file)\n shutil.copy2(source_file, destination_file)\n exit_code = os.system(magick_command + \" mogrify -resize 50% \" + destination_file)\n if exit_code != 0:\n logging.error(f\"50% resize failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\n destination_file = os.path.join(args.source_path, \"images_4\", file)\n shutil.copy2(source_file, destination_file)\n exit_code = os.system(magick_command + \" mogrify -resize 25% \" + destination_file)\n if exit_code != 0:\n logging.error(f\"25% resize failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\n destination_file = os.path.join(args.source_path, \"images_8\", file)\n shutil.copy2(source_file, destination_file)\n exit_code = os.system(magick_command + \" mogrify -resize 12.5% \" + destination_file)\n if exit_code != 0:\n logging.error(f\"12.5% resize failed with code {exit_code}. Exiting.\")\n exit(exit_code)\n\nprint(\"Done.\")","source_hash":"e534a5f64425412dc7a1ae4360f8caf3421167984bbaca307916d8a40ba16b64","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:process_dynerf_dataset","uri":"program://EfficientDynamic3DGaussian/module/process_dynerf_dataset#L1-L233","kind":"module","name":"process_dynerf_dataset","path":"process_dynerf_dataset.py","language":"python","start_line":1,"end_line":233,"context_start_line":1,"context_end_line":233,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.\n \"\"\"\n video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break\n video_frames.release()\n print(f\"Video {video_path} processed.\")\n return None\n\n\n# define a function to process all videos\ndef process_videos(videos, skip_index, img_wh, downsample, transform, num_workers=1):\n \"\"\"\n A multi-threaded function to load all videos fastly and memory-efficiently.\n To save memory, we pre-allocate a tensor to store all the images and spawn multi-threads to load the images into this tensor.\n \"\"\"\n all_imgs = torch.zeros(len(videos) - 1, 300, img_wh[-1] * img_wh[-2], 3)\n with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:\n # start a thread for each video\n current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):\n self.img_wh = (\n int(1024 / downsample),\n int(768 / downsample),\n ) # According to the neural 3D paper, the default resolution is 1024x768\n self.root_dir = datadir\n self.split = split\n self.downsample = 2704 / self.img_wh[0]\n self.is_stack = is_stack\n self.N_vis = N_vis\n self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.\n\n near_original = self.near_fars.min()\n scale_factor = near_original * 0.75\n self.near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n poses[..., 3] /= scale_factor\n\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n self.val_poses = get_spiral(poses, self.near_fars, N_views=N_views)\n\n W, H = self.img_wh\n self.directions = torch.tensor(\n get_ray_directions_blender(H, W, self.focal)\n ) # (H, W, 3)\n\n if self.split == \"train\":\n # Loading all videos from this dataset requires around 50GB memory, and stack them into a tensor requires another 50GB.\n # To save memory, we allocate a large tensor and load videos into it instead of using torch.stack/cat operations.\n all_times = []\n all_rays = []\n count = 300\n\n for index in range(0, len(videos)):\n if (\n index == self.eval_index\n ): # the eval_index(0 as default) is the evaluation one. We skip evaluation cameras.\n continue\n\n video_times = torch.tensor([i / (count - 1) for i in range(count)])\n all_times += [video_times]\n\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays += [torch.cat([rays_o, rays_d], 1)]\n print(f\"video {index} is loaded\")\n gc.collect()\n\n # load all video images\n all_imgs = process_videos(\n videos,\n self.eval_index,\n self.img_wh,\n self.downsample,\n self.transform,\n num_workers=8,\n )\n all_times = torch.stack(all_times, 0)\n all_rays = torch.stack(all_rays, 0)\n breakpoint()\n print(\"stack performed\")\n N_cam, N_time, N_rays, C = all_imgs.shape\n self.image_stride = N_rays\n self.cam_number = N_cam\n self.time_number = N_time\n self.all_rgbs = all_imgs\n self.all_times = all_times.view(N_cam, N_time, 1)\n self.all_rays = all_rays.reshape(N_cam, N_rays, 6)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n self.global_mean_rgb = torch.mean(all_imgs, dim=1)\n else:\n index = self.eval_index\n video_imgs = []\n video_frames = cv2.VideoCapture(videos[index])\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if self.downsample != 1.0:\n img = video_frame.resize(self.img_wh, Image.LANCZOS)\n img = self.transform(img)\n video_imgs += [img.view(3, -1).permute(1, 0)]\n else:\n break\n video_imgs = torch.stack(video_imgs, 0)\n video_times = torch.tensor(\n [i / (len(video_imgs) - 1) for i in range(len(video_imgs))]\n )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:process_dynerf_dataset.process_video","uri":"program://EfficientDynamic3DGaussian/function/process_dynerf_dataset.process_video#L13-L33","kind":"function","name":"process_video","path":"process_dynerf_dataset.py","language":"python","start_line":13,"end_line":33,"context_start_line":1,"context_end_line":53,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.\n \"\"\"\n video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break\n video_frames.release()\n print(f\"Video {video_path} processed.\")\n return None\n\n\n# define a function to process all videos\ndef process_videos(videos, skip_index, img_wh, downsample, transform, num_workers=1):\n \"\"\"\n A multi-threaded function to load all videos fastly and memory-efficiently.\n To save memory, we pre-allocate a tensor to store all the images and spawn multi-threads to load the images into this tensor.\n \"\"\"\n all_imgs = torch.zeros(len(videos) - 1, 300, img_wh[-1] * img_wh[-2], 3)\n with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:\n # start a thread for each video\n current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:process_dynerf_dataset.process_videos","uri":"program://EfficientDynamic3DGaussian/function/process_dynerf_dataset.process_videos#L37-L62","kind":"function","name":"process_videos","path":"process_dynerf_dataset.py","language":"python","start_line":37,"end_line":62,"context_start_line":17,"context_end_line":82,"code":" video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break\n video_frames.release()\n print(f\"Video {video_path} processed.\")\n return None\n\n\n# define a function to process all videos\ndef process_videos(videos, skip_index, img_wh, downsample, transform, num_workers=1):\n \"\"\"\n A multi-threaded function to load all videos fastly and memory-efficiently.\n To save memory, we pre-allocate a tensor to store all the images and spawn multi-threads to load the images into this tensor.\n \"\"\"\n all_imgs = torch.zeros(len(videos) - 1, 300, img_wh[-1] * img_wh[-2], 3)\n with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:\n # start a thread for each video\n current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:process_dynerf_dataset.Neural3D_NDC_Dataset","uri":"program://EfficientDynamic3DGaussian/class/process_dynerf_dataset.Neural3D_NDC_Dataset#L67-L232","kind":"class","name":"Neural3D_NDC_Dataset","path":"process_dynerf_dataset.py","language":"python","start_line":67,"end_line":232,"context_start_line":47,"context_end_line":233,"code":" for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):\n self.img_wh = (\n int(1024 / downsample),\n int(768 / downsample),\n ) # According to the neural 3D paper, the default resolution is 1024x768\n self.root_dir = datadir\n self.split = split\n self.downsample = 2704 / self.img_wh[0]\n self.is_stack = is_stack\n self.N_vis = N_vis\n self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.\n\n near_original = self.near_fars.min()\n scale_factor = near_original * 0.75\n self.near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n poses[..., 3] /= scale_factor\n\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n self.val_poses = get_spiral(poses, self.near_fars, N_views=N_views)\n\n W, H = self.img_wh\n self.directions = torch.tensor(\n get_ray_directions_blender(H, W, self.focal)\n ) # (H, W, 3)\n\n if self.split == \"train\":\n # Loading all videos from this dataset requires around 50GB memory, and stack them into a tensor requires another 50GB.\n # To save memory, we allocate a large tensor and load videos into it instead of using torch.stack/cat operations.\n all_times = []\n all_rays = []\n count = 300\n\n for index in range(0, len(videos)):\n if (\n index == self.eval_index\n ): # the eval_index(0 as default) is the evaluation one. We skip evaluation cameras.\n continue\n\n video_times = torch.tensor([i / (count - 1) for i in range(count)])\n all_times += [video_times]\n\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays += [torch.cat([rays_o, rays_d], 1)]\n print(f\"video {index} is loaded\")\n gc.collect()\n\n # load all video images\n all_imgs = process_videos(\n videos,\n self.eval_index,\n self.img_wh,\n self.downsample,\n self.transform,\n num_workers=8,\n )\n all_times = torch.stack(all_times, 0)\n all_rays = torch.stack(all_rays, 0)\n breakpoint()\n print(\"stack performed\")\n N_cam, N_time, N_rays, C = all_imgs.shape\n self.image_stride = N_rays\n self.cam_number = N_cam\n self.time_number = N_time\n self.all_rgbs = all_imgs\n self.all_times = all_times.view(N_cam, N_time, 1)\n self.all_rays = all_rays.reshape(N_cam, N_rays, 6)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n self.global_mean_rgb = torch.mean(all_imgs, dim=1)\n else:\n index = self.eval_index\n video_imgs = []\n video_frames = cv2.VideoCapture(videos[index])\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if self.downsample != 1.0:\n img = video_frame.resize(self.img_wh, Image.LANCZOS)\n img = self.transform(img)\n video_imgs += [img.view(3, -1).permute(1, 0)]\n else:\n break\n video_imgs = torch.stack(video_imgs, 0)\n video_times = torch.tensor(\n [i / (len(video_imgs) - 1) for i in range(len(video_imgs))]\n )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:process_dynerf_dataset.__init__","uri":"program://EfficientDynamic3DGaussian/function/process_dynerf_dataset.__init__#L68-L112","kind":"function","name":"__init__","path":"process_dynerf_dataset.py","language":"python","start_line":68,"end_line":112,"context_start_line":48,"context_end_line":132,"code":" # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):\n self.img_wh = (\n int(1024 / downsample),\n int(768 / downsample),\n ) # According to the neural 3D paper, the default resolution is 1024x768\n self.root_dir = datadir\n self.split = split\n self.downsample = 2704 / self.img_wh[0]\n self.is_stack = is_stack\n self.N_vis = N_vis\n self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:process_dynerf_dataset.load_meta","uri":"program://EfficientDynamic3DGaussian/function/process_dynerf_dataset.load_meta#L114-L232","kind":"function","name":"load_meta","path":"process_dynerf_dataset.py","language":"python","start_line":114,"end_line":232,"context_start_line":94,"context_end_line":233,"code":" self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.\n\n near_original = self.near_fars.min()\n scale_factor = near_original * 0.75\n self.near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n poses[..., 3] /= scale_factor\n\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n self.val_poses = get_spiral(poses, self.near_fars, N_views=N_views)\n\n W, H = self.img_wh\n self.directions = torch.tensor(\n get_ray_directions_blender(H, W, self.focal)\n ) # (H, W, 3)\n\n if self.split == \"train\":\n # Loading all videos from this dataset requires around 50GB memory, and stack them into a tensor requires another 50GB.\n # To save memory, we allocate a large tensor and load videos into it instead of using torch.stack/cat operations.\n all_times = []\n all_rays = []\n count = 300\n\n for index in range(0, len(videos)):\n if (\n index == self.eval_index\n ): # the eval_index(0 as default) is the evaluation one. We skip evaluation cameras.\n continue\n\n video_times = torch.tensor([i / (count - 1) for i in range(count)])\n all_times += [video_times]\n\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays += [torch.cat([rays_o, rays_d], 1)]\n print(f\"video {index} is loaded\")\n gc.collect()\n\n # load all video images\n all_imgs = process_videos(\n videos,\n self.eval_index,\n self.img_wh,\n self.downsample,\n self.transform,\n num_workers=8,\n )\n all_times = torch.stack(all_times, 0)\n all_rays = torch.stack(all_rays, 0)\n breakpoint()\n print(\"stack performed\")\n N_cam, N_time, N_rays, C = all_imgs.shape\n self.image_stride = N_rays\n self.cam_number = N_cam\n self.time_number = N_time\n self.all_rgbs = all_imgs\n self.all_times = all_times.view(N_cam, N_time, 1)\n self.all_rays = all_rays.reshape(N_cam, N_rays, 6)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n self.global_mean_rgb = torch.mean(all_imgs, dim=1)\n else:\n index = self.eval_index\n video_imgs = []\n video_frames = cv2.VideoCapture(videos[index])\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if self.downsample != 1.0:\n img = video_frame.resize(self.img_wh, Image.LANCZOS)\n img = self.transform(img)\n video_imgs += [img.view(3, -1).permute(1, 0)]\n else:\n break\n video_imgs = torch.stack(video_imgs, 0)\n video_times = torch.tensor(\n [i / (len(video_imgs) - 1) for i in range(len(video_imgs))]\n )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:full_eval","uri":"program://EfficientDynamic3DGaussian/module/full_eval#L1-L75","kind":"module","name":"full_eval","path":"full_eval.py","language":"python","start_line":1,"end_line":75,"context_start_line":1,"context_end_line":75,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nfrom argparse import ArgumentParser\n\nmipnerf360_outdoor_scenes = [\"bicycle\", \"flowers\", \"garden\", \"stump\", \"treehill\"]\nmipnerf360_indoor_scenes = [\"room\", \"counter\", \"kitchen\", \"bonsai\"]\ntanks_and_temples_scenes = [\"truck\", \"train\"]\ndeep_blending_scenes = [\"drjohnson\", \"playroom\"]\n\nparser = ArgumentParser(description=\"Full evaluation script parameters\")\nparser.add_argument(\"--skip_training\", action=\"store_true\")\nparser.add_argument(\"--skip_rendering\", action=\"store_true\")\nparser.add_argument(\"--skip_metrics\", action=\"store_true\")\nparser.add_argument(\"--output_path\", default=\"./eval\")\nargs, _ = parser.parse_known_args()\n\nall_scenes = []\nall_scenes.extend(mipnerf360_outdoor_scenes)\nall_scenes.extend(mipnerf360_indoor_scenes)\nall_scenes.extend(tanks_and_temples_scenes)\nall_scenes.extend(deep_blending_scenes)\n\nif not args.skip_training or not args.skip_rendering:\n parser.add_argument('--mipnerf360', \"-m360\", required=True, type=str)\n parser.add_argument(\"--tanksandtemples\", \"-tat\", required=True, type=str)\n parser.add_argument(\"--deepblending\", \"-db\", required=True, type=str)\n args = parser.parse_args()\n\nif not args.skip_training:\n common_args = \" --quiet --eval --test_iterations -1 \"\n for scene in mipnerf360_outdoor_scenes:\n source = args.mipnerf360 + \"/\" + scene\n os.system(\"python train.py -s \" + source + \" -i images_4 -m \" + args.output_path + \"/\" + scene + common_args)\n for scene in mipnerf360_indoor_scenes:\n source = args.mipnerf360 + \"/\" + scene\n os.system(\"python train.py -s \" + source + \" -i images_2 -m \" + args.output_path + \"/\" + scene + common_args)\n for scene in tanks_and_temples_scenes:\n source = args.tanksandtemples + \"/\" + scene\n os.system(\"python train.py -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n for scene in deep_blending_scenes:\n source = args.deepblending + \"/\" + scene\n os.system(\"python train.py -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n\nif not args.skip_rendering:\n all_sources = []\n for scene in mipnerf360_outdoor_scenes:\n all_sources.append(args.mipnerf360 + \"/\" + scene)\n for scene in mipnerf360_indoor_scenes:\n all_sources.append(args.mipnerf360 + \"/\" + scene)\n for scene in tanks_and_temples_scenes:\n all_sources.append(args.tanksandtemples + \"/\" + scene)\n for scene in deep_blending_scenes:\n all_sources.append(args.deepblending + \"/\" + scene)\n\n common_args = \" --quiet --eval --skip_train\"\n for scene, source in zip(all_scenes, all_sources):\n os.system(\"python render.py --iteration 7000 -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n os.system(\"python render.py --iteration 30000 -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n\nif not args.skip_metrics:\n scenes_string = \"\"\n for scene in all_scenes:\n scenes_string += \"\\\"\" + args.output_path + \"/\" + scene + \"\\\" \"\n\n os.system(\"python metrics.py -m \" + scenes_string)","source_hash":"f28cca2b796b1fc5f99d63e2bd39133b1a678b607fcc55cd9051655f6540b476","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render","uri":"program://EfficientDynamic3DGaussian/module/render#L1-L76","kind":"module","name":"render","path":"render.py","language":"python","start_line":1,"end_line":76,"context_start_line":1,"context_end_line":76,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\n\ndef render_set(model_path, name, iteration, views, gaussians, pipeline, background):\n render_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"renders\")\n gts_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"gt\")\n\n makedirs(render_path, exist_ok=True)\n makedirs(gts_path, exist_ok=True)\n\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n # if idx % 30:\n # continue\n if type(view) is list:\n view = view[0]\n rendering = render(view, gaussians, pipeline, background)[\"render\"]\n gt = view.original_image[0:3, :, :]\n torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n if not skip_train:\n if scene.use_loader:\n views = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=False, num_workers=16, collate_fn=list)\n else:\n views = scene.getTrainCameras()\n\n render_set(dataset.model_path, \"train\", scene.loaded_iter, views, gaussians, pipeline, background)\n\n if not skip_test:\n render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background)\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Testing script parameters\")\n model = ModelParams(parser, sentinel=True)\n pipeline = PipelineParams(parser)\n parser.add_argument(\"--iteration\", default=-1, type=int)\n parser.add_argument(\"--skip_train\", action=\"store_true\")\n parser.add_argument(\"--skip_test\", action=\"store_true\")\n parser.add_argument(\"--quiet\", action=\"store_true\")\n args = get_combined_args(parser)\n print(\"Rendering \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)","source_hash":"77e983c44996fc119ba91d558bb3ff46d7f01aff278e417785dd00b67345a817","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render.render_set","uri":"program://EfficientDynamic3DGaussian/function/render.render_set#L25-L40","kind":"function","name":"render_set","path":"render.py","language":"python","start_line":25,"end_line":40,"context_start_line":5,"context_end_line":60,"code":"#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\n\ndef render_set(model_path, name, iteration, views, gaussians, pipeline, background):\n render_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"renders\")\n gts_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"gt\")\n\n makedirs(render_path, exist_ok=True)\n makedirs(gts_path, exist_ok=True)\n\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n # if idx % 30:\n # continue\n if type(view) is list:\n view = view[0]\n rendering = render(view, gaussians, pipeline, background)[\"render\"]\n gt = view.original_image[0:3, :, :]\n torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n if not skip_train:\n if scene.use_loader:\n views = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=False, num_workers=16, collate_fn=list)\n else:\n views = scene.getTrainCameras()\n\n render_set(dataset.model_path, \"train\", scene.loaded_iter, views, gaussians, pipeline, background)\n\n if not skip_test:\n render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background)\n","source_hash":"77e983c44996fc119ba91d558bb3ff46d7f01aff278e417785dd00b67345a817","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render.render_sets","uri":"program://EfficientDynamic3DGaussian/function/render.render_sets#L42-L59","kind":"function","name":"render_sets","path":"render.py","language":"python","start_line":42,"end_line":59,"context_start_line":22,"context_end_line":76,"code":"from arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\n\ndef render_set(model_path, name, iteration, views, gaussians, pipeline, background):\n render_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"renders\")\n gts_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"gt\")\n\n makedirs(render_path, exist_ok=True)\n makedirs(gts_path, exist_ok=True)\n\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n # if idx % 30:\n # continue\n if type(view) is list:\n view = view[0]\n rendering = render(view, gaussians, pipeline, background)[\"render\"]\n gt = view.original_image[0:3, :, :]\n torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n if not skip_train:\n if scene.use_loader:\n views = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=False, num_workers=16, collate_fn=list)\n else:\n views = scene.getTrainCameras()\n\n render_set(dataset.model_path, \"train\", scene.loaded_iter, views, gaussians, pipeline, background)\n\n if not skip_test:\n render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background)\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Testing script parameters\")\n model = ModelParams(parser, sentinel=True)\n pipeline = PipelineParams(parser)\n parser.add_argument(\"--iteration\", default=-1, type=int)\n parser.add_argument(\"--skip_train\", action=\"store_true\")\n parser.add_argument(\"--skip_test\", action=\"store_true\")\n parser.add_argument(\"--quiet\", action=\"store_true\")\n args = get_combined_args(parser)\n print(\"Rendering \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)","source_hash":"77e983c44996fc119ba91d558bb3ff46d7f01aff278e417785dd00b67345a817","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:train","uri":"program://EfficientDynamic3DGaussian/module/train#L1-L277","kind":"module","name":"train","path":"train.py","language":"python","start_line":1,"end_line":277,"context_start_line":1,"context_end_line":277,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nimport torch\nfrom torch.utils.data import DataLoader\nfrom random import randint\nfrom utils.loss_utils import l1_loss, ssim\nfrom gaussian_renderer import render, render_flow, network_gui\nimport sys\nfrom scene import Scene, GaussianModel\nfrom utils.general_utils import safe_state\nimport uuid\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser, Namespace\nfrom arguments import ModelParams, PipelineParams, OptimizationParams\nimport copy\ntry:\n from torch.utils.tensorboard import SummaryWriter\n TENSORBOARD_FOUND = True\nexcept ImportError:\n TENSORBOARD_FOUND = False\n\nfrom PIL import Image\nimport numpy as np\n\ndef training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from):\n first_iter = 0\n tb_writer = prepare_output_and_logger(dataset)\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians)\n gaussians.training_setup(opt)\n if checkpoint:\n (model_params, first_iter) = torch.load(checkpoint)\n gaussians.restore(model_params, opt)\n\n\n bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n white_color = [1, 1, 1]\n white_background = torch.tensor(white_color, dtype=torch.float32, device=\"cuda\")\n\n iter_start = torch.cuda.Event(enable_timing = True)\n iter_end = torch.cuda.Event(enable_timing = True)\n\n viewpoint_stack = None\n ema_loss_for_log = 0.0\n ema_flow_loss_for_log = 0.0\n progress_bar = tqdm(range(first_iter, opt.iterations), desc=\"Training progress\")\n first_iter += 1\n if scene.use_loader:\n cam_loader = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=True, num_workers=16, collate_fn=list)\n loader = iter(cam_loader)\n\n # mask = torch.tensor((np.array(Image.open('mask.png'))[:, :, 3] > 0)).cuda()\n\n for iteration in range(first_iter, opt.iterations + 1): \n if network_gui.conn == None:\n network_gui.try_connect()\n while network_gui.conn != None:\n try:\n net_image_bytes = None\n custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive()\n if custom_cam != None:\n net_image = render(custom_cam, gaussians, pipe, background, scaling_modifer)[\"render\"]\n net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy())\n network_gui.send(net_image_bytes, dataset.source_path)\n if do_training and ((iteration < int(opt.iterations)) or not keep_alive):\n break\n except Exception as e:\n network_gui.conn = None\n\n iter_start.record()\n\n gaussians.update_learning_rate(iteration)\n\n # Every 1000 its we increase the levels of SH up to a maximum degree\n if iteration % 1000 == 0:\n gaussians.oneupSHdegree()\n\n\n if scene.use_loader:\n try:\n viewpoint_cam = next(loader)[0]\n except:\n loader = iter(cam_loader)\n viewpoint_cam = next(loader)[0]\n else:\n # Pick a random Camera\n if not viewpoint_stack:\n viewpoint_stack = scene.getTrainCameras().copy()\n viewpoint_cam = viewpoint_stack.pop(randint(0, len(viewpoint_stack)-1))\n\n # Render\n if (iteration - 1) == debug_from:\n pipe.debug = True\n\n\n render_pkg = render(viewpoint_cam, gaussians, pipe, background, itr=iteration)\n image, viewspace_point_tensor, visibility_filter, radii = render_pkg[\"render\"], render_pkg[\"viewspace_points\"], render_pkg[\"visibility_filter\"], render_pkg[\"radii\"]\n # Loss\n gt_image = viewpoint_cam.original_image.cuda()\n\n # if iteration % 200 == 0:\n # print(image.mean().item(), image.max().item(), image.min().item(), gt_image.mean().item(), gt_image.max().item(), gt_image.min().item())\n Ll1 = l1_loss(image, gt_image)\n # Ll1 = (torch.abs((image - gt_image))*mask).mean()\n lasso_loss = torch.nanmean(torch.abs(gaussians.get_xyz[:, 1:, :])) # + torch.nanmean(torch.abs(gaussians.get_rotation[:, 1:, :]))\n # print(lasso_loss, gaussians.get_rotation[:, 1:, :].abs().mean())\n flow_loss = 0\n if iteration >= 3000 and viewpoint_cam.kwargs['fwd_flow'] is not None:\n fwd_flow = viewpoint_cam.kwargs['fwd_flow'].cuda().permute(2, 0, 1)\n fwd_flow_mask = viewpoint_cam.kwargs['fwd_flow_mask'].cuda()\n render_flow_fwd = render_flow(viewpoint_cam, gaussians, pipe, white_background, itr=iteration, time_delta=scene.time_delta)['render'][:2, ...]\n fwd_flow = fwd_flow / (torch.max(torch.sqrt(torch.square(fwd_flow).sum(-1))) + 1e-5)\n render_flow_fwd = render_flow_fwd / (torch.max(torch.sqrt(torch.square(render_flow_fwd).sum(-1))) + 1e-5)\n M = fwd_flow_mask.unsqueeze(0)\n fwd_flow_loss = torch.sum(torch.abs(fwd_flow - render_flow_fwd) * M) / (torch.sum(M) + 1e-8) / fwd_flow.shape[-1]\n # fwd_flow_loss = torch.mean(torch.abs(fwd_flow - render_flow_fwd))\n flow_loss += fwd_flow_loss\n\n if iteration >= 3000 and viewpoint_cam.kwargs['bwd_flow'] is not None:\n bwd_flow = viewpoint_cam.kwargs['bwd_flow'].permute(2, 0, 1).cuda()\n bwd_flow_mask = viewpoint_cam.kwargs['bwd_flow_mask'].cuda()\n render_flow_bwd = render_flow(viewpoint_cam, gaussians, pipe, white_background, itr=iteration, time_delta=-scene.time_delta)['render'][:2, ...]\n bwd_flow = bwd_flow / (torch.max(torch.sqrt(torch.square(bwd_flow).sum(-1))) + 1e-5)\n render_flow_bwd = render_flow_bwd / (torch.max(torch.sqrt(torch.square(render_flow_bwd).sum(-1))) + 1e-5)\n M = bwd_flow_mask.unsqueeze(0)\n bwd_flow_loss = torch.sum(torch.abs(bwd_flow - render_flow_bwd) * M) / (torch.sum(M) + 1e-8) / bwd_flow.shape[-1]\n flow_loss += bwd_flow_loss\n\n loss = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim(image, gt_image)) + opt.lambda_lasso * lasso_loss\n loss += opt.lambda_flow * flow_loss\n # if type(loss) is int:\n # continue\n loss.backward()\n # print(gaussians._xyz[:, 0, 0].grad.shape)\n # print(gaussians.optimizer.param_groups[0]['params'][0].data.abs().mean(0)[1:5].flatten())\n iter_end.record()\n\n with torch.no_grad():\n # Progress bar\n ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log\n fl = flow_loss.item() if hasattr(flow_loss, 'item') else flow_loss\n ema_flow_loss_for_log = 0.4 * fl + 0.6 * ema_flow_loss_for_log\n if iteration % 10 == 0:\n progress_bar.set_postfix({\"Loss\": f\"{ema_loss_for_log:.{7}f}\", \"Flow loss\": f\"{ema_flow_loss_for_log:.{7}f}\"})\n progress_bar.update(10)\n if iteration == opt.iterations:\n progress_bar.close()\n\n # Log and save\n training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background))\n if (iteration in saving_iterations):\n print(\"\\n[ITER {}] Saving Gaussians\".format(iteration))\n scene.save(iteration)\n\n # Densification\n if iteration < opt.densify_until_iter:\n # Keep track of max radii in image-space for pruning\n gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter])\n gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)\n\n if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:\n size_threshold = 20 if iteration > opt.opacity_reset_interval else None\n gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold)\n \n if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter):\n gaussians.reset_opacity()\n\n # Optimizer step\n if iteration < opt.iterations:\n gaussians.optimizer.step()\n gaussians.optimizer.zero_grad(set_to_none = True)\n\n if (iteration in checkpoint_iterations):\n print(\"\\n[ITER {}] Saving Checkpoint\".format(iteration))\n torch.save((gaussians.capture(), iteration), scene.model_path + \"/chkpnt\" + str(iteration) + \".pth\")\n\ndef prepare_output_and_logger(args): \n if not args.model_path:\n if os.getenv('OAR_JOB_ID'):\n unique_str=os.getenv('OAR_JOB_ID')\n else:\n unique_str = str(uuid.uuid4())\n args.model_path = os.path.join(\"./output/\", unique_str[0:10])\n \n # Set up output folder\n print(\"Output folder: {}\".format(args.model_path))\n os.makedirs(args.model_path, exist_ok = True)\n with open(os.path.join(args.model_path, \"cfg_args\"), 'w') as cfg_log_f:\n cfg_log_f.write(str(Namespace(**vars(args))))\n\n # Create Tensorboard writer\n tb_writer = None\n if TENSORBOARD_FOUND:\n tb_writer = SummaryWriter(args.model_path)\n else:\n print(\"Tensorboard not available: not logging progress\")\n return tb_writer\n\ndef training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs):\n if tb_writer:\n tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration)\n tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration)\n tb_writer.add_scalar('iter_time', elapsed, iteration)\n\n # Report test and samples of training set\n if iteration in testing_iterations:\n torch.cuda.empty_cache()\n validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()}, \n {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]})\n\n for config in validation_configs:\n if config['cameras'] and len(config['cameras']) > 0:\n l1_test = 0.0\n psnr_test = 0.0\n for idx, viewpoint in enumerate(config['cameras']):\n image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)[\"render\"], 0.0, 1.0)\n gt_image = torch.clamp(viewpoint.original_image.to(\"cuda\"), 0.0, 1.0)\n if tb_writer and (idx < 5):\n tb_writer.add_images(config['name'] + \"_view_{}/render\".format(viewpoint.image_name), image[None], global_step=iteration)\n if iteration == testing_iterations[0]:\n tb_writer.add_images(config['name'] + \"_view_{}/ground_truth\".format(viewpoint.image_name), gt_image[None], global_step=iteration)\n l1_test += l1_loss(image, gt_image).mean().double()\n psnr_test += psnr(image, gt_image).mean().double()\n psnr_test /= len(config['cameras'])\n l1_test /= len(config['cameras']) \n print(\"\\n[ITER {}] Evaluating {}: L1 {} PSNR {}\".format(iteration, config['name'], l1_test, psnr_test))\n if tb_writer:\n tb_writer.add_scalar(config['name'] + '/loss_viewpoint - l1_loss', l1_test, iteration)\n tb_writer.add_scalar(config['name'] + '/loss_viewpoint - psnr', psnr_test, iteration)\n\n if tb_writer:\n tb_writer.add_histogram(\"scene/opacity_histogram\", scene.gaussians.get_opacity, iteration)\n tb_writer.add_scalar('total_points', scene.gaussians.get_xyz.shape[0], iteration)\n torch.cuda.empty_cache()\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Training script parameters\")\n lp = ModelParams(parser)\n op = OptimizationParams(parser)\n pp = PipelineParams(parser)\n parser.add_argument('--ip', type=str, default=\"127.0.0.1\")\n parser.add_argument('--port', type=int, default=6009)\n parser.add_argument('--debug_from', type=int, default=-1)\n parser.add_argument('--detect_anomaly', action='store_true', default=False)\n parser.add_argument(\"--test_iterations\", nargs=\"+\", type=int, default=[7_000, 30_000])\n parser.add_argument(\"--save_iterations\", nargs=\"+\", type=int, default=[7_000, 30_000])\n parser.add_argument(\"--quiet\", action=\"store_true\")\n parser.add_argument(\"--checkpoint_iterations\", nargs=\"+\", type=int, default=[])\n parser.add_argument(\"--start_checkpoint\", type=str, default = None)\n args = parser.parse_args(sys.argv[1:])\n args.save_iterations.append(args.iterations)\n \n print(\"Optimizing \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n # Start GUI server, configure and run training\n network_gui.init(args.ip, args.port)\n torch.autograd.set_detect_anomaly(args.detect_anomaly)\n training(lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from)\n\n # All done\n print(\"\\nTraining complete.\")","source_hash":"e500724aaebaf72b9527b166018435b5dd73aa7cf2a330a2664fd89de7f7db35","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:train.training","uri":"program://EfficientDynamic3DGaussian/function/train.training#L36-L187","kind":"function","name":"training","path":"train.py","language":"python","start_line":36,"end_line":187,"context_start_line":16,"context_end_line":207,"code":"from utils.loss_utils import l1_loss, ssim\nfrom gaussian_renderer import render, render_flow, network_gui\nimport sys\nfrom scene import Scene, GaussianModel\nfrom utils.general_utils import safe_state\nimport uuid\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser, Namespace\nfrom arguments import ModelParams, PipelineParams, OptimizationParams\nimport copy\ntry:\n from torch.utils.tensorboard import SummaryWriter\n TENSORBOARD_FOUND = True\nexcept ImportError:\n TENSORBOARD_FOUND = False\n\nfrom PIL import Image\nimport numpy as np\n\ndef training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from):\n first_iter = 0\n tb_writer = prepare_output_and_logger(dataset)\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians)\n gaussians.training_setup(opt)\n if checkpoint:\n (model_params, first_iter) = torch.load(checkpoint)\n gaussians.restore(model_params, opt)\n\n\n bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n white_color = [1, 1, 1]\n white_background = torch.tensor(white_color, dtype=torch.float32, device=\"cuda\")\n\n iter_start = torch.cuda.Event(enable_timing = True)\n iter_end = torch.cuda.Event(enable_timing = True)\n\n viewpoint_stack = None\n ema_loss_for_log = 0.0\n ema_flow_loss_for_log = 0.0\n progress_bar = tqdm(range(first_iter, opt.iterations), desc=\"Training progress\")\n first_iter += 1\n if scene.use_loader:\n cam_loader = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=True, num_workers=16, collate_fn=list)\n loader = iter(cam_loader)\n\n # mask = torch.tensor((np.array(Image.open('mask.png'))[:, :, 3] > 0)).cuda()\n\n for iteration in range(first_iter, opt.iterations + 1): \n if network_gui.conn == None:\n network_gui.try_connect()\n while network_gui.conn != None:\n try:\n net_image_bytes = None\n custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive()\n if custom_cam != None:\n net_image = render(custom_cam, gaussians, pipe, background, scaling_modifer)[\"render\"]\n net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy())\n network_gui.send(net_image_bytes, dataset.source_path)\n if do_training and ((iteration < int(opt.iterations)) or not keep_alive):\n break\n except Exception as e:\n network_gui.conn = None\n\n iter_start.record()\n\n gaussians.update_learning_rate(iteration)\n\n # Every 1000 its we increase the levels of SH up to a maximum degree\n if iteration % 1000 == 0:\n gaussians.oneupSHdegree()\n\n\n if scene.use_loader:\n try:\n viewpoint_cam = next(loader)[0]\n except:\n loader = iter(cam_loader)\n viewpoint_cam = next(loader)[0]\n else:\n # Pick a random Camera\n if not viewpoint_stack:\n viewpoint_stack = scene.getTrainCameras().copy()\n viewpoint_cam = viewpoint_stack.pop(randint(0, len(viewpoint_stack)-1))\n\n # Render\n if (iteration - 1) == debug_from:\n pipe.debug = True\n\n\n render_pkg = render(viewpoint_cam, gaussians, pipe, background, itr=iteration)\n image, viewspace_point_tensor, visibility_filter, radii = render_pkg[\"render\"], render_pkg[\"viewspace_points\"], render_pkg[\"visibility_filter\"], render_pkg[\"radii\"]\n # Loss\n gt_image = viewpoint_cam.original_image.cuda()\n\n # if iteration % 200 == 0:\n # print(image.mean().item(), image.max().item(), image.min().item(), gt_image.mean().item(), gt_image.max().item(), gt_image.min().item())\n Ll1 = l1_loss(image, gt_image)\n # Ll1 = (torch.abs((image - gt_image))*mask).mean()\n lasso_loss = torch.nanmean(torch.abs(gaussians.get_xyz[:, 1:, :])) # + torch.nanmean(torch.abs(gaussians.get_rotation[:, 1:, :]))\n # print(lasso_loss, gaussians.get_rotation[:, 1:, :].abs().mean())\n flow_loss = 0\n if iteration >= 3000 and viewpoint_cam.kwargs['fwd_flow'] is not None:\n fwd_flow = viewpoint_cam.kwargs['fwd_flow'].cuda().permute(2, 0, 1)\n fwd_flow_mask = viewpoint_cam.kwargs['fwd_flow_mask'].cuda()\n render_flow_fwd = render_flow(viewpoint_cam, gaussians, pipe, white_background, itr=iteration, time_delta=scene.time_delta)['render'][:2, ...]\n fwd_flow = fwd_flow / (torch.max(torch.sqrt(torch.square(fwd_flow).sum(-1))) + 1e-5)\n render_flow_fwd = render_flow_fwd / (torch.max(torch.sqrt(torch.square(render_flow_fwd).sum(-1))) + 1e-5)\n M = fwd_flow_mask.unsqueeze(0)\n fwd_flow_loss = torch.sum(torch.abs(fwd_flow - render_flow_fwd) * M) / (torch.sum(M) + 1e-8) / fwd_flow.shape[-1]\n # fwd_flow_loss = torch.mean(torch.abs(fwd_flow - render_flow_fwd))\n flow_loss += fwd_flow_loss\n\n if iteration >= 3000 and viewpoint_cam.kwargs['bwd_flow'] is not None:\n bwd_flow = viewpoint_cam.kwargs['bwd_flow'].permute(2, 0, 1).cuda()\n bwd_flow_mask = viewpoint_cam.kwargs['bwd_flow_mask'].cuda()\n render_flow_bwd = render_flow(viewpoint_cam, gaussians, pipe, white_background, itr=iteration, time_delta=-scene.time_delta)['render'][:2, ...]\n bwd_flow = bwd_flow / (torch.max(torch.sqrt(torch.square(bwd_flow).sum(-1))) + 1e-5)\n render_flow_bwd = render_flow_bwd / (torch.max(torch.sqrt(torch.square(render_flow_bwd).sum(-1))) + 1e-5)\n M = bwd_flow_mask.unsqueeze(0)\n bwd_flow_loss = torch.sum(torch.abs(bwd_flow - render_flow_bwd) * M) / (torch.sum(M) + 1e-8) / bwd_flow.shape[-1]\n flow_loss += bwd_flow_loss\n\n loss = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim(image, gt_image)) + opt.lambda_lasso * lasso_loss\n loss += opt.lambda_flow * flow_loss\n # if type(loss) is int:\n # continue\n loss.backward()\n # print(gaussians._xyz[:, 0, 0].grad.shape)\n # print(gaussians.optimizer.param_groups[0]['params'][0].data.abs().mean(0)[1:5].flatten())\n iter_end.record()\n\n with torch.no_grad():\n # Progress bar\n ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log\n fl = flow_loss.item() if hasattr(flow_loss, 'item') else flow_loss\n ema_flow_loss_for_log = 0.4 * fl + 0.6 * ema_flow_loss_for_log\n if iteration % 10 == 0:\n progress_bar.set_postfix({\"Loss\": f\"{ema_loss_for_log:.{7}f}\", \"Flow loss\": f\"{ema_flow_loss_for_log:.{7}f}\"})\n progress_bar.update(10)\n if iteration == opt.iterations:\n progress_bar.close()\n\n # Log and save\n training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background))\n if (iteration in saving_iterations):\n print(\"\\n[ITER {}] Saving Gaussians\".format(iteration))\n scene.save(iteration)\n\n # Densification\n if iteration < opt.densify_until_iter:\n # Keep track of max radii in image-space for pruning\n gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter])\n gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)\n\n if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:\n size_threshold = 20 if iteration > opt.opacity_reset_interval else None\n gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold)\n \n if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter):\n gaussians.reset_opacity()\n\n # Optimizer step\n if iteration < opt.iterations:\n gaussians.optimizer.step()\n gaussians.optimizer.zero_grad(set_to_none = True)\n\n if (iteration in checkpoint_iterations):\n print(\"\\n[ITER {}] Saving Checkpoint\".format(iteration))\n torch.save((gaussians.capture(), iteration), scene.model_path + \"/chkpnt\" + str(iteration) + \".pth\")\n\ndef prepare_output_and_logger(args): \n if not args.model_path:\n if os.getenv('OAR_JOB_ID'):\n unique_str=os.getenv('OAR_JOB_ID')\n else:\n unique_str = str(uuid.uuid4())\n args.model_path = os.path.join(\"./output/\", unique_str[0:10])\n \n # Set up output folder\n print(\"Output folder: {}\".format(args.model_path))\n os.makedirs(args.model_path, exist_ok = True)\n with open(os.path.join(args.model_path, \"cfg_args\"), 'w') as cfg_log_f:\n cfg_log_f.write(str(Namespace(**vars(args))))\n\n # Create Tensorboard writer\n tb_writer = None\n if TENSORBOARD_FOUND:\n tb_writer = SummaryWriter(args.model_path)\n else:","source_hash":"e500724aaebaf72b9527b166018435b5dd73aa7cf2a330a2664fd89de7f7db35","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:train.prepare_output_and_logger","uri":"program://EfficientDynamic3DGaussian/function/train.prepare_output_and_logger#L189-L209","kind":"function","name":"prepare_output_and_logger","path":"train.py","language":"python","start_line":189,"end_line":209,"context_start_line":169,"context_end_line":229,"code":" # Keep track of max radii in image-space for pruning\n gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter])\n gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)\n\n if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:\n size_threshold = 20 if iteration > opt.opacity_reset_interval else None\n gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold)\n \n if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter):\n gaussians.reset_opacity()\n\n # Optimizer step\n if iteration < opt.iterations:\n gaussians.optimizer.step()\n gaussians.optimizer.zero_grad(set_to_none = True)\n\n if (iteration in checkpoint_iterations):\n print(\"\\n[ITER {}] Saving Checkpoint\".format(iteration))\n torch.save((gaussians.capture(), iteration), scene.model_path + \"/chkpnt\" + str(iteration) + \".pth\")\n\ndef prepare_output_and_logger(args): \n if not args.model_path:\n if os.getenv('OAR_JOB_ID'):\n unique_str=os.getenv('OAR_JOB_ID')\n else:\n unique_str = str(uuid.uuid4())\n args.model_path = os.path.join(\"./output/\", unique_str[0:10])\n \n # Set up output folder\n print(\"Output folder: {}\".format(args.model_path))\n os.makedirs(args.model_path, exist_ok = True)\n with open(os.path.join(args.model_path, \"cfg_args\"), 'w') as cfg_log_f:\n cfg_log_f.write(str(Namespace(**vars(args))))\n\n # Create Tensorboard writer\n tb_writer = None\n if TENSORBOARD_FOUND:\n tb_writer = SummaryWriter(args.model_path)\n else:\n print(\"Tensorboard not available: not logging progress\")\n return tb_writer\n\ndef training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs):\n if tb_writer:\n tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration)\n tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration)\n tb_writer.add_scalar('iter_time', elapsed, iteration)\n\n # Report test and samples of training set\n if iteration in testing_iterations:\n torch.cuda.empty_cache()\n validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()}, \n {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]})\n\n for config in validation_configs:\n if config['cameras'] and len(config['cameras']) > 0:\n l1_test = 0.0\n psnr_test = 0.0\n for idx, viewpoint in enumerate(config['cameras']):\n image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)[\"render\"], 0.0, 1.0)\n gt_image = torch.clamp(viewpoint.original_image.to(\"cuda\"), 0.0, 1.0)","source_hash":"e500724aaebaf72b9527b166018435b5dd73aa7cf2a330a2664fd89de7f7db35","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:train.training_report","uri":"program://EfficientDynamic3DGaussian/function/train.training_report#L211-L246","kind":"function","name":"training_report","path":"train.py","language":"python","start_line":211,"end_line":246,"context_start_line":191,"context_end_line":266,"code":" if os.getenv('OAR_JOB_ID'):\n unique_str=os.getenv('OAR_JOB_ID')\n else:\n unique_str = str(uuid.uuid4())\n args.model_path = os.path.join(\"./output/\", unique_str[0:10])\n \n # Set up output folder\n print(\"Output folder: {}\".format(args.model_path))\n os.makedirs(args.model_path, exist_ok = True)\n with open(os.path.join(args.model_path, \"cfg_args\"), 'w') as cfg_log_f:\n cfg_log_f.write(str(Namespace(**vars(args))))\n\n # Create Tensorboard writer\n tb_writer = None\n if TENSORBOARD_FOUND:\n tb_writer = SummaryWriter(args.model_path)\n else:\n print(\"Tensorboard not available: not logging progress\")\n return tb_writer\n\ndef training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs):\n if tb_writer:\n tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration)\n tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration)\n tb_writer.add_scalar('iter_time', elapsed, iteration)\n\n # Report test and samples of training set\n if iteration in testing_iterations:\n torch.cuda.empty_cache()\n validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()}, \n {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]})\n\n for config in validation_configs:\n if config['cameras'] and len(config['cameras']) > 0:\n l1_test = 0.0\n psnr_test = 0.0\n for idx, viewpoint in enumerate(config['cameras']):\n image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)[\"render\"], 0.0, 1.0)\n gt_image = torch.clamp(viewpoint.original_image.to(\"cuda\"), 0.0, 1.0)\n if tb_writer and (idx < 5):\n tb_writer.add_images(config['name'] + \"_view_{}/render\".format(viewpoint.image_name), image[None], global_step=iteration)\n if iteration == testing_iterations[0]:\n tb_writer.add_images(config['name'] + \"_view_{}/ground_truth\".format(viewpoint.image_name), gt_image[None], global_step=iteration)\n l1_test += l1_loss(image, gt_image).mean().double()\n psnr_test += psnr(image, gt_image).mean().double()\n psnr_test /= len(config['cameras'])\n l1_test /= len(config['cameras']) \n print(\"\\n[ITER {}] Evaluating {}: L1 {} PSNR {}\".format(iteration, config['name'], l1_test, psnr_test))\n if tb_writer:\n tb_writer.add_scalar(config['name'] + '/loss_viewpoint - l1_loss', l1_test, iteration)\n tb_writer.add_scalar(config['name'] + '/loss_viewpoint - psnr', psnr_test, iteration)\n\n if tb_writer:\n tb_writer.add_histogram(\"scene/opacity_histogram\", scene.gaussians.get_opacity, iteration)\n tb_writer.add_scalar('total_points', scene.gaussians.get_xyz.shape[0], iteration)\n torch.cuda.empty_cache()\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Training script parameters\")\n lp = ModelParams(parser)\n op = OptimizationParams(parser)\n pp = PipelineParams(parser)\n parser.add_argument('--ip', type=str, default=\"127.0.0.1\")\n parser.add_argument('--port', type=int, default=6009)\n parser.add_argument('--debug_from', type=int, default=-1)\n parser.add_argument('--detect_anomaly', action='store_true', default=False)\n parser.add_argument(\"--test_iterations\", nargs=\"+\", type=int, default=[7_000, 30_000])\n parser.add_argument(\"--save_iterations\", nargs=\"+\", type=int, default=[7_000, 30_000])\n parser.add_argument(\"--quiet\", action=\"store_true\")\n parser.add_argument(\"--checkpoint_iterations\", nargs=\"+\", type=int, default=[])\n parser.add_argument(\"--start_checkpoint\", type=str, default = None)\n args = parser.parse_args(sys.argv[1:])\n args.save_iterations.append(args.iterations)\n \n print(\"Optimizing \" + args.model_path)","source_hash":"e500724aaebaf72b9527b166018435b5dd73aa7cf2a330a2664fd89de7f7db35","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:merge_gaussians","uri":"program://EfficientDynamic3DGaussian/module/merge_gaussians#L1-L203","kind":"module","name":"merge_gaussians","path":"merge_gaussians.py","language":"python","start_line":1,"end_line":203,"context_start_line":1,"context_end_line":203,"code":"import os\nimport torch\nfrom torch import nn\n\nimport sys\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nimport numpy as np\nimport quaternion\n\ndef save_ply(xyz, features_dc, features_rest, opacity, scaling, rotation, path):\n mkdir_p(os.path.dirname(path))\n\n l = []\n for t in range(xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(features_dc.shape[1]*features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(features_rest.shape[1]*features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(rotation.shape[-1]):\n for t in range(rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n dtype_full = [(attribute, 'f4') for attribute in l]\n xyz = xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = opacity.detach().cpu().numpy()\n scale = scaling.detach().cpu().numpy()\n rotation = rotation.detach().flatten(start_dim=1).cpu().numpy()\n print(xyz.shape, f_dc.shape, f_rest.shape, opacities.shape, scaling.shape, rotation.shape)\n\n print(len(l))\n print(xyz.shape[0], len(dtype_full))\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\ndef load_ply(path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n xyz = np.stack((x, y, z), axis=-1)\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n\n features_dc = np.zeros((xyz.shape[0], 3, 1))\n features_dc[:, 0, 0] = np.asarray(plydata.elements[0][\"f_dc_0\"])\n features_dc[:, 1, 0] = np.asarray(plydata.elements[0][\"f_dc_1\"])\n features_dc[:, 2, 0] = np.asarray(plydata.elements[0][\"f_dc_2\"])\n\n extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"f_rest_\")]\n extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))\n assert len(extra_f_names)==3*(3 + 1) ** 2 - 3\n features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))\n for idx, attr_name in enumerate(extra_f_names):\n features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)\n features_extra = features_extra.reshape((features_extra.shape[0], 3, (3 + 1) ** 2 - 1))\n\n scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"scale_\")]\n scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))\n scales = np.zeros((xyz.shape[0], len(scale_names)))\n for idx, attr_name in enumerate(scale_names):\n scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n rot_names = sorted(rot_names, key = lambda x: (int(x.split('_')[-1]), int(x.split('_')[-2])))\n rots = np.zeros((xyz.shape[0], len(rot_names)))\n for idx, attr_name in enumerate(rot_names):\n rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n rots = rots.reshape(xyz.shape[0], -1, 4)\n\n xyz = torch.tensor(xyz, dtype=torch.float, device=\"cuda\")\n features_dc = torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous()\n features_rest = torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous()\n opacity = torch.tensor(opacities, dtype=torch.float, device=\"cuda\")\n scaling = torch.tensor(scales, dtype=torch.float, device=\"cuda\")\n rotation = torch.tensor(rots, dtype=torch.float, device=\"cuda\")\n return xyz, features_dc, features_rest, opacity, scaling, rotation\n\n\nply_path1 = sys.argv[1]\nply_path2 = sys.argv[2]\nnew_ply_path = sys.argv[3]\noffset_x, offset_y, offset_z = sys.argv[4:7]\noffset_x, offset_y, offset_z = float(offset_x), float(offset_y), float(offset_z)\n\nxyz1, features_dc1, features_rest1, opacity1, scaling1, rotation1 = load_ply(ply_path1)\nxyz2, features_dc2, features_rest2, opacity2, scaling2, rotation2 = load_ply(ply_path2)\n\n\nxyz2 = torch.cat([xyz2, torch.zeros((xyz2.shape[0], xyz1.shape[1] - xyz2.shape[1], xyz2.shape[2])).to('cuda')], dim=1)\nrotation2 = torch.cat([rotation2, torch.zeros((rotation2.shape[0], rotation1.shape[1] - rotation2.shape[1], rotation2.shape[2])).to('cuda')], dim=1)\n\nc2w = np.array([\n [\n 0.8865219950675964,\n -0.30261921882629395,\n 0.3500004708766937,\n 1.4108970165252686\n ],\n [\n 0.4626864194869995,\n 0.579828143119812,\n -0.670612096786499,\n -2.7033238410949707\n ],\n [\n -1.4901161193847656e-08,\n 0.756452739238739,\n 0.6540482640266418,\n 2.6365528106689453\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 1.0\n ]\n ])\nc2w = np.array([[ 0.888224 , -0.28239794, 0.36236657, 1.4108970165252686],\n [ 0.4588151 , 0.50513121, -0.7309796, -2.7033238410949707 ],\n [ 0.02338447, 0.81553287, 0.5782381, 2.6365528106689453 ],\n [0, 0, 0, 1]])\nc2w[:3, :3] = np.array([[ 0.83427332, -0.19049942, 0.51739541],\n [ 0.53440564, 0.51025918, -0.67382949],\n [-0.13564163, 0.83865698, 0.52749958]])\nc2w[:3, :3] = np.array([[ 0.99391392, 0.01907107, 0.10849614],\n [ 0.09653589, 0.32365205, -0.94123864],\n [-0.05306543, 0.94598396, 0.31984124]])\nc2w[:3, 1:3] *= -1\n# get the world-to-camera transform and set R, T\n\nw2c = np.linalg.inv(c2w)\nprint(xyz2[:, 0, :].mean(0), xyz2[:, 0, :].var(0))\nxyz2 = xyz2 @ torch.tensor(w2c[:3, :3]).to('cuda').float()\nxyz2 = xyz2 / 2.4\n\n# quaternions = quaternion.from_rotation_matrix(w2c, nonorthogonal=True)\n# rotation2[:, 0, :] = torch.tensor(quaternion.as_float_array(quaternion.from_rotation_matrix(quaternion.as_rotation_matrix(quaternion.as_quat_array(rotation2[:, 0, :].cpu().numpy())) @ w2c[:3, :3], nonorthogonal=True))).to('cuda').float()\n# rotation2[:, 0, :] = torch.tensor(quaternion.as_float_array(quaternion.as_quat_array(rotation2[:, 0, :].cpu().numpy()) * quaternions)).to('cuda')\nprint(scaling2[:, :].mean(0), scaling2[:, :].var(0), scaling2[:, :].max(0)[0], scaling2[:, :].min(0)[0])\n# scaling2 = scaling2 @ torch.tensor(np.linalg.inv(w2c[:3, :3])).to('cuda').float()\n# rotation2[:, 1, :] /= 2\n# scaling2[:, 0] = scaling2[:, :] @ torch.tensor(w2c[:3, 0]).to('cuda').float()\n# scaling2[:, 1], scaling2[:, 0] = scaling2[:, 0], scaling2[:, 1]\nscaling2 *= 1.4\n\n\n# R = quaternion.as_rotation_matrix(quaternion.as_quat_array(rotation2[:, 0, :].cpu().numpy())) @ w2c[:3, :3]\n# print(R.shape)\n# inv_R = np.linalg.inv(R)\n\n# print(np.diag(scaling2.cpu().numpy()).shape)\n# print((torch.diag_embed(scaling2).cpu().numpy() @ R @ w2c[:3, :3]).shape, np.linalg.inv(R @ w2c[:3, :3]).shape)\n# scaling2 = np.matmul(torch.diag_embed(scaling2).cpu().numpy()@ R @ w2c[:3, :3], np.linalg.inv(R @ w2c[:3, :3]))\n# print(scaling2.shape)\n# print(scaling2[:, :].mean(0), scaling2[:, :].var(0), scaling2[:, :].max(0)[0], scaling2[:, :].min(0)[0])\n# scaling2 = torch.diagonal(torch.tensor(scaling2).to('cuda'), dim1=-2, dim2=-1)\n\n\noffset = torch.tensor(np.array([offset_x, offset_y, offset_z])).to('cuda')\nxyz2[:, 0, :] = xyz2[:, 0, :] + offset\nprint(xyz2[:, 0, :].mean(0), xyz2[:, 0, :].var(0))\n\nxyz = torch.cat([xyz1, xyz2], dim=0)\nfeatures_dc = torch.cat([features_dc1, features_dc2], dim=0)\nfeatures_rest = torch.cat([features_rest1, features_rest2], dim=0)\nopacity = torch.cat([opacity1, opacity2], dim=0)\nscaling = torch.cat([scaling1, scaling2], dim=0)\nrotation = torch.cat([rotation1, rotation2], dim=0)\n\n\n\n\nsave_ply(xyz, features_dc, features_rest, opacity, scaling, rotation, new_ply_path)\n","source_hash":"b345b5b7a18f522623cd37e9a20fade4c40c21eab4c5df09ed1b85876723151e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:merge_gaussians.save_ply","uri":"program://EfficientDynamic3DGaussian/function/merge_gaussians.save_ply#L11-L47","kind":"function","name":"save_ply","path":"merge_gaussians.py","language":"python","start_line":11,"end_line":47,"context_start_line":1,"context_end_line":67,"code":"import os\nimport torch\nfrom torch import nn\n\nimport sys\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nimport numpy as np\nimport quaternion\n\ndef save_ply(xyz, features_dc, features_rest, opacity, scaling, rotation, path):\n mkdir_p(os.path.dirname(path))\n\n l = []\n for t in range(xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(features_dc.shape[1]*features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(features_rest.shape[1]*features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(rotation.shape[-1]):\n for t in range(rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n dtype_full = [(attribute, 'f4') for attribute in l]\n xyz = xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = opacity.detach().cpu().numpy()\n scale = scaling.detach().cpu().numpy()\n rotation = rotation.detach().flatten(start_dim=1).cpu().numpy()\n print(xyz.shape, f_dc.shape, f_rest.shape, opacities.shape, scaling.shape, rotation.shape)\n\n print(len(l))\n print(xyz.shape[0], len(dtype_full))\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\ndef load_ply(path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):","source_hash":"b345b5b7a18f522623cd37e9a20fade4c40c21eab4c5df09ed1b85876723151e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:merge_gaussians.load_ply","uri":"program://EfficientDynamic3DGaussian/function/merge_gaussians.load_ply#L49-L105","kind":"function","name":"load_ply","path":"merge_gaussians.py","language":"python","start_line":49,"end_line":105,"context_start_line":29,"context_end_line":125,"code":" l.append(f'rot_{t:03}_{i}')\n dtype_full = [(attribute, 'f4') for attribute in l]\n xyz = xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = opacity.detach().cpu().numpy()\n scale = scaling.detach().cpu().numpy()\n rotation = rotation.detach().flatten(start_dim=1).cpu().numpy()\n print(xyz.shape, f_dc.shape, f_rest.shape, opacities.shape, scaling.shape, rotation.shape)\n\n print(len(l))\n print(xyz.shape[0], len(dtype_full))\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\ndef load_ply(path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n xyz = np.stack((x, y, z), axis=-1)\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n\n features_dc = np.zeros((xyz.shape[0], 3, 1))\n features_dc[:, 0, 0] = np.asarray(plydata.elements[0][\"f_dc_0\"])\n features_dc[:, 1, 0] = np.asarray(plydata.elements[0][\"f_dc_1\"])\n features_dc[:, 2, 0] = np.asarray(plydata.elements[0][\"f_dc_2\"])\n\n extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"f_rest_\")]\n extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))\n assert len(extra_f_names)==3*(3 + 1) ** 2 - 3\n features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))\n for idx, attr_name in enumerate(extra_f_names):\n features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)\n features_extra = features_extra.reshape((features_extra.shape[0], 3, (3 + 1) ** 2 - 1))\n\n scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"scale_\")]\n scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))\n scales = np.zeros((xyz.shape[0], len(scale_names)))\n for idx, attr_name in enumerate(scale_names):\n scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n rot_names = sorted(rot_names, key = lambda x: (int(x.split('_')[-1]), int(x.split('_')[-2])))\n rots = np.zeros((xyz.shape[0], len(rot_names)))\n for idx, attr_name in enumerate(rot_names):\n rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n rots = rots.reshape(xyz.shape[0], -1, 4)\n\n xyz = torch.tensor(xyz, dtype=torch.float, device=\"cuda\")\n features_dc = torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous()\n features_rest = torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous()\n opacity = torch.tensor(opacities, dtype=torch.float, device=\"cuda\")\n scaling = torch.tensor(scales, dtype=torch.float, device=\"cuda\")\n rotation = torch.tensor(rots, dtype=torch.float, device=\"cuda\")\n return xyz, features_dc, features_rest, opacity, scaling, rotation\n\n\nply_path1 = sys.argv[1]\nply_path2 = sys.argv[2]\nnew_ply_path = sys.argv[3]\noffset_x, offset_y, offset_z = sys.argv[4:7]\noffset_x, offset_y, offset_z = float(offset_x), float(offset_y), float(offset_z)\n\nxyz1, features_dc1, features_rest1, opacity1, scaling1, rotation1 = load_ply(ply_path1)\nxyz2, features_dc2, features_rest2, opacity2, scaling2, rotation2 = load_ply(ply_path2)\n\n\nxyz2 = torch.cat([xyz2, torch.zeros((xyz2.shape[0], xyz1.shape[1] - xyz2.shape[1], xyz2.shape[2])).to('cuda')], dim=1)\nrotation2 = torch.cat([rotation2, torch.zeros((rotation2.shape[0], rotation1.shape[1] - rotation2.shape[1], rotation2.shape[2])).to('cuda')], dim=1)\n\nc2w = np.array([\n [\n 0.8865219950675964,\n -0.30261921882629395,\n 0.3500004708766937,","source_hash":"b345b5b7a18f522623cd37e9a20fade4c40c21eab4c5df09ed1b85876723151e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC","uri":"program://EfficientDynamic3DGaussian/module/neural_3D_dataset_NDC#L1-L429","kind":"module","name":"neural_3D_dataset_NDC","path":"neural_3D_dataset_NDC.py","language":"python","start_line":1,"end_line":429,"context_start_line":1,"context_end_line":429,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\nfrom .ray_utils import get_ray_directions_blender, get_rays, ndc_rays_blender\n\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n pose_avg: (3, 4) the average pose\n \"\"\"\n # 1. Compute the center\n center = poses[..., 3].mean(0) # (3)\n\n # 2. Compute the z axis\n z = normalize(poses[..., 2].mean(0)) # (3)\n\n # 3. Compute axis y' (no need to normalize as it's not the final output)\n y_ = poses[..., 1].mean(0) # (3)\n\n # 4. Compute the x axis\n x = normalize(np.cross(z, y_)) # (3)\n\n # 5. Compute the y axis (as z and x are normalized, y is already of norm 1)\n y = np.cross(x, z) # (3)\n\n pose_avg = np.stack([x, y, z, center], 1) # (3, 4)\n\n return pose_avg\n\n\ndef center_poses(poses, blender2opencv):\n \"\"\"\n Center the poses so that we can use NDC.\n See https://github.com/bmild/nerf/issues/34\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n poses_centered: (N_images, 3, 4) the centered poses\n pose_avg: (3, 4) the average pose\n \"\"\"\n poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.\n \"\"\"\n video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break\n video_frames.release()\n print(f\"Video {video_path} processed.\")\n return None\n\n\n# define a function to process all videos\ndef process_videos(videos, skip_index, img_wh, downsample, transform, num_workers=1):\n \"\"\"\n A multi-threaded function to load all videos fastly and memory-efficiently.\n To save memory, we pre-allocate a tensor to store all the images and spawn multi-threads to load the images into this tensor.\n \"\"\"\n all_imgs = torch.zeros(len(videos) - 1, 300, img_wh[-1] * img_wh[-2], 3)\n with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:\n # start a thread for each video\n current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"\n Generate a set of poses using NeRF's spiral camera trajectory as validation poses.\n \"\"\"\n # center pose\n c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):\n self.img_wh = (\n int(1024 / downsample),\n int(768 / downsample),\n ) # According to the neural 3D paper, the default resolution is 1024x768\n self.root_dir = datadir\n self.split = split\n self.downsample = 2704 / self.img_wh[0]\n self.is_stack = is_stack\n self.N_vis = N_vis\n self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.\n\n near_original = self.near_fars.min()\n scale_factor = near_original * 0.75\n self.near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n poses[..., 3] /= scale_factor\n\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n self.val_poses = get_spiral(poses, self.near_fars, N_views=N_views)\n\n W, H = self.img_wh\n self.directions = torch.tensor(\n get_ray_directions_blender(H, W, self.focal)\n ) # (H, W, 3)\n\n if self.split == \"train\":\n # Loading all videos from this dataset requires around 50GB memory, and stack them into a tensor requires another 50GB.\n # To save memory, we allocate a large tensor and load videos into it instead of using torch.stack/cat operations.\n all_times = []\n all_rays = []\n count = 300\n\n for index in range(0, len(videos)):\n if (\n index == self.eval_index\n ): # the eval_index(0 as default) is the evaluation one. We skip evaluation cameras.\n continue\n\n video_times = torch.tensor([i / (count - 1) for i in range(count)])\n all_times += [video_times]\n\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays += [torch.cat([rays_o, rays_d], 1)]\n print(f\"video {index} is loaded\")\n gc.collect()\n\n # load all video images\n all_imgs = process_videos(\n videos,\n self.eval_index,\n self.img_wh,\n self.downsample,\n self.transform,\n num_workers=8,\n )\n all_times = torch.stack(all_times, 0)\n all_rays = torch.stack(all_rays, 0)\n breakpoint()\n print(\"stack performed\")\n N_cam, N_time, N_rays, C = all_imgs.shape\n self.image_stride = N_rays\n self.cam_number = N_cam\n self.time_number = N_time\n self.all_rgbs = all_imgs\n self.all_times = all_times.view(N_cam, N_time, 1)\n self.all_rays = all_rays.reshape(N_cam, N_rays, 6)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n self.global_mean_rgb = torch.mean(all_imgs, dim=1)\n else:\n index = self.eval_index\n video_imgs = []\n video_frames = cv2.VideoCapture(videos[index])\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if self.downsample != 1.0:\n img = video_frame.resize(self.img_wh, Image.LANCZOS)\n img = self.transform(img)\n video_imgs += [img.view(3, -1).permute(1, 0)]\n else:\n break\n video_imgs = torch.stack(video_imgs, 0)\n video_times = torch.tensor(\n [i / (len(video_imgs) - 1) for i in range(len(video_imgs))]\n )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n\n def __len__(self):\n if self.split == \"train\" and self.is_stack is True:\n return self.cam_number * self.time_number\n else:\n return len(self.all_rgbs)\n\n def __getitem__(self, idx):\n if self.split == \"train\": # use data in the buffers\n if self.is_stack:\n cam_idx = idx // self.time_number\n time_idx = idx % self.time_number\n sample = {\n \"rays\": self.all_rays[cam_idx],\n \"rgbs\": self.all_rgbs[cam_idx, time_idx],\n \"time\": self.all_times[cam_idx, time_idx]\n * torch.ones_like(self.all_rays[cam_idx][:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[\n idx // (self.time_number * self.image_stride),\n idx % (self.image_stride),\n ],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[\n idx // (self.time_number * self.image_stride),\n idx\n % (self.time_number * self.image_stride)\n // self.image_stride,\n ]\n * torch.ones_like(self.all_rgbs[idx][:, 0:1]),\n }\n\n else: # create data for each image separately\n if self.is_stack:\n sample = {\n \"rays\": self.all_rays,\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[idx % self.image_stride],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx // self.image_stride]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n return sample\n\n def get_val_pose(self):\n render_poses = self.val_poses\n render_times = torch.linspace(0.0, 1.0, render_poses.shape[0]) * 2.0 - 1.0\n return render_poses, self.time_scale * render_times\n\n def get_val_rays(self):\n val_poses, val_times = self.get_val_pose() # get valitdation poses and times\n rays_all = [] # initialize list to store [rays_o, rays_d]\n\n for i in range(val_poses.shape[0]):\n c2w = torch.FloatTensor(val_poses[i])\n rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3)\n if self.ndc_ray:\n W, H = self.img_wh\n rays_o, rays_d = ndc_rays_blender(\n H, W, self.focal[0], 1.0, rays_o, rays_d\n )\n rays = torch.cat([rays_o, rays_d], 1) # (h*w, 6)\n rays_all.append(rays)\n return rays_all, torch.FloatTensor(val_times)","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.normalize","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.normalize#L16-L18","kind":"function","name":"normalize","path":"neural_3D_dataset_NDC.py","language":"python","start_line":16,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\nfrom .ray_utils import get_ray_directions_blender, get_rays, ndc_rays_blender\n\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n pose_avg: (3, 4) the average pose\n \"\"\"\n # 1. Compute the center","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.average_poses","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.average_poses#L21-L55","kind":"function","name":"average_poses","path":"neural_3D_dataset_NDC.py","language":"python","start_line":21,"end_line":55,"context_start_line":1,"context_end_line":75,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\nfrom .ray_utils import get_ray_directions_blender, get_rays, ndc_rays_blender\n\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n pose_avg: (3, 4) the average pose\n \"\"\"\n # 1. Compute the center\n center = poses[..., 3].mean(0) # (3)\n\n # 2. Compute the z axis\n z = normalize(poses[..., 2].mean(0)) # (3)\n\n # 3. Compute axis y' (no need to normalize as it's not the final output)\n y_ = poses[..., 1].mean(0) # (3)\n\n # 4. Compute the x axis\n x = normalize(np.cross(z, y_)) # (3)\n\n # 5. Compute the y axis (as z and x are normalized, y is already of norm 1)\n y = np.cross(x, z) # (3)\n\n pose_avg = np.stack([x, y, z, center], 1) # (3, 4)\n\n return pose_avg\n\n\ndef center_poses(poses, blender2opencv):\n \"\"\"\n Center the poses so that we can use NDC.\n See https://github.com/bmild/nerf/issues/34\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n poses_centered: (N_images, 3, 4) the centered poses\n pose_avg: (3, 4) the average pose\n \"\"\"\n poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.center_poses","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.center_poses#L58-L85","kind":"function","name":"center_poses","path":"neural_3D_dataset_NDC.py","language":"python","start_line":58,"end_line":85,"context_start_line":38,"context_end_line":105,"code":" # 1. Compute the center\n center = poses[..., 3].mean(0) # (3)\n\n # 2. Compute the z axis\n z = normalize(poses[..., 2].mean(0)) # (3)\n\n # 3. Compute axis y' (no need to normalize as it's not the final output)\n y_ = poses[..., 1].mean(0) # (3)\n\n # 4. Compute the x axis\n x = normalize(np.cross(z, y_)) # (3)\n\n # 5. Compute the y axis (as z and x are normalized, y is already of norm 1)\n y = np.cross(x, z) # (3)\n\n pose_avg = np.stack([x, y, z, center], 1) # (3, 4)\n\n return pose_avg\n\n\ndef center_poses(poses, blender2opencv):\n \"\"\"\n Center the poses so that we can use NDC.\n See https://github.com/bmild/nerf/issues/34\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n poses_centered: (N_images, 3, 4) the centered poses\n pose_avg: (3, 4) the average pose\n \"\"\"\n poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.viewmatrix","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.viewmatrix#L88-L95","kind":"function","name":"viewmatrix","path":"neural_3D_dataset_NDC.py","language":"python","start_line":88,"end_line":95,"context_start_line":68,"context_end_line":115,"code":" poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.render_path_spiral","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.render_path_spiral#L98-L110","kind":"function","name":"render_path_spiral","path":"neural_3D_dataset_NDC.py","language":"python","start_line":98,"end_line":110,"context_start_line":78,"context_end_line":130,"code":" [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.\n \"\"\"\n video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.process_video","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.process_video#L113-L133","kind":"function","name":"process_video","path":"neural_3D_dataset_NDC.py","language":"python","start_line":113,"end_line":133,"context_start_line":93,"context_end_line":153,"code":" m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.\n \"\"\"\n video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break\n video_frames.release()\n print(f\"Video {video_path} processed.\")\n return None\n\n\n# define a function to process all videos\ndef process_videos(videos, skip_index, img_wh, downsample, transform, num_workers=1):\n \"\"\"\n A multi-threaded function to load all videos fastly and memory-efficiently.\n To save memory, we pre-allocate a tensor to store all the images and spawn multi-threads to load the images into this tensor.\n \"\"\"\n all_imgs = torch.zeros(len(videos) - 1, 300, img_wh[-1] * img_wh[-2], 3)\n with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:\n # start a thread for each video\n current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.process_videos","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.process_videos#L137-L162","kind":"function","name":"process_videos","path":"neural_3D_dataset_NDC.py","language":"python","start_line":137,"end_line":162,"context_start_line":117,"context_end_line":182,"code":" video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if downsample != 1.0:\n img = video_frame.resize(img_wh, Image.LANCZOS)\n img = transform(img)\n video_data_save[count] = img.view(3, -1).permute(1, 0)\n count += 1\n else:\n break\n video_frames.release()\n print(f\"Video {video_path} processed.\")\n return None\n\n\n# define a function to process all videos\ndef process_videos(videos, skip_index, img_wh, downsample, transform, num_workers=1):\n \"\"\"\n A multi-threaded function to load all videos fastly and memory-efficiently.\n To save memory, we pre-allocate a tensor to store all the images and spawn multi-threads to load the images into this tensor.\n \"\"\"\n all_imgs = torch.zeros(len(videos) - 1, 300, img_wh[-1] * img_wh[-2], 3)\n with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:\n # start a thread for each video\n current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"\n Generate a set of poses using NeRF's spiral camera trajectory as validation poses.\n \"\"\"\n # center pose\n c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.get_spiral","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.get_spiral#L165-L187","kind":"function","name":"get_spiral","path":"neural_3D_dataset_NDC.py","language":"python","start_line":165,"end_line":187,"context_start_line":145,"context_end_line":207,"code":" current_index = 0\n futures = []\n for index, video_path in enumerate(videos):\n # skip the video with skip_index (eval video)\n if index == skip_index:\n continue\n else:\n future = executor.submit(\n process_video,\n all_imgs[current_index],\n video_path,\n img_wh,\n downsample,\n transform,\n )\n futures.append(future)\n current_index += 1\n return all_imgs\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"\n Generate a set of poses using NeRF's spiral camera trajectory as validation poses.\n \"\"\"\n # center pose\n c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.Neural3D_NDC_Dataset","uri":"program://EfficientDynamic3DGaussian/class/neural_3D_dataset_NDC.Neural3D_NDC_Dataset#L190-L429","kind":"class","name":"Neural3D_NDC_Dataset","path":"neural_3D_dataset_NDC.py","language":"python","start_line":190,"end_line":429,"context_start_line":170,"context_end_line":429,"code":" c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):\n self.img_wh = (\n int(1024 / downsample),\n int(768 / downsample),\n ) # According to the neural 3D paper, the default resolution is 1024x768\n self.root_dir = datadir\n self.split = split\n self.downsample = 2704 / self.img_wh[0]\n self.is_stack = is_stack\n self.N_vis = N_vis\n self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.\n\n near_original = self.near_fars.min()\n scale_factor = near_original * 0.75\n self.near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n poses[..., 3] /= scale_factor\n\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n self.val_poses = get_spiral(poses, self.near_fars, N_views=N_views)\n\n W, H = self.img_wh\n self.directions = torch.tensor(\n get_ray_directions_blender(H, W, self.focal)\n ) # (H, W, 3)\n\n if self.split == \"train\":\n # Loading all videos from this dataset requires around 50GB memory, and stack them into a tensor requires another 50GB.\n # To save memory, we allocate a large tensor and load videos into it instead of using torch.stack/cat operations.\n all_times = []\n all_rays = []\n count = 300\n\n for index in range(0, len(videos)):\n if (\n index == self.eval_index\n ): # the eval_index(0 as default) is the evaluation one. We skip evaluation cameras.\n continue\n\n video_times = torch.tensor([i / (count - 1) for i in range(count)])\n all_times += [video_times]\n\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays += [torch.cat([rays_o, rays_d], 1)]\n print(f\"video {index} is loaded\")\n gc.collect()\n\n # load all video images\n all_imgs = process_videos(\n videos,\n self.eval_index,\n self.img_wh,\n self.downsample,\n self.transform,\n num_workers=8,\n )\n all_times = torch.stack(all_times, 0)\n all_rays = torch.stack(all_rays, 0)\n breakpoint()\n print(\"stack performed\")\n N_cam, N_time, N_rays, C = all_imgs.shape\n self.image_stride = N_rays\n self.cam_number = N_cam\n self.time_number = N_time\n self.all_rgbs = all_imgs\n self.all_times = all_times.view(N_cam, N_time, 1)\n self.all_rays = all_rays.reshape(N_cam, N_rays, 6)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n self.global_mean_rgb = torch.mean(all_imgs, dim=1)\n else:\n index = self.eval_index\n video_imgs = []\n video_frames = cv2.VideoCapture(videos[index])\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if self.downsample != 1.0:\n img = video_frame.resize(self.img_wh, Image.LANCZOS)\n img = self.transform(img)\n video_imgs += [img.view(3, -1).permute(1, 0)]\n else:\n break\n video_imgs = torch.stack(video_imgs, 0)\n video_times = torch.tensor(\n [i / (len(video_imgs) - 1) for i in range(len(video_imgs))]\n )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n\n def __len__(self):\n if self.split == \"train\" and self.is_stack is True:\n return self.cam_number * self.time_number\n else:\n return len(self.all_rgbs)\n\n def __getitem__(self, idx):\n if self.split == \"train\": # use data in the buffers\n if self.is_stack:\n cam_idx = idx // self.time_number\n time_idx = idx % self.time_number\n sample = {\n \"rays\": self.all_rays[cam_idx],\n \"rgbs\": self.all_rgbs[cam_idx, time_idx],\n \"time\": self.all_times[cam_idx, time_idx]\n * torch.ones_like(self.all_rays[cam_idx][:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[\n idx // (self.time_number * self.image_stride),\n idx % (self.image_stride),\n ],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[\n idx // (self.time_number * self.image_stride),\n idx\n % (self.time_number * self.image_stride)\n // self.image_stride,\n ]\n * torch.ones_like(self.all_rgbs[idx][:, 0:1]),\n }\n\n else: # create data for each image separately\n if self.is_stack:\n sample = {\n \"rays\": self.all_rays,\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[idx % self.image_stride],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx // self.image_stride]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n return sample\n\n def get_val_pose(self):\n render_poses = self.val_poses\n render_times = torch.linspace(0.0, 1.0, render_poses.shape[0]) * 2.0 - 1.0\n return render_poses, self.time_scale * render_times\n\n def get_val_rays(self):\n val_poses, val_times = self.get_val_pose() # get valitdation poses and times\n rays_all = [] # initialize list to store [rays_o, rays_d]\n\n for i in range(val_poses.shape[0]):\n c2w = torch.FloatTensor(val_poses[i])\n rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3)\n if self.ndc_ray:\n W, H = self.img_wh\n rays_o, rays_d = ndc_rays_blender(\n H, W, self.focal[0], 1.0, rays_o, rays_d\n )\n rays = torch.cat([rays_o, rays_d], 1) # (h*w, 6)\n rays_all.append(rays)\n return rays_all, torch.FloatTensor(val_times)","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.__init__","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.__init__#L191-L235","kind":"function","name":"__init__","path":"neural_3D_dataset_NDC.py","language":"python","start_line":191,"end_line":235,"context_start_line":171,"context_end_line":255,"code":"\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\nclass Neural3D_NDC_Dataset(Dataset):\n def __init__(\n self,\n datadir,\n split=\"train\",\n downsample=1.0,\n is_stack=True,\n cal_fine_bbox=False,\n N_vis=-1,\n time_scale=1.0,\n scene_bbox_min=[-1.0, -1.0, -1.0],\n scene_bbox_max=[1.0, 1.0, 1.0],\n N_random_pose=1000,\n bd_factor=0.75,\n eval_step=1,\n eval_index=0,\n sphere_scale=1.0,\n ):\n self.img_wh = (\n int(1024 / downsample),\n int(768 / downsample),\n ) # According to the neural 3D paper, the default resolution is 1024x768\n self.root_dir = datadir\n self.split = split\n self.downsample = 2704 / self.img_wh[0]\n self.is_stack = is_stack\n self.N_vis = N_vis\n self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.load_meta","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.load_meta#L237-L355","kind":"function","name":"load_meta","path":"neural_3D_dataset_NDC.py","language":"python","start_line":237,"end_line":355,"context_start_line":217,"context_end_line":375,"code":" self.time_scale = time_scale\n self.scene_bbox = torch.tensor([scene_bbox_min, scene_bbox_max])\n\n self.world_bound_scale = 1.1\n self.bd_factor = bd_factor\n self.eval_step = eval_step\n self.eval_index = eval_index\n self.blender2opencv = np.eye(4)\n self.transform = T.ToTensor()\n\n self.near = 0.0\n self.far = 1.0\n self.near_far = [self.near, self.far] # NDC near far is [0, 1.0]\n self.white_bg = False\n self.ndc_ray = True\n self.depth_data = False\n\n self.load_meta()\n print(\"meta data loaded\")\n\n def load_meta(self):\n \"\"\"\n Load meta data from the dataset.\n \"\"\"\n # Read poses and video file paths.\n poses_arr = np.load(os.path.join(self.root_dir, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n self.near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(self.root_dir, \"cam*.mp4\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / self.downsample\n self.focal = [focal, focal]\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, self.blender2opencv\n ) # Re-center poses so that the average is near the center.\n\n near_original = self.near_fars.min()\n scale_factor = near_original * 0.75\n self.near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n poses[..., 3] /= scale_factor\n\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n self.val_poses = get_spiral(poses, self.near_fars, N_views=N_views)\n\n W, H = self.img_wh\n self.directions = torch.tensor(\n get_ray_directions_blender(H, W, self.focal)\n ) # (H, W, 3)\n\n if self.split == \"train\":\n # Loading all videos from this dataset requires around 50GB memory, and stack them into a tensor requires another 50GB.\n # To save memory, we allocate a large tensor and load videos into it instead of using torch.stack/cat operations.\n all_times = []\n all_rays = []\n count = 300\n\n for index in range(0, len(videos)):\n if (\n index == self.eval_index\n ): # the eval_index(0 as default) is the evaluation one. We skip evaluation cameras.\n continue\n\n video_times = torch.tensor([i / (count - 1) for i in range(count)])\n all_times += [video_times]\n\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays += [torch.cat([rays_o, rays_d], 1)]\n print(f\"video {index} is loaded\")\n gc.collect()\n\n # load all video images\n all_imgs = process_videos(\n videos,\n self.eval_index,\n self.img_wh,\n self.downsample,\n self.transform,\n num_workers=8,\n )\n all_times = torch.stack(all_times, 0)\n all_rays = torch.stack(all_rays, 0)\n breakpoint()\n print(\"stack performed\")\n N_cam, N_time, N_rays, C = all_imgs.shape\n self.image_stride = N_rays\n self.cam_number = N_cam\n self.time_number = N_time\n self.all_rgbs = all_imgs\n self.all_times = all_times.view(N_cam, N_time, 1)\n self.all_rays = all_rays.reshape(N_cam, N_rays, 6)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n self.global_mean_rgb = torch.mean(all_imgs, dim=1)\n else:\n index = self.eval_index\n video_imgs = []\n video_frames = cv2.VideoCapture(videos[index])\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:\n video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)\n video_frame = Image.fromarray(video_frame)\n if self.downsample != 1.0:\n img = video_frame.resize(self.img_wh, Image.LANCZOS)\n img = self.transform(img)\n video_imgs += [img.view(3, -1).permute(1, 0)]\n else:\n break\n video_imgs = torch.stack(video_imgs, 0)\n video_times = torch.tensor(\n [i / (len(video_imgs) - 1) for i in range(len(video_imgs))]\n )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n\n def __len__(self):\n if self.split == \"train\" and self.is_stack is True:\n return self.cam_number * self.time_number\n else:\n return len(self.all_rgbs)\n\n def __getitem__(self, idx):\n if self.split == \"train\": # use data in the buffers\n if self.is_stack:\n cam_idx = idx // self.time_number\n time_idx = idx % self.time_number\n sample = {\n \"rays\": self.all_rays[cam_idx],\n \"rgbs\": self.all_rgbs[cam_idx, time_idx],\n \"time\": self.all_times[cam_idx, time_idx]\n * torch.ones_like(self.all_rays[cam_idx][:, 0:1]),\n }\n\n else:","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.__len__","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.__len__#L357-L361","kind":"function","name":"__len__","path":"neural_3D_dataset_NDC.py","language":"python","start_line":357,"end_line":361,"context_start_line":337,"context_end_line":381,"code":" )\n video_imgs = video_imgs[0 :: self.eval_step]\n video_times = video_times[0 :: self.eval_step]\n rays_o, rays_d = get_rays(\n self.directions, torch.FloatTensor(poses[index])\n ) # both (h*w, 3)\n rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n\n def __len__(self):\n if self.split == \"train\" and self.is_stack is True:\n return self.cam_number * self.time_number\n else:\n return len(self.all_rgbs)\n\n def __getitem__(self, idx):\n if self.split == \"train\": # use data in the buffers\n if self.is_stack:\n cam_idx = idx // self.time_number\n time_idx = idx % self.time_number\n sample = {\n \"rays\": self.all_rays[cam_idx],\n \"rgbs\": self.all_rgbs[cam_idx, time_idx],\n \"time\": self.all_times[cam_idx, time_idx]\n * torch.ones_like(self.all_rays[cam_idx][:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[\n idx // (self.time_number * self.image_stride),\n idx % (self.image_stride),\n ],\n \"rgbs\": self.all_rgbs[idx],","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.__getitem__","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.__getitem__#L363-L408","kind":"function","name":"__getitem__","path":"neural_3D_dataset_NDC.py","language":"python","start_line":363,"end_line":408,"context_start_line":343,"context_end_line":428,"code":" rays_o, rays_d = ndc_rays_blender(H, W, focal, 1.0, rays_o, rays_d)\n all_rays = torch.cat([rays_o, rays_d], 1)\n gc.collect()\n N_time, N_rays, C = video_imgs.shape\n self.image_stride = N_rays\n self.time_number = N_time\n self.all_rgbs = video_imgs.view(-1, N_rays, 3)\n self.all_rays = all_rays\n self.all_times = video_times\n self.all_rgbs = self.all_rgbs.view(\n -1, *self.img_wh[::-1], 3\n ) # (len(self.meta['frames]),h,w,3)\n self.all_times = self.time_scale * (self.all_times * 2.0 - 1.0)\n\n def __len__(self):\n if self.split == \"train\" and self.is_stack is True:\n return self.cam_number * self.time_number\n else:\n return len(self.all_rgbs)\n\n def __getitem__(self, idx):\n if self.split == \"train\": # use data in the buffers\n if self.is_stack:\n cam_idx = idx // self.time_number\n time_idx = idx % self.time_number\n sample = {\n \"rays\": self.all_rays[cam_idx],\n \"rgbs\": self.all_rgbs[cam_idx, time_idx],\n \"time\": self.all_times[cam_idx, time_idx]\n * torch.ones_like(self.all_rays[cam_idx][:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[\n idx // (self.time_number * self.image_stride),\n idx % (self.image_stride),\n ],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[\n idx // (self.time_number * self.image_stride),\n idx\n % (self.time_number * self.image_stride)\n // self.image_stride,\n ]\n * torch.ones_like(self.all_rgbs[idx][:, 0:1]),\n }\n\n else: # create data for each image separately\n if self.is_stack:\n sample = {\n \"rays\": self.all_rays,\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[idx % self.image_stride],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx // self.image_stride]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n return sample\n\n def get_val_pose(self):\n render_poses = self.val_poses\n render_times = torch.linspace(0.0, 1.0, render_poses.shape[0]) * 2.0 - 1.0\n return render_poses, self.time_scale * render_times\n\n def get_val_rays(self):\n val_poses, val_times = self.get_val_pose() # get valitdation poses and times\n rays_all = [] # initialize list to store [rays_o, rays_d]\n\n for i in range(val_poses.shape[0]):\n c2w = torch.FloatTensor(val_poses[i])\n rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3)\n if self.ndc_ray:\n W, H = self.img_wh\n rays_o, rays_d = ndc_rays_blender(\n H, W, self.focal[0], 1.0, rays_o, rays_d\n )\n rays = torch.cat([rays_o, rays_d], 1) # (h*w, 6)\n rays_all.append(rays)","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.get_val_pose","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.get_val_pose#L410-L413","kind":"function","name":"get_val_pose","path":"neural_3D_dataset_NDC.py","language":"python","start_line":410,"end_line":413,"context_start_line":390,"context_end_line":429,"code":"\n else: # create data for each image separately\n if self.is_stack:\n sample = {\n \"rays\": self.all_rays,\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[idx % self.image_stride],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx // self.image_stride]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n return sample\n\n def get_val_pose(self):\n render_poses = self.val_poses\n render_times = torch.linspace(0.0, 1.0, render_poses.shape[0]) * 2.0 - 1.0\n return render_poses, self.time_scale * render_times\n\n def get_val_rays(self):\n val_poses, val_times = self.get_val_pose() # get valitdation poses and times\n rays_all = [] # initialize list to store [rays_o, rays_d]\n\n for i in range(val_poses.shape[0]):\n c2w = torch.FloatTensor(val_poses[i])\n rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3)\n if self.ndc_ray:\n W, H = self.img_wh\n rays_o, rays_d = ndc_rays_blender(\n H, W, self.focal[0], 1.0, rays_o, rays_d\n )\n rays = torch.cat([rays_o, rays_d], 1) # (h*w, 6)\n rays_all.append(rays)\n return rays_all, torch.FloatTensor(val_times)","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:neural_3D_dataset_NDC.get_val_rays","uri":"program://EfficientDynamic3DGaussian/function/neural_3D_dataset_NDC.get_val_rays#L415-L429","kind":"function","name":"get_val_rays","path":"neural_3D_dataset_NDC.py","language":"python","start_line":415,"end_line":429,"context_start_line":395,"context_end_line":429,"code":" \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n else:\n sample = {\n \"rays\": self.all_rays[idx % self.image_stride],\n \"rgbs\": self.all_rgbs[idx],\n \"time\": self.all_times[idx // self.image_stride]\n * torch.ones_like(self.all_rays[:, 0:1]),\n }\n\n return sample\n\n def get_val_pose(self):\n render_poses = self.val_poses\n render_times = torch.linspace(0.0, 1.0, render_poses.shape[0]) * 2.0 - 1.0\n return render_poses, self.time_scale * render_times\n\n def get_val_rays(self):\n val_poses, val_times = self.get_val_pose() # get valitdation poses and times\n rays_all = [] # initialize list to store [rays_o, rays_d]\n\n for i in range(val_poses.shape[0]):\n c2w = torch.FloatTensor(val_poses[i])\n rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3)\n if self.ndc_ray:\n W, H = self.img_wh\n rays_o, rays_d = ndc_rays_blender(\n H, W, self.focal[0], 1.0, rays_o, rays_d\n )\n rays = torch.cat([rays_o, rays_d], 1) # (h*w, 6)\n rays_all.append(rays)\n return rays_all, torch.FloatTensor(val_times)","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render_video","uri":"program://EfficientDynamic3DGaussian/module/render_video#L1-L66","kind":"module","name":"render_video","path":"render_video.py","language":"python","start_line":1,"end_line":66,"context_start_line":1,"context_end_line":66,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\nimport imageio\nimport numpy as np\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n model_path = dataset.model_path\n iteration = scene.loaded_iter\n\n render_path = os.path.join(model_path, \"path.mp4\")\n\n views = scene.getVisCameras()\n rendering_list = []\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n if type(view) is list:\n view = view[0]\n rendering = render(view, gaussians, pipeline, background)[\"render\"]\n rendering_list.append((255*np.clip(rendering.cpu().numpy(),0,1)).astype(np.uint8).transpose(1, 2, 0))\n\n print(rendering_list[0].shape)\n imageio.mimwrite(render_path, rendering_list)\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Testing script parameters\")\n model = ModelParams(parser, sentinel=True)\n pipeline = PipelineParams(parser)\n parser.add_argument(\"--iteration\", default=-1, type=int)\n parser.add_argument(\"--skip_train\", action=\"store_true\")\n parser.add_argument(\"--skip_test\", action=\"store_true\")\n parser.add_argument(\"--quiet\", action=\"store_true\")\n args = get_combined_args(parser)\n print(\"Rendering \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)","source_hash":"70a7eacbb8ed3a2576771f239b75104d7d6fd91cc271fe12cb97fea4b7002771","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render_video.render_sets","uri":"program://EfficientDynamic3DGaussian/function/render_video.render_sets#L27-L49","kind":"function","name":"render_sets","path":"render_video.py","language":"python","start_line":27,"end_line":49,"context_start_line":7,"context_end_line":66,"code":"# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\nimport imageio\nimport numpy as np\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n model_path = dataset.model_path\n iteration = scene.loaded_iter\n\n render_path = os.path.join(model_path, \"path.mp4\")\n\n views = scene.getVisCameras()\n rendering_list = []\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n if type(view) is list:\n view = view[0]\n rendering = render(view, gaussians, pipeline, background)[\"render\"]\n rendering_list.append((255*np.clip(rendering.cpu().numpy(),0,1)).astype(np.uint8).transpose(1, 2, 0))\n\n print(rendering_list[0].shape)\n imageio.mimwrite(render_path, rendering_list)\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Testing script parameters\")\n model = ModelParams(parser, sentinel=True)\n pipeline = PipelineParams(parser)\n parser.add_argument(\"--iteration\", default=-1, type=int)\n parser.add_argument(\"--skip_train\", action=\"store_true\")\n parser.add_argument(\"--skip_test\", action=\"store_true\")\n parser.add_argument(\"--quiet\", action=\"store_true\")\n args = get_combined_args(parser)\n print(\"Rendering \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)","source_hash":"70a7eacbb8ed3a2576771f239b75104d7d6fd91cc271fe12cb97fea4b7002771","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:metrics","uri":"program://EfficientDynamic3DGaussian/module/metrics#L1-L114","kind":"module","name":"metrics","path":"metrics.py","language":"python","start_line":1,"end_line":114,"context_start_line":1,"context_end_line":114,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom pathlib import Path\nimport os\nfrom PIL import Image\nimport torch\nimport torchvision.transforms.functional as tf\nfrom utils.loss_utils import ssim, msssim\nfrom lpipsPyTorch import lpips_helper\nimport json\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser\n\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\ndef readImages(renders_dir, gt_dir):\n renders = []\n gts = []\n image_names = []\n for fname in os.listdir(renders_dir):\n render = Image.open(renders_dir / fname)\n gt = Image.open(gt_dir / fname)\n renders.append(tf.to_tensor(render).unsqueeze(0)[:, :3, :, :].cuda())\n gts.append(tf.to_tensor(gt).unsqueeze(0)[:, :3, :, :].cuda())\n image_names.append(fname)\n return renders, gts, image_names\n\ndef evaluate(model_paths):\n\n full_dict = {}\n per_view_dict = {}\n full_dict_polytopeonly = {}\n per_view_dict_polytopeonly = {}\n print(\"\")\n\n lpips = lpips_helper(net_type='vgg')\n for scene_dir in model_paths:\n try:\n print(\"Scene:\", scene_dir)\n full_dict[scene_dir] = {}\n per_view_dict[scene_dir] = {}\n full_dict_polytopeonly[scene_dir] = {}\n per_view_dict_polytopeonly[scene_dir] = {}\n\n test_dir = Path(scene_dir) / \"test\"\n\n for method in os.listdir(test_dir):\n print(\"Method:\", method)\n\n full_dict[scene_dir][method] = {}\n per_view_dict[scene_dir][method] = {}\n full_dict_polytopeonly[scene_dir][method] = {}\n per_view_dict_polytopeonly[scene_dir][method] = {}\n\n method_dir = test_dir / method\n gt_dir = method_dir/ \"gt\"\n renders_dir = method_dir / \"renders\"\n renders, gts, image_names = readImages(renders_dir, gt_dir)\n\n ssims = []\n psnrs = []\n lpipss = []\n msssims = []\n\n for idx in tqdm(range(len(renders)), desc=\"Metric evaluation progress\"):\n ssims.append(ssim(renders[idx], gts[idx]))\n msssims.append(msssim(renders[idx], gts[idx]))\n psnrs.append(psnr(renders[idx], gts[idx]))\n lpipss.append(lpips(renders[idx], gts[idx]))\n\n print(\" SSIM : {:>12.7f}\".format(torch.tensor(ssims).mean(), \".5\"))\n print(\" MS-SSIM: {:>12.7f}\".format(torch.tensor(msssims).mean(), \".5\"))\n print(\" PSNR : {:>12.7f}\".format(torch.tensor(psnrs).mean(), \".5\"))\n print(\" LPIPS : {:>12.7f}\".format(torch.tensor(lpipss).mean(), \".5\"))\n print(\"\")\n\n full_dict[scene_dir][method].update({\"SSIM\": torch.tensor(ssims).mean().item(),\n \"MS-SSIM\": torch.tensor(msssims).mean().item(),\n \"PSNR\": torch.tensor(psnrs).mean().item(),\n \"LPIPS\": torch.tensor(lpipss).mean().item()})\n per_view_dict[scene_dir][method].update({\"SSIM\": {name: ssim for ssim, name in zip(torch.tensor(ssims).tolist(), image_names)},\n \"MS-SSIM\": {name: ssim for ssim, name in zip(torch.tensor(msssims).tolist(), image_names)},\n \"PSNR\": {name: psnr for psnr, name in zip(torch.tensor(psnrs).tolist(), image_names)},\n \"LPIPS\": {name: lp for lp, name in zip(torch.tensor(lpipss).tolist(), image_names)}})\n\n with open(scene_dir + \"/results.json\", 'w') as fp:\n json.dump(full_dict[scene_dir], fp, indent=True)\n with open(scene_dir + \"/per_view.json\", 'w') as fp:\n json.dump(per_view_dict[scene_dir], fp, indent=True)\n except Exception as e:\n print(e)\n print(\"Unable to compute metrics for model\", scene_dir)\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda:0\")\n torch.cuda.set_device(device)\n\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Training script parameters\")\n parser.add_argument('--model_paths', '-m', required=True, nargs=\"+\", type=str, default=[])\n args = parser.parse_args()\n evaluate(args.model_paths)","source_hash":"4a7702c2632eed4fdf5c0d856ec269eb6d8a120343ef2da57c56ed3da688fbbc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:metrics.readImages","uri":"program://EfficientDynamic3DGaussian/function/metrics.readImages#L28-L38","kind":"function","name":"readImages","path":"metrics.py","language":"python","start_line":28,"end_line":38,"context_start_line":8,"context_end_line":58,"code":"#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom pathlib import Path\nimport os\nfrom PIL import Image\nimport torch\nimport torchvision.transforms.functional as tf\nfrom utils.loss_utils import ssim, msssim\nfrom lpipsPyTorch import lpips_helper\nimport json\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser\n\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\ndef readImages(renders_dir, gt_dir):\n renders = []\n gts = []\n image_names = []\n for fname in os.listdir(renders_dir):\n render = Image.open(renders_dir / fname)\n gt = Image.open(gt_dir / fname)\n renders.append(tf.to_tensor(render).unsqueeze(0)[:, :3, :, :].cuda())\n gts.append(tf.to_tensor(gt).unsqueeze(0)[:, :3, :, :].cuda())\n image_names.append(fname)\n return renders, gts, image_names\n\ndef evaluate(model_paths):\n\n full_dict = {}\n per_view_dict = {}\n full_dict_polytopeonly = {}\n per_view_dict_polytopeonly = {}\n print(\"\")\n\n lpips = lpips_helper(net_type='vgg')\n for scene_dir in model_paths:\n try:\n print(\"Scene:\", scene_dir)\n full_dict[scene_dir] = {}\n per_view_dict[scene_dir] = {}\n full_dict_polytopeonly[scene_dir] = {}\n per_view_dict_polytopeonly[scene_dir] = {}\n\n test_dir = Path(scene_dir) / \"test\"\n","source_hash":"4a7702c2632eed4fdf5c0d856ec269eb6d8a120343ef2da57c56ed3da688fbbc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:metrics.evaluate","uri":"program://EfficientDynamic3DGaussian/function/metrics.evaluate#L40-L104","kind":"function","name":"evaluate","path":"metrics.py","language":"python","start_line":40,"end_line":104,"context_start_line":20,"context_end_line":114,"code":"from tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser\n\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\ndef readImages(renders_dir, gt_dir):\n renders = []\n gts = []\n image_names = []\n for fname in os.listdir(renders_dir):\n render = Image.open(renders_dir / fname)\n gt = Image.open(gt_dir / fname)\n renders.append(tf.to_tensor(render).unsqueeze(0)[:, :3, :, :].cuda())\n gts.append(tf.to_tensor(gt).unsqueeze(0)[:, :3, :, :].cuda())\n image_names.append(fname)\n return renders, gts, image_names\n\ndef evaluate(model_paths):\n\n full_dict = {}\n per_view_dict = {}\n full_dict_polytopeonly = {}\n per_view_dict_polytopeonly = {}\n print(\"\")\n\n lpips = lpips_helper(net_type='vgg')\n for scene_dir in model_paths:\n try:\n print(\"Scene:\", scene_dir)\n full_dict[scene_dir] = {}\n per_view_dict[scene_dir] = {}\n full_dict_polytopeonly[scene_dir] = {}\n per_view_dict_polytopeonly[scene_dir] = {}\n\n test_dir = Path(scene_dir) / \"test\"\n\n for method in os.listdir(test_dir):\n print(\"Method:\", method)\n\n full_dict[scene_dir][method] = {}\n per_view_dict[scene_dir][method] = {}\n full_dict_polytopeonly[scene_dir][method] = {}\n per_view_dict_polytopeonly[scene_dir][method] = {}\n\n method_dir = test_dir / method\n gt_dir = method_dir/ \"gt\"\n renders_dir = method_dir / \"renders\"\n renders, gts, image_names = readImages(renders_dir, gt_dir)\n\n ssims = []\n psnrs = []\n lpipss = []\n msssims = []\n\n for idx in tqdm(range(len(renders)), desc=\"Metric evaluation progress\"):\n ssims.append(ssim(renders[idx], gts[idx]))\n msssims.append(msssim(renders[idx], gts[idx]))\n psnrs.append(psnr(renders[idx], gts[idx]))\n lpipss.append(lpips(renders[idx], gts[idx]))\n\n print(\" SSIM : {:>12.7f}\".format(torch.tensor(ssims).mean(), \".5\"))\n print(\" MS-SSIM: {:>12.7f}\".format(torch.tensor(msssims).mean(), \".5\"))\n print(\" PSNR : {:>12.7f}\".format(torch.tensor(psnrs).mean(), \".5\"))\n print(\" LPIPS : {:>12.7f}\".format(torch.tensor(lpipss).mean(), \".5\"))\n print(\"\")\n\n full_dict[scene_dir][method].update({\"SSIM\": torch.tensor(ssims).mean().item(),\n \"MS-SSIM\": torch.tensor(msssims).mean().item(),\n \"PSNR\": torch.tensor(psnrs).mean().item(),\n \"LPIPS\": torch.tensor(lpipss).mean().item()})\n per_view_dict[scene_dir][method].update({\"SSIM\": {name: ssim for ssim, name in zip(torch.tensor(ssims).tolist(), image_names)},\n \"MS-SSIM\": {name: ssim for ssim, name in zip(torch.tensor(msssims).tolist(), image_names)},\n \"PSNR\": {name: psnr for psnr, name in zip(torch.tensor(psnrs).tolist(), image_names)},\n \"LPIPS\": {name: lp for lp, name in zip(torch.tensor(lpipss).tolist(), image_names)}})\n\n with open(scene_dir + \"/results.json\", 'w') as fp:\n json.dump(full_dict[scene_dir], fp, indent=True)\n with open(scene_dir + \"/per_view.json\", 'w') as fp:\n json.dump(per_view_dict[scene_dir], fp, indent=True)\n except Exception as e:\n print(e)\n print(\"Unable to compute metrics for model\", scene_dir)\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda:0\")\n torch.cuda.set_device(device)\n\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Training script parameters\")\n parser.add_argument('--model_paths', '-m', required=True, nargs=\"+\", type=str, default=[])\n args = parser.parse_args()\n evaluate(args.model_paths)","source_hash":"4a7702c2632eed4fdf5c0d856ec269eb6d8a120343ef2da57c56ed3da688fbbc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render_flow","uri":"program://EfficientDynamic3DGaussian/module/render_flow#L1-L99","kind":"module","name":"render_flow","path":"render_flow.py","language":"python","start_line":1,"end_line":99,"context_start_line":1,"context_end_line":99,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render_flow\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom utils import flow_viz\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\nimport cv2 as cv\nimport numpy as np\n\ndef render_set(model_path, name, iteration, views, gaussians, pipeline, background, time_delta):\n render_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"flow\")\n gts_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"gt\")\n\n makedirs(render_path, exist_ok=True)\n makedirs(gts_path, exist_ok=True)\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n if type(view) is list:\n view = view[0]\n rendering = render_flow(view, gaussians, pipeline, background, time_delta=time_delta)[\"render\"]\n # print(view.world_view_transform)\n tx, ty, tz = view.world_view_transform[3, :3]\n # print(tx, ty, tz)\n # print(rendering.shape) \n # flow = rendering.permute(1, 2, 0) @ torch.from_numpy(np.array([[1, 0, -tx/tz], [0, 1, -ty/tz]])).float().T.cuda()\n flow = rendering.permute(1, 2, 0) @ torch.from_numpy(np.array([[1, 0, 0], [0, 1, 0]])).float().T.cuda()\n flow = flow.cpu().numpy()\n # flow[..., 0] *= 1024\n # flow[..., 1] *= 1386\n # print(flow.mean(axis=(0, 1)), flow.std(axis=(0, 1)))\n # for i in range(20):\n # print(flow[40*i:40*(i+1)].mean(axis=(0, 1)))\n\n gt = view.original_image[0:3, :, :]\n # hsv = np.zeros((gt.shape[1], gt.shape[2], 3), dtype=np.uint8)\n # hsv[..., 1] = 255\n # mag, ang = cv.cartToPolar(flow[..., 0], flow[..., 1])\n # hsv[..., 0] = ang*180/np.pi/2\n # hsv[..., 2] = cv.normalize(mag, None, 0, 255, cv.NORM_MINMAX)\n # bgr = cv.cvtColor(hsv, cv.COLOR_HSV2RGB)\n\n bgr = flow_viz.flow_to_image(flow)\n bgr = torch.from_numpy(bgr).permute(2, 0, 1).float()/255\n\n torchvision.utils.save_image(bgr, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n if not skip_train:\n if scene.use_loader:\n views = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=False, num_workers=16, collate_fn=list)\n else:\n views = scene.getTrainCameras()\n\n render_set(dataset.model_path, \"train\", scene.loaded_iter, views, gaussians, pipeline, background, scene.time_delta)\n\n if not skip_test:\n render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background, scene.time_delta)\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Testing script parameters\")\n model = ModelParams(parser, sentinel=True)\n pipeline = PipelineParams(parser)\n parser.add_argument(\"--iteration\", default=-1, type=int)\n parser.add_argument(\"--skip_train\", action=\"store_true\")\n parser.add_argument(\"--skip_test\", action=\"store_true\")\n parser.add_argument(\"--quiet\", action=\"store_true\")\n args = get_combined_args(parser)\n print(\"Rendering \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)","source_hash":"0828d19a18547188c42e9b4093cf65483d9c60b5bbaf72c03af3a26c8fe13f5e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render_flow.render_set","uri":"program://EfficientDynamic3DGaussian/function/render_flow.render_set#L28-L63","kind":"function","name":"render_set","path":"render_flow.py","language":"python","start_line":28,"end_line":63,"context_start_line":8,"context_end_line":83,"code":"#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render_flow\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom utils import flow_viz\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\nimport cv2 as cv\nimport numpy as np\n\ndef render_set(model_path, name, iteration, views, gaussians, pipeline, background, time_delta):\n render_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"flow\")\n gts_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"gt\")\n\n makedirs(render_path, exist_ok=True)\n makedirs(gts_path, exist_ok=True)\n for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n if type(view) is list:\n view = view[0]\n rendering = render_flow(view, gaussians, pipeline, background, time_delta=time_delta)[\"render\"]\n # print(view.world_view_transform)\n tx, ty, tz = view.world_view_transform[3, :3]\n # print(tx, ty, tz)\n # print(rendering.shape) \n # flow = rendering.permute(1, 2, 0) @ torch.from_numpy(np.array([[1, 0, -tx/tz], [0, 1, -ty/tz]])).float().T.cuda()\n flow = rendering.permute(1, 2, 0) @ torch.from_numpy(np.array([[1, 0, 0], [0, 1, 0]])).float().T.cuda()\n flow = flow.cpu().numpy()\n # flow[..., 0] *= 1024\n # flow[..., 1] *= 1386\n # print(flow.mean(axis=(0, 1)), flow.std(axis=(0, 1)))\n # for i in range(20):\n # print(flow[40*i:40*(i+1)].mean(axis=(0, 1)))\n\n gt = view.original_image[0:3, :, :]\n # hsv = np.zeros((gt.shape[1], gt.shape[2], 3), dtype=np.uint8)\n # hsv[..., 1] = 255\n # mag, ang = cv.cartToPolar(flow[..., 0], flow[..., 1])\n # hsv[..., 0] = ang*180/np.pi/2\n # hsv[..., 2] = cv.normalize(mag, None, 0, 255, cv.NORM_MINMAX)\n # bgr = cv.cvtColor(hsv, cv.COLOR_HSV2RGB)\n\n bgr = flow_viz.flow_to_image(flow)\n bgr = torch.from_numpy(bgr).permute(2, 0, 1).float()/255\n\n torchvision.utils.save_image(bgr, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n if not skip_train:\n if scene.use_loader:\n views = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=False, num_workers=16, collate_fn=list)\n else:\n views = scene.getTrainCameras()\n\n render_set(dataset.model_path, \"train\", scene.loaded_iter, views, gaussians, pipeline, background, scene.time_delta)\n\n if not skip_test:\n render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background, scene.time_delta)\n","source_hash":"0828d19a18547188c42e9b4093cf65483d9c60b5bbaf72c03af3a26c8fe13f5e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:render_flow.render_sets","uri":"program://EfficientDynamic3DGaussian/function/render_flow.render_sets#L65-L82","kind":"function","name":"render_sets","path":"render_flow.py","language":"python","start_line":65,"end_line":82,"context_start_line":45,"context_end_line":99,"code":" # flow[..., 0] *= 1024\n # flow[..., 1] *= 1386\n # print(flow.mean(axis=(0, 1)), flow.std(axis=(0, 1)))\n # for i in range(20):\n # print(flow[40*i:40*(i+1)].mean(axis=(0, 1)))\n\n gt = view.original_image[0:3, :, :]\n # hsv = np.zeros((gt.shape[1], gt.shape[2], 3), dtype=np.uint8)\n # hsv[..., 1] = 255\n # mag, ang = cv.cartToPolar(flow[..., 0], flow[..., 1])\n # hsv[..., 0] = ang*180/np.pi/2\n # hsv[..., 2] = cv.normalize(mag, None, 0, 255, cv.NORM_MINMAX)\n # bgr = cv.cvtColor(hsv, cv.COLOR_HSV2RGB)\n\n bgr = flow_viz.flow_to_image(flow)\n bgr = torch.from_numpy(bgr).permute(2, 0, 1).float()/255\n\n torchvision.utils.save_image(bgr, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):\n with torch.no_grad():\n gaussians = GaussianModel(dataset.sh_degree, dataset.approx_l)\n scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n if not skip_train:\n if scene.use_loader:\n views = DataLoader(scene.getTrainCameras(), batch_size=1, shuffle=False, num_workers=16, collate_fn=list)\n else:\n views = scene.getTrainCameras()\n\n render_set(dataset.model_path, \"train\", scene.loaded_iter, views, gaussians, pipeline, background, scene.time_delta)\n\n if not skip_test:\n render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background, scene.time_delta)\n\nif __name__ == \"__main__\":\n # Set up command line argument parser\n parser = ArgumentParser(description=\"Testing script parameters\")\n model = ModelParams(parser, sentinel=True)\n pipeline = PipelineParams(parser)\n parser.add_argument(\"--iteration\", default=-1, type=int)\n parser.add_argument(\"--skip_train\", action=\"store_true\")\n parser.add_argument(\"--skip_test\", action=\"store_true\")\n parser.add_argument(\"--quiet\", action=\"store_true\")\n args = get_combined_args(parser)\n print(\"Rendering \" + args.model_path)\n\n # Initialize system state (RNG)\n safe_state(args.quiet)\n\n render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)","source_hash":"0828d19a18547188c42e9b4093cf65483d9c60b5bbaf72c03af3a26c8fe13f5e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader","uri":"program://EfficientDynamic3DGaussian/module/scene.colmap_loader#L1-L294","kind":"module","name":"scene.colmap_loader","path":"scene/colmap_loader.py","language":"python","start_line":1,"end_line":294,"context_start_line":1,"context_end_line":294,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport numpy as np\nimport collections\nimport struct\n\nCameraModel = collections.namedtuple(\n \"CameraModel\", [\"model_id\", \"model_name\", \"num_params\"])\nCamera = collections.namedtuple(\n \"Camera\", [\"id\", \"model\", \"width\", \"height\", \"params\"])\nBaseImage = collections.namedtuple(\n \"Image\", [\"id\", \"qvec\", \"tvec\", \"camera_id\", \"name\", \"xys\", \"point3D_ids\"])\nPoint3D = collections.namedtuple(\n \"Point3D\", [\"id\", \"xyz\", \"rgb\", \"error\", \"image_ids\", \"point2D_idxs\"])\nCAMERA_MODELS = {\n CameraModel(model_id=0, model_name=\"SIMPLE_PINHOLE\", num_params=3),\n CameraModel(model_id=1, model_name=\"PINHOLE\", num_params=4),\n CameraModel(model_id=2, model_name=\"SIMPLE_RADIAL\", num_params=4),\n CameraModel(model_id=3, model_name=\"RADIAL\", num_params=5),\n CameraModel(model_id=4, model_name=\"OPENCV\", num_params=8),\n CameraModel(model_id=5, model_name=\"OPENCV_FISHEYE\", num_params=8),\n CameraModel(model_id=6, model_name=\"FULL_OPENCV\", num_params=12),\n CameraModel(model_id=7, model_name=\"FOV\", num_params=5),\n CameraModel(model_id=8, model_name=\"SIMPLE_RADIAL_FISHEYE\", num_params=4),\n CameraModel(model_id=9, model_name=\"RADIAL_FISHEYE\", num_params=5),\n CameraModel(model_id=10, model_name=\"THIN_PRISM_FISHEYE\", num_params=12)\n}\nCAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model)\n for camera_model in CAMERA_MODELS])\nCAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model)\n for camera_model in CAMERA_MODELS])\n\n\ndef qvec2rotmat(qvec):\n return np.array([\n [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,\n 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, <, >, !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None\n errors = None\n num_points = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n num_points += 1\n\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n count = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n xyz = np.array(tuple(map(float, elems[1:4])))\n rgb = np.array(tuple(map(int, elems[4:7])))\n error = np.array(float(elems[7]))\n xyzs[count] = xyz\n rgbs[count] = rgb\n errors[count] = error\n count += 1\n\n return xyzs, rgbs, errors\n\ndef read_points3D_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DBinary(const std::string& path)\n void Reconstruction::WritePoints3DBinary(const std::string& path)\n \"\"\"\n\n\n with open(path_to_model_file, \"rb\") as fid:\n num_points = read_next_bytes(fid, 8, \"Q\")[0]\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n\n for p_id in range(num_points):\n binary_point_line_properties = read_next_bytes(\n fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n xyz = np.array(binary_point_line_properties[1:4])\n rgb = np.array(binary_point_line_properties[4:7])\n error = np.array(binary_point_line_properties[7])\n track_length = read_next_bytes(\n fid, num_bytes=8, format_char_sequence=\"Q\")[0]\n track_elems = read_next_bytes(\n fid, num_bytes=8*track_length,\n format_char_sequence=\"ii\"*track_length)\n xyzs[p_id] = xyz\n rgbs[p_id] = rgb\n errors[p_id] = error\n return xyzs, rgbs, errors\n\ndef read_intrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n cameras = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n camera_id = int(elems[0])\n model = elems[1]\n assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n width = int(elems[2])\n height = int(elems[3])\n params = np.array(tuple(map(float, elems[4:])))\n cameras[camera_id] = Camera(id=camera_id, model=model,\n width=width, height=height,\n params=params)\n return cameras\n\ndef read_extrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadImagesBinary(const std::string& path)\n void Reconstruction::WriteImagesBinary(const std::string& path)\n \"\"\"\n images = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_reg_images):\n binary_image_properties = read_next_bytes(\n fid, num_bytes=64, format_char_sequence=\"idddddddi\")\n image_id = binary_image_properties[0]\n qvec = np.array(binary_image_properties[1:5])\n tvec = np.array(binary_image_properties[5:8])\n camera_id = binary_image_properties[8]\n image_name = \"\"\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n while current_char != b\"\\x00\": # look for the ASCII 0 entry\n image_name += current_char.decode(\"utf-8\")\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n num_points2D = read_next_bytes(fid, num_bytes=8,\n format_char_sequence=\"Q\")[0]\n x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,\n format_char_sequence=\"ddq\"*num_points2D)\n xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),\n tuple(map(float, x_y_id_s[1::3]))])\n point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images\n\n\ndef read_intrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::WriteCamerasBinary(const std::string& path)\n void Reconstruction::ReadCamerasBinary(const std::string& path)\n \"\"\"\n cameras = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_cameras):\n camera_properties = read_next_bytes(\n fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n camera_id = camera_properties[0]\n model_id = camera_properties[1]\n model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n width = camera_properties[2]\n height = camera_properties[3]\n num_params = CAMERA_MODEL_IDS[model_id].num_params\n params = read_next_bytes(fid, num_bytes=8*num_params,\n format_char_sequence=\"d\"*num_params)\n cameras[camera_id] = Camera(id=camera_id,\n model=model_name,\n width=width,\n height=height,\n params=np.array(params))\n assert len(cameras) == num_cameras\n return cameras\n\n\ndef read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n image_id = int(elems[0])\n qvec = np.array(tuple(map(float, elems[1:5])))\n tvec = np.array(tuple(map(float, elems[5:8])))\n camera_id = int(elems[8])\n image_name = elems[9]\n elems = fid.readline().split()\n xys = np.column_stack([tuple(map(float, elems[0::3])),\n tuple(map(float, elems[1::3]))])\n point3D_ids = np.array(tuple(map(int, elems[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images\n\n\ndef read_colmap_bin_array(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py\n\n :param path: path to the colmap binary file.\n :return: nd array with the floating point values in the value\n \"\"\"\n with open(path, \"rb\") as fid:\n width, height, channels = np.genfromtxt(fid, delimiter=\"&\", max_rows=1,\n usecols=(0, 1, 2), dtype=int)\n fid.seek(0)\n num_delimiter = 0\n byte = fid.read(1)\n while True:\n if byte == b\"&\":\n num_delimiter += 1\n if num_delimiter >= 3:\n break\n byte = fid.read(1)\n array = np.fromfile(fid, np.float32)\n array = array.reshape((width, height, channels), order=\"F\")\n return np.transpose(array, (1, 0, 2)).squeeze()","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.qvec2rotmat","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.qvec2rotmat#L69-L70","kind":"function","name":"qvec2rotmat","path":"scene/colmap_loader.py","language":"python","start_line":69,"end_line":70,"context_start_line":49,"context_end_line":90,"code":" 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, <, >, !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.rotmat2qvec","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.rotmat2qvec#L55-L66","kind":"function","name":"rotmat2qvec","path":"scene/colmap_loader.py","language":"python","start_line":55,"end_line":66,"context_start_line":35,"context_end_line":86,"code":" CameraModel(model_id=10, model_name=\"THIN_PRISM_FISHEYE\", num_params=12)\n}\nCAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model)\n for camera_model in CAMERA_MODELS])\nCAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model)\n for camera_model in CAMERA_MODELS])\n\n\ndef qvec2rotmat(qvec):\n return np.array([\n [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,\n 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, <, >, !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.Image","uri":"program://EfficientDynamic3DGaussian/class/scene.colmap_loader.Image#L68-L70","kind":"class","name":"Image","path":"scene/colmap_loader.py","language":"python","start_line":68,"end_line":70,"context_start_line":48,"context_end_line":90,"code":" [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, <, >, !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_next_bytes","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_next_bytes#L72-L81","kind":"function","name":"read_next_bytes","path":"scene/colmap_loader.py","language":"python","start_line":72,"end_line":81,"context_start_line":52,"context_end_line":101,"code":" 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, <, >, !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None\n errors = None\n num_points = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n num_points += 1\n","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_points3D_text","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_points3D_text#L83-L123","kind":"function","name":"read_points3D_text","path":"scene/colmap_loader.py","language":"python","start_line":83,"end_line":123,"context_start_line":63,"context_end_line":143,"code":" qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, <, >, !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None\n errors = None\n num_points = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n num_points += 1\n\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n count = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n xyz = np.array(tuple(map(float, elems[1:4])))\n rgb = np.array(tuple(map(int, elems[4:7])))\n error = np.array(float(elems[7]))\n xyzs[count] = xyz\n rgbs[count] = rgb\n errors[count] = error\n count += 1\n\n return xyzs, rgbs, errors\n\ndef read_points3D_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DBinary(const std::string& path)\n void Reconstruction::WritePoints3DBinary(const std::string& path)\n \"\"\"\n\n\n with open(path_to_model_file, \"rb\") as fid:\n num_points = read_next_bytes(fid, 8, \"Q\")[0]\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n\n for p_id in range(num_points):\n binary_point_line_properties = read_next_bytes(\n fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n xyz = np.array(binary_point_line_properties[1:4])","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_points3D_binary","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_points3D_binary#L125-L154","kind":"function","name":"read_points3D_binary","path":"scene/colmap_loader.py","language":"python","start_line":125,"end_line":154,"context_start_line":105,"context_end_line":174,"code":" errors = np.empty((num_points, 1))\n count = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n xyz = np.array(tuple(map(float, elems[1:4])))\n rgb = np.array(tuple(map(int, elems[4:7])))\n error = np.array(float(elems[7]))\n xyzs[count] = xyz\n rgbs[count] = rgb\n errors[count] = error\n count += 1\n\n return xyzs, rgbs, errors\n\ndef read_points3D_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DBinary(const std::string& path)\n void Reconstruction::WritePoints3DBinary(const std::string& path)\n \"\"\"\n\n\n with open(path_to_model_file, \"rb\") as fid:\n num_points = read_next_bytes(fid, 8, \"Q\")[0]\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n\n for p_id in range(num_points):\n binary_point_line_properties = read_next_bytes(\n fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n xyz = np.array(binary_point_line_properties[1:4])\n rgb = np.array(binary_point_line_properties[4:7])\n error = np.array(binary_point_line_properties[7])\n track_length = read_next_bytes(\n fid, num_bytes=8, format_char_sequence=\"Q\")[0]\n track_elems = read_next_bytes(\n fid, num_bytes=8*track_length,\n format_char_sequence=\"ii\"*track_length)\n xyzs[p_id] = xyz\n rgbs[p_id] = rgb\n errors[p_id] = error\n return xyzs, rgbs, errors\n\ndef read_intrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n cameras = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n camera_id = int(elems[0])\n model = elems[1]\n assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n width = int(elems[2])\n height = int(elems[3])\n params = np.array(tuple(map(float, elems[4:])))","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_intrinsics_text","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_intrinsics_text#L156-L178","kind":"function","name":"read_intrinsics_text","path":"scene/colmap_loader.py","language":"python","start_line":156,"end_line":178,"context_start_line":136,"context_end_line":198,"code":" xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n\n for p_id in range(num_points):\n binary_point_line_properties = read_next_bytes(\n fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n xyz = np.array(binary_point_line_properties[1:4])\n rgb = np.array(binary_point_line_properties[4:7])\n error = np.array(binary_point_line_properties[7])\n track_length = read_next_bytes(\n fid, num_bytes=8, format_char_sequence=\"Q\")[0]\n track_elems = read_next_bytes(\n fid, num_bytes=8*track_length,\n format_char_sequence=\"ii\"*track_length)\n xyzs[p_id] = xyz\n rgbs[p_id] = rgb\n errors[p_id] = error\n return xyzs, rgbs, errors\n\ndef read_intrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n cameras = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n camera_id = int(elems[0])\n model = elems[1]\n assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n width = int(elems[2])\n height = int(elems[3])\n params = np.array(tuple(map(float, elems[4:])))\n cameras[camera_id] = Camera(id=camera_id, model=model,\n width=width, height=height,\n params=params)\n return cameras\n\ndef read_extrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadImagesBinary(const std::string& path)\n void Reconstruction::WriteImagesBinary(const std::string& path)\n \"\"\"\n images = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_reg_images):\n binary_image_properties = read_next_bytes(\n fid, num_bytes=64, format_char_sequence=\"idddddddi\")\n image_id = binary_image_properties[0]\n qvec = np.array(binary_image_properties[1:5])\n tvec = np.array(binary_image_properties[5:8])\n camera_id = binary_image_properties[8]\n image_name = \"\"\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n while current_char != b\"\\x00\": # look for the ASCII 0 entry","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_extrinsics_binary","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_extrinsics_binary#L180-L212","kind":"function","name":"read_extrinsics_binary","path":"scene/colmap_loader.py","language":"python","start_line":180,"end_line":212,"context_start_line":160,"context_end_line":232,"code":" cameras = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n camera_id = int(elems[0])\n model = elems[1]\n assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n width = int(elems[2])\n height = int(elems[3])\n params = np.array(tuple(map(float, elems[4:])))\n cameras[camera_id] = Camera(id=camera_id, model=model,\n width=width, height=height,\n params=params)\n return cameras\n\ndef read_extrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadImagesBinary(const std::string& path)\n void Reconstruction::WriteImagesBinary(const std::string& path)\n \"\"\"\n images = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_reg_images):\n binary_image_properties = read_next_bytes(\n fid, num_bytes=64, format_char_sequence=\"idddddddi\")\n image_id = binary_image_properties[0]\n qvec = np.array(binary_image_properties[1:5])\n tvec = np.array(binary_image_properties[5:8])\n camera_id = binary_image_properties[8]\n image_name = \"\"\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n while current_char != b\"\\x00\": # look for the ASCII 0 entry\n image_name += current_char.decode(\"utf-8\")\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n num_points2D = read_next_bytes(fid, num_bytes=8,\n format_char_sequence=\"Q\")[0]\n x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,\n format_char_sequence=\"ddq\"*num_points2D)\n xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),\n tuple(map(float, x_y_id_s[1::3]))])\n point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images\n\n\ndef read_intrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::WriteCamerasBinary(const std::string& path)\n void Reconstruction::ReadCamerasBinary(const std::string& path)\n \"\"\"\n cameras = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_cameras):\n camera_properties = read_next_bytes(\n fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n camera_id = camera_properties[0]\n model_id = camera_properties[1]\n model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n width = camera_properties[2]\n height = camera_properties[3]\n num_params = CAMERA_MODEL_IDS[model_id].num_params","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_intrinsics_binary","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_intrinsics_binary#L215-L241","kind":"function","name":"read_intrinsics_binary","path":"scene/colmap_loader.py","language":"python","start_line":215,"end_line":241,"context_start_line":195,"context_end_line":261,"code":" camera_id = binary_image_properties[8]\n image_name = \"\"\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n while current_char != b\"\\x00\": # look for the ASCII 0 entry\n image_name += current_char.decode(\"utf-8\")\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n num_points2D = read_next_bytes(fid, num_bytes=8,\n format_char_sequence=\"Q\")[0]\n x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,\n format_char_sequence=\"ddq\"*num_points2D)\n xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),\n tuple(map(float, x_y_id_s[1::3]))])\n point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images\n\n\ndef read_intrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::WriteCamerasBinary(const std::string& path)\n void Reconstruction::ReadCamerasBinary(const std::string& path)\n \"\"\"\n cameras = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_cameras):\n camera_properties = read_next_bytes(\n fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n camera_id = camera_properties[0]\n model_id = camera_properties[1]\n model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n width = camera_properties[2]\n height = camera_properties[3]\n num_params = CAMERA_MODEL_IDS[model_id].num_params\n params = read_next_bytes(fid, num_bytes=8*num_params,\n format_char_sequence=\"d\"*num_params)\n cameras[camera_id] = Camera(id=camera_id,\n model=model_name,\n width=width,\n height=height,\n params=np.array(params))\n assert len(cameras) == num_cameras\n return cameras\n\n\ndef read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n image_id = int(elems[0])\n qvec = np.array(tuple(map(float, elems[1:5])))\n tvec = np.array(tuple(map(float, elems[5:8])))\n camera_id = int(elems[8])\n image_name = elems[9]","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_extrinsics_text","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_extrinsics_text#L244-L270","kind":"function","name":"read_extrinsics_text","path":"scene/colmap_loader.py","language":"python","start_line":244,"end_line":270,"context_start_line":224,"context_end_line":290,"code":" for _ in range(num_cameras):\n camera_properties = read_next_bytes(\n fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n camera_id = camera_properties[0]\n model_id = camera_properties[1]\n model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n width = camera_properties[2]\n height = camera_properties[3]\n num_params = CAMERA_MODEL_IDS[model_id].num_params\n params = read_next_bytes(fid, num_bytes=8*num_params,\n format_char_sequence=\"d\"*num_params)\n cameras[camera_id] = Camera(id=camera_id,\n model=model_name,\n width=width,\n height=height,\n params=np.array(params))\n assert len(cameras) == num_cameras\n return cameras\n\n\ndef read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n image_id = int(elems[0])\n qvec = np.array(tuple(map(float, elems[1:5])))\n tvec = np.array(tuple(map(float, elems[5:8])))\n camera_id = int(elems[8])\n image_name = elems[9]\n elems = fid.readline().split()\n xys = np.column_stack([tuple(map(float, elems[0::3])),\n tuple(map(float, elems[1::3]))])\n point3D_ids = np.array(tuple(map(int, elems[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images\n\n\ndef read_colmap_bin_array(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py\n\n :param path: path to the colmap binary file.\n :return: nd array with the floating point values in the value\n \"\"\"\n with open(path, \"rb\") as fid:\n width, height, channels = np.genfromtxt(fid, delimiter=\"&\", max_rows=1,\n usecols=(0, 1, 2), dtype=int)\n fid.seek(0)\n num_delimiter = 0\n byte = fid.read(1)\n while True:\n if byte == b\"&\":\n num_delimiter += 1\n if num_delimiter >= 3:\n break","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.colmap_loader.read_colmap_bin_array","uri":"program://EfficientDynamic3DGaussian/function/scene.colmap_loader.read_colmap_bin_array#L273-L294","kind":"function","name":"read_colmap_bin_array","path":"scene/colmap_loader.py","language":"python","start_line":273,"end_line":294,"context_start_line":253,"context_end_line":294,"code":" break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n image_id = int(elems[0])\n qvec = np.array(tuple(map(float, elems[1:5])))\n tvec = np.array(tuple(map(float, elems[5:8])))\n camera_id = int(elems[8])\n image_name = elems[9]\n elems = fid.readline().split()\n xys = np.column_stack([tuple(map(float, elems[0::3])),\n tuple(map(float, elems[1::3]))])\n point3D_ids = np.array(tuple(map(int, elems[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images\n\n\ndef read_colmap_bin_array(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py\n\n :param path: path to the colmap binary file.\n :return: nd array with the floating point values in the value\n \"\"\"\n with open(path, \"rb\") as fid:\n width, height, channels = np.genfromtxt(fid, delimiter=\"&\", max_rows=1,\n usecols=(0, 1, 2), dtype=int)\n fid.seek(0)\n num_delimiter = 0\n byte = fid.read(1)\n while True:\n if byte == b\"&\":\n num_delimiter += 1\n if num_delimiter >= 3:\n break\n byte = fid.read(1)\n array = np.fromfile(fid, np.float32)\n array = array.reshape((width, height, channels), order=\"F\")\n return np.transpose(array, (1, 0, 2)).squeeze()","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.cameras","uri":"program://EfficientDynamic3DGaussian/module/scene.cameras#L1-L116","kind":"module","name":"scene.cameras","path":"scene/cameras.py","language":"python","start_line":1,"end_line":116,"context_start_line":1,"context_end_line":116,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom utils.graphics_utils import getWorld2View2, getProjectionMatrix\n\nclass Camera(nn.Module):\n def __init__(self, colmap_id, R, T, FoVx, FoVy, image, gt_alpha_mask,\n image_name, uid, time=0,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n **kwargs):\n super(Camera, self).__init__()\n\n self.uid = uid\n self.colmap_id = colmap_id\n self.R = R\n self.T = T\n self.FoVx = FoVx\n self.FoVy = FoVy\n self.image_name = image_name\n self.time = time\n self.kwargs = kwargs\n\n try:\n self.data_device = torch.device(data_device)\n except Exception as e:\n print(e)\n print(f\"[Warning] Custom device {data_device} failed, fallback to default cuda device\" )\n self.data_device = torch.device(\"cuda\")\n\n self.original_image = image.clamp(0.0, 1.0) # .to(self.data_device)\n self.image_width = self.original_image.shape[2]\n self.image_height = self.original_image.shape[1]\n # self.image_width = 1386\n # self.image_height = 1014\n\n if gt_alpha_mask is not None:\n self.original_image *= gt_alpha_mask # .to(self.data_device)\n else:\n self.original_image *= torch.ones((1, self.image_height, self.image_width)) # , device=self.data_device)\n\n self.zfar = 100.0\n self.znear = 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\nclass Camera2(nn.Module):\n def __init__(self, colmap_id, R, T, FoVx, FoVy, width, height,\n uid, time=0,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n **kwargs):\n super(Camera2, self).__init__()\n\n self.uid = uid\n self.colmap_id = colmap_id\n self.R = R\n self.T = T\n self.FoVx = FoVx\n self.FoVy = FoVy\n self.time = time\n self.kwargs = kwargs\n\n try:\n self.data_device = torch.device(data_device)\n except Exception as e:\n print(e)\n print(f\"[Warning] Custom device {data_device} failed, fallback to default cuda device\" )\n self.data_device = torch.device(\"cuda\")\n\n self.image_width = width\n self.image_height = height\n\n\n self.zfar = 100.0\n self.znear = 10 # 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\n\n\n\nclass MiniCam:\n def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform):\n self.image_width = width\n self.image_height = height \n self.FoVy = fovy\n self.FoVx = fovx\n self.znear = znear\n self.zfar = zfar\n self.world_view_transform = world_view_transform\n self.full_proj_transform = full_proj_transform\n view_inv = torch.inverse(self.world_view_transform)\n self.camera_center = view_inv[3][:3]\n","source_hash":"69ccfa581123f12b32fb80056ddc850c630bf7fe3721c57e9e8c2c6beb20f5e9","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.cameras.Camera","uri":"program://EfficientDynamic3DGaussian/class/scene.cameras.Camera#L17-L61","kind":"class","name":"Camera","path":"scene/cameras.py","language":"python","start_line":17,"end_line":61,"context_start_line":1,"context_end_line":81,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom utils.graphics_utils import getWorld2View2, getProjectionMatrix\n\nclass Camera(nn.Module):\n def __init__(self, colmap_id, R, T, FoVx, FoVy, image, gt_alpha_mask,\n image_name, uid, time=0,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n **kwargs):\n super(Camera, self).__init__()\n\n self.uid = uid\n self.colmap_id = colmap_id\n self.R = R\n self.T = T\n self.FoVx = FoVx\n self.FoVy = FoVy\n self.image_name = image_name\n self.time = time\n self.kwargs = kwargs\n\n try:\n self.data_device = torch.device(data_device)\n except Exception as e:\n print(e)\n print(f\"[Warning] Custom device {data_device} failed, fallback to default cuda device\" )\n self.data_device = torch.device(\"cuda\")\n\n self.original_image = image.clamp(0.0, 1.0) # .to(self.data_device)\n self.image_width = self.original_image.shape[2]\n self.image_height = self.original_image.shape[1]\n # self.image_width = 1386\n # self.image_height = 1014\n\n if gt_alpha_mask is not None:\n self.original_image *= gt_alpha_mask # .to(self.data_device)\n else:\n self.original_image *= torch.ones((1, self.image_height, self.image_width)) # , device=self.data_device)\n\n self.zfar = 100.0\n self.znear = 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\nclass Camera2(nn.Module):\n def __init__(self, colmap_id, R, T, FoVx, FoVy, width, height,\n uid, time=0,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n **kwargs):\n super(Camera2, self).__init__()\n\n self.uid = uid\n self.colmap_id = colmap_id\n self.R = R\n self.T = T\n self.FoVx = FoVx\n self.FoVy = FoVy\n self.time = time\n self.kwargs = kwargs\n\n try:\n self.data_device = torch.device(data_device)\n except Exception as e:","source_hash":"69ccfa581123f12b32fb80056ddc850c630bf7fe3721c57e9e8c2c6beb20f5e9","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.cameras.Camera2","uri":"program://EfficientDynamic3DGaussian/class/scene.cameras.Camera2#L63-L99","kind":"class","name":"Camera2","path":"scene/cameras.py","language":"python","start_line":63,"end_line":99,"context_start_line":43,"context_end_line":116,"code":" self.image_height = self.original_image.shape[1]\n # self.image_width = 1386\n # self.image_height = 1014\n\n if gt_alpha_mask is not None:\n self.original_image *= gt_alpha_mask # .to(self.data_device)\n else:\n self.original_image *= torch.ones((1, self.image_height, self.image_width)) # , device=self.data_device)\n\n self.zfar = 100.0\n self.znear = 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\nclass Camera2(nn.Module):\n def __init__(self, colmap_id, R, T, FoVx, FoVy, width, height,\n uid, time=0,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n **kwargs):\n super(Camera2, self).__init__()\n\n self.uid = uid\n self.colmap_id = colmap_id\n self.R = R\n self.T = T\n self.FoVx = FoVx\n self.FoVy = FoVy\n self.time = time\n self.kwargs = kwargs\n\n try:\n self.data_device = torch.device(data_device)\n except Exception as e:\n print(e)\n print(f\"[Warning] Custom device {data_device} failed, fallback to default cuda device\" )\n self.data_device = torch.device(\"cuda\")\n\n self.image_width = width\n self.image_height = height\n\n\n self.zfar = 100.0\n self.znear = 10 # 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\n\n\n\nclass MiniCam:\n def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform):\n self.image_width = width\n self.image_height = height \n self.FoVy = fovy\n self.FoVx = fovx\n self.znear = znear\n self.zfar = zfar\n self.world_view_transform = world_view_transform\n self.full_proj_transform = full_proj_transform\n view_inv = torch.inverse(self.world_view_transform)\n self.camera_center = view_inv[3][:3]\n","source_hash":"69ccfa581123f12b32fb80056ddc850c630bf7fe3721c57e9e8c2c6beb20f5e9","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.cameras.MiniCam","uri":"program://EfficientDynamic3DGaussian/class/scene.cameras.MiniCam#L104-L115","kind":"class","name":"MiniCam","path":"scene/cameras.py","language":"python","start_line":104,"end_line":115,"context_start_line":84,"context_end_line":116,"code":" self.data_device = torch.device(\"cuda\")\n\n self.image_width = width\n self.image_height = height\n\n\n self.zfar = 100.0\n self.znear = 10 # 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\n\n\n\nclass MiniCam:\n def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform):\n self.image_width = width\n self.image_height = height \n self.FoVy = fovy\n self.FoVx = fovx\n self.znear = znear\n self.zfar = zfar\n self.world_view_transform = world_view_transform\n self.full_proj_transform = full_proj_transform\n view_inv = torch.inverse(self.world_view_transform)\n self.camera_center = view_inv[3][:3]\n","source_hash":"69ccfa581123f12b32fb80056ddc850c630bf7fe3721c57e9e8c2c6beb20f5e9","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.cameras.__init__","uri":"program://EfficientDynamic3DGaussian/function/scene.cameras.__init__#L105-L115","kind":"function","name":"__init__","path":"scene/cameras.py","language":"python","start_line":105,"end_line":115,"context_start_line":85,"context_end_line":116,"code":"\n self.image_width = width\n self.image_height = height\n\n\n self.zfar = 100.0\n self.znear = 10 # 0.01\n\n self.trans = trans\n self.scale = scale\n\n self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1) # .cuda()\n self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1) # .cuda()\n self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n self.camera_center = self.world_view_transform.inverse()[3, :3]\n\n\n\n\nclass MiniCam:\n def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform):\n self.image_width = width\n self.image_height = height \n self.FoVy = fovy\n self.FoVx = fovx\n self.znear = znear\n self.zfar = zfar\n self.world_view_transform = world_view_transform\n self.full_proj_transform = full_proj_transform\n view_inv = torch.inverse(self.world_view_transform)\n self.camera_center = view_inv[3][:3]\n","source_hash":"69ccfa581123f12b32fb80056ddc850c630bf7fe3721c57e9e8c2c6beb20f5e9","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model","uri":"program://EfficientDynamic3DGaussian/module/scene.gaussian_model#L1-L437","kind":"module","name":"scene.gaussian_model","path":"scene/gaussian_model.py","language":"python","start_line":1,"end_line":437,"context_start_line":1,"context_end_line":437,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport numpy as np\nfrom utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation\nfrom torch import nn\nimport os\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import RGB2SH\nfrom simple_knn._C import distCUDA2\nfrom utils.graphics_utils import BasicPointCloud\nfrom utils.general_utils import strip_symmetric, build_scaling_rotation\n\nclass GaussianModel:\n\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n actual_covariance = L @ L.transpose(1, 2)\n symm = strip_symmetric(actual_covariance)\n return symm\n \n self.scaling_activation = torch.exp\n self.scaling_inverse_activation = torch.log\n\n self.covariance_activation = build_covariance_from_scaling_rotation\n\n self.opacity_activation = torch.sigmoid\n self.inverse_opacity_activation = inverse_sigmoid\n\n self.rotation_activation = torch.nn.functional.normalize\n\n\n def __init__(self, sh_degree : int, L: int):\n self.active_sh_degree = 0\n self.L = L\n self.max_sh_degree = sh_degree \n self._xyz = torch.empty(0)\n self._features_dc = torch.empty(0)\n self._features_rest = torch.empty(0)\n self._scaling = torch.empty(0)\n self._rotation = torch.empty(0)\n self._opacity = torch.empty(0)\n self.max_radii2D = torch.empty(0)\n self.xyz_gradient_accum = torch.empty(0)\n self.denom = torch.empty(0)\n self.optimizer = None\n self.percent_dense = 0\n self.spatial_lr_scale = 0\n self.setup_functions()\n\n def capture(self):\n return (\n self.active_sh_degree,\n self._xyz,\n self._features_dc,\n self._features_rest,\n self._scaling,\n self._rotation,\n self._opacity,\n self.max_radii2D,\n self.xyz_gradient_accum,\n self.denom,\n self.optimizer.state_dict(),\n self.spatial_lr_scale,\n )\n \n def restore(self, model_args, training_args):\n (self.active_sh_degree, \n self._xyz,\n self._features_dc, \n self._features_rest,\n self._scaling, \n self._rotation,\n self._opacity,\n self.max_radii2D, \n xyz_gradient_accum, \n denom,\n opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n rots = torch.zeros((fused_point_cloud.shape[0], fused_point_cloud.shape[1], 4), device=\"cuda\")\n rots[:, 0, 0] = 1\n # rots[:, 3, 0] = 1\n\n opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device=\"cuda\"))\n\n self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))\n self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))\n self._scaling = nn.Parameter(scales.requires_grad_(True))\n self._rotation = nn.Parameter(rots.requires_grad_(True))\n self._opacity = nn.Parameter(opacities.requires_grad_(True))\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def training_setup(self, training_args):\n self.percent_dense = training_args.percent_dense\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n\n l = [\n {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, \"name\": \"xyz\"},\n {'params': [self._features_dc], 'lr': training_args.feature_lr, \"name\": \"f_dc\"},\n {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n ]\n\n self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n lr_delay_mult=training_args.position_lr_delay_mult,\n max_steps=training_args.position_lr_max_steps)\n\n def update_learning_rate(self, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in self.optimizer.param_groups:\n if param_group[\"name\"] == \"xyz\":\n lr = self.xyz_scheduler_args(iteration)\n param_group['lr'] = lr\n return lr\n\n def construct_list_of_attributes(self):\n l = []\n for t in range(self._xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(self._scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(self._rotation.shape[-1]):\n for t in range(self._rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n return l\n\n def save_ply(self, path):\n mkdir_p(os.path.dirname(path))\n\n xyz = self._xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = self._opacity.detach().cpu().numpy()\n scale = self._scaling.detach().cpu().numpy()\n rotation = self._rotation.detach().flatten(start_dim=1).cpu().numpy()\n\n dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\n def reset_opacity(self):\n opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))\n optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, \"opacity\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load_ply(self, path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n xyz = np.stack((x, y, z), axis=-1)\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n\n features_dc = np.zeros((xyz.shape[0], 3, 1))\n features_dc[:, 0, 0] = np.asarray(plydata.elements[0][\"f_dc_0\"])\n features_dc[:, 1, 0] = np.asarray(plydata.elements[0][\"f_dc_1\"])\n features_dc[:, 2, 0] = np.asarray(plydata.elements[0][\"f_dc_2\"])\n\n extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"f_rest_\")]\n extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))\n assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3\n features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))\n for idx, attr_name in enumerate(extra_f_names):\n features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)\n features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))\n\n scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"scale_\")]\n scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))\n scales = np.zeros((xyz.shape[0], len(scale_names)))\n for idx, attr_name in enumerate(scale_names):\n scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n rot_names = sorted(rot_names, key = lambda x: (int(x.split('_')[-1]), int(x.split('_')[-2])))\n rots = np.zeros((xyz.shape[0], len(rot_names)))\n for idx, attr_name in enumerate(rot_names):\n rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n rots = rots.reshape(xyz.shape[0], -1, 4)\n\n self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n\n self.active_sh_degree = self.max_sh_degree\n\n def replace_tensor_to_optimizer(self, tensor, name):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n if group[\"name\"] == name:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n stored_state[\"exp_avg\"] = torch.zeros_like(tensor)\n stored_state[\"exp_avg_sq\"] = torch.zeros_like(tensor)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(tensor.requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def _prune_optimizer(self, mask):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = stored_state[\"exp_avg\"][mask]\n stored_state[\"exp_avg_sq\"] = stored_state[\"exp_avg_sq\"][mask]\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter((group[\"params\"][0][mask].requires_grad_(True)))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def prune_points(self, mask):\n valid_points_mask = ~mask\n optimizable_tensors = self._prune_optimizer(valid_points_mask)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n\n self.denom = self.denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n\n def cat_tensors_to_optimizer(self, tensors_dict):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n assert len(group[\"params\"]) == 1\n extension_tensor = tensors_dict[group[\"name\"]]\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = torch.cat((stored_state[\"exp_avg\"], torch.zeros_like(extension_tensor)), dim=0)\n stored_state[\"exp_avg_sq\"] = torch.cat((stored_state[\"exp_avg_sq\"], torch.zeros_like(extension_tensor)), dim=0)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n\n return optimizable_tensors\n\n def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n d = {\"xyz\": new_xyz,\n \"f_dc\": new_features_dc,\n \"f_rest\": new_features_rest,\n \"opacity\": new_opacities,\n \"scaling\" : new_scaling,\n \"rotation\" : new_rotation}\n\n optimizable_tensors = self.cat_tensors_to_optimizer(d)\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n n_init_points = self.get_xyz.shape[0]\n # Extract points that satisfy the gradient condition\n padded_grad = torch.zeros((n_init_points), device=\"cuda\")\n padded_grad[:grads.shape[0]] = grads.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)\n\n # print(grads.shape)\n # print(selected_pts_mask.shape)\n stds = self.get_scaling[selected_pts_mask].repeat(N*self.get_xyz.shape[1],1)\n means = torch.zeros((stds.size(0), 3),device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1,1).reshape(-1, 3, 3)\n\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1).unsqueeze(1).reshape(-1, self.get_xyz.shape[1], 3) + self.get_xyz[selected_pts_mask].repeat(N, 1, 1)\n new_xyz[:, 1:, :] = self.get_xyz[selected_pts_mask].repeat(N, 1, 1)[:, 1:, :]\n new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))\n new_rotation = self._rotation[selected_pts_mask].repeat(N,1,1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)\n new_opacity = self._opacity[selected_pts_mask].repeat(N,1)\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)\n\n prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool)))\n self.prune_points(prune_filter)\n\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n # Extract points that satisfy the gradient condition\n selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected\n# ... truncated ...","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":true} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.GaussianModel","uri":"program://EfficientDynamic3DGaussian/class/scene.gaussian_model.GaussianModel#L24-L437","kind":"class","name":"GaussianModel","path":"scene/gaussian_model.py","language":"python","start_line":24,"end_line":437,"context_start_line":4,"context_end_line":437,"code":"# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport numpy as np\nfrom utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation\nfrom torch import nn\nimport os\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import RGB2SH\nfrom simple_knn._C import distCUDA2\nfrom utils.graphics_utils import BasicPointCloud\nfrom utils.general_utils import strip_symmetric, build_scaling_rotation\n\nclass GaussianModel:\n\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n actual_covariance = L @ L.transpose(1, 2)\n symm = strip_symmetric(actual_covariance)\n return symm\n \n self.scaling_activation = torch.exp\n self.scaling_inverse_activation = torch.log\n\n self.covariance_activation = build_covariance_from_scaling_rotation\n\n self.opacity_activation = torch.sigmoid\n self.inverse_opacity_activation = inverse_sigmoid\n\n self.rotation_activation = torch.nn.functional.normalize\n\n\n def __init__(self, sh_degree : int, L: int):\n self.active_sh_degree = 0\n self.L = L\n self.max_sh_degree = sh_degree \n self._xyz = torch.empty(0)\n self._features_dc = torch.empty(0)\n self._features_rest = torch.empty(0)\n self._scaling = torch.empty(0)\n self._rotation = torch.empty(0)\n self._opacity = torch.empty(0)\n self.max_radii2D = torch.empty(0)\n self.xyz_gradient_accum = torch.empty(0)\n self.denom = torch.empty(0)\n self.optimizer = None\n self.percent_dense = 0\n self.spatial_lr_scale = 0\n self.setup_functions()\n\n def capture(self):\n return (\n self.active_sh_degree,\n self._xyz,\n self._features_dc,\n self._features_rest,\n self._scaling,\n self._rotation,\n self._opacity,\n self.max_radii2D,\n self.xyz_gradient_accum,\n self.denom,\n self.optimizer.state_dict(),\n self.spatial_lr_scale,\n )\n \n def restore(self, model_args, training_args):\n (self.active_sh_degree, \n self._xyz,\n self._features_dc, \n self._features_rest,\n self._scaling, \n self._rotation,\n self._opacity,\n self.max_radii2D, \n xyz_gradient_accum, \n denom,\n opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n rots = torch.zeros((fused_point_cloud.shape[0], fused_point_cloud.shape[1], 4), device=\"cuda\")\n rots[:, 0, 0] = 1\n # rots[:, 3, 0] = 1\n\n opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device=\"cuda\"))\n\n self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))\n self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))\n self._scaling = nn.Parameter(scales.requires_grad_(True))\n self._rotation = nn.Parameter(rots.requires_grad_(True))\n self._opacity = nn.Parameter(opacities.requires_grad_(True))\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def training_setup(self, training_args):\n self.percent_dense = training_args.percent_dense\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n\n l = [\n {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, \"name\": \"xyz\"},\n {'params': [self._features_dc], 'lr': training_args.feature_lr, \"name\": \"f_dc\"},\n {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n ]\n\n self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n lr_delay_mult=training_args.position_lr_delay_mult,\n max_steps=training_args.position_lr_max_steps)\n\n def update_learning_rate(self, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in self.optimizer.param_groups:\n if param_group[\"name\"] == \"xyz\":\n lr = self.xyz_scheduler_args(iteration)\n param_group['lr'] = lr\n return lr\n\n def construct_list_of_attributes(self):\n l = []\n for t in range(self._xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(self._scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(self._rotation.shape[-1]):\n for t in range(self._rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n return l\n\n def save_ply(self, path):\n mkdir_p(os.path.dirname(path))\n\n xyz = self._xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = self._opacity.detach().cpu().numpy()\n scale = self._scaling.detach().cpu().numpy()\n rotation = self._rotation.detach().flatten(start_dim=1).cpu().numpy()\n\n dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\n def reset_opacity(self):\n opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))\n optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, \"opacity\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load_ply(self, path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n xyz = np.stack((x, y, z), axis=-1)\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n\n features_dc = np.zeros((xyz.shape[0], 3, 1))\n features_dc[:, 0, 0] = np.asarray(plydata.elements[0][\"f_dc_0\"])\n features_dc[:, 1, 0] = np.asarray(plydata.elements[0][\"f_dc_1\"])\n features_dc[:, 2, 0] = np.asarray(plydata.elements[0][\"f_dc_2\"])\n\n extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"f_rest_\")]\n extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))\n assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3\n features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))\n for idx, attr_name in enumerate(extra_f_names):\n features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)\n features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))\n\n scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"scale_\")]\n scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))\n scales = np.zeros((xyz.shape[0], len(scale_names)))\n for idx, attr_name in enumerate(scale_names):\n scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n rot_names = sorted(rot_names, key = lambda x: (int(x.split('_')[-1]), int(x.split('_')[-2])))\n rots = np.zeros((xyz.shape[0], len(rot_names)))\n for idx, attr_name in enumerate(rot_names):\n rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n rots = rots.reshape(xyz.shape[0], -1, 4)\n\n self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n\n self.active_sh_degree = self.max_sh_degree\n\n def replace_tensor_to_optimizer(self, tensor, name):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n if group[\"name\"] == name:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n stored_state[\"exp_avg\"] = torch.zeros_like(tensor)\n stored_state[\"exp_avg_sq\"] = torch.zeros_like(tensor)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(tensor.requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def _prune_optimizer(self, mask):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = stored_state[\"exp_avg\"][mask]\n stored_state[\"exp_avg_sq\"] = stored_state[\"exp_avg_sq\"][mask]\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter((group[\"params\"][0][mask].requires_grad_(True)))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def prune_points(self, mask):\n valid_points_mask = ~mask\n optimizable_tensors = self._prune_optimizer(valid_points_mask)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n\n self.denom = self.denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n\n def cat_tensors_to_optimizer(self, tensors_dict):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n assert len(group[\"params\"]) == 1\n extension_tensor = tensors_dict[group[\"name\"]]\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = torch.cat((stored_state[\"exp_avg\"], torch.zeros_like(extension_tensor)), dim=0)\n stored_state[\"exp_avg_sq\"] = torch.cat((stored_state[\"exp_avg_sq\"], torch.zeros_like(extension_tensor)), dim=0)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n\n return optimizable_tensors\n\n def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n d = {\"xyz\": new_xyz,\n \"f_dc\": new_features_dc,\n \"f_rest\": new_features_rest,\n \"opacity\": new_opacities,\n \"scaling\" : new_scaling,\n \"rotation\" : new_rotation}\n\n optimizable_tensors = self.cat_tensors_to_optimizer(d)\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n n_init_points = self.get_xyz.shape[0]\n # Extract points that satisfy the gradient condition\n padded_grad = torch.zeros((n_init_points), device=\"cuda\")\n padded_grad[:grads.shape[0]] = grads.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)\n\n # print(grads.shape)\n # print(selected_pts_mask.shape)\n stds = self.get_scaling[selected_pts_mask].repeat(N*self.get_xyz.shape[1],1)\n means = torch.zeros((stds.size(0), 3),device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1,1).reshape(-1, 3, 3)\n\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1).unsqueeze(1).reshape(-1, self.get_xyz.shape[1], 3) + self.get_xyz[selected_pts_mask].repeat(N, 1, 1)\n new_xyz[:, 1:, :] = self.get_xyz[selected_pts_mask].repeat(N, 1, 1)[:, 1:, :]\n new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))\n new_rotation = self._rotation[selected_pts_mask].repeat(N,1,1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)\n new_opacity = self._opacity[selected_pts_mask].repeat(N,1)\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)\n\n prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool)))\n self.prune_points(prune_filter)\n\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n # Extract points that satisfy the gradient condition\n selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1\n# ... truncated ...","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":true} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.setup_functions","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.setup_functions#L26-L41","kind":"function","name":"setup_functions","path":"scene/gaussian_model.py","language":"python","start_line":26,"end_line":41,"context_start_line":6,"context_end_line":61,"code":"# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport numpy as np\nfrom utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation\nfrom torch import nn\nimport os\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import RGB2SH\nfrom simple_knn._C import distCUDA2\nfrom utils.graphics_utils import BasicPointCloud\nfrom utils.general_utils import strip_symmetric, build_scaling_rotation\n\nclass GaussianModel:\n\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n actual_covariance = L @ L.transpose(1, 2)\n symm = strip_symmetric(actual_covariance)\n return symm\n \n self.scaling_activation = torch.exp\n self.scaling_inverse_activation = torch.log\n\n self.covariance_activation = build_covariance_from_scaling_rotation\n\n self.opacity_activation = torch.sigmoid\n self.inverse_opacity_activation = inverse_sigmoid\n\n self.rotation_activation = torch.nn.functional.normalize\n\n\n def __init__(self, sh_degree : int, L: int):\n self.active_sh_degree = 0\n self.L = L\n self.max_sh_degree = sh_degree \n self._xyz = torch.empty(0)\n self._features_dc = torch.empty(0)\n self._features_rest = torch.empty(0)\n self._scaling = torch.empty(0)\n self._rotation = torch.empty(0)\n self._opacity = torch.empty(0)\n self.max_radii2D = torch.empty(0)\n self.xyz_gradient_accum = torch.empty(0)\n self.denom = torch.empty(0)\n self.optimizer = None\n self.percent_dense = 0\n self.spatial_lr_scale = 0\n self.setup_functions()\n","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.__init__","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.__init__#L44-L60","kind":"function","name":"__init__","path":"scene/gaussian_model.py","language":"python","start_line":44,"end_line":60,"context_start_line":24,"context_end_line":80,"code":"class GaussianModel:\n\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n actual_covariance = L @ L.transpose(1, 2)\n symm = strip_symmetric(actual_covariance)\n return symm\n \n self.scaling_activation = torch.exp\n self.scaling_inverse_activation = torch.log\n\n self.covariance_activation = build_covariance_from_scaling_rotation\n\n self.opacity_activation = torch.sigmoid\n self.inverse_opacity_activation = inverse_sigmoid\n\n self.rotation_activation = torch.nn.functional.normalize\n\n\n def __init__(self, sh_degree : int, L: int):\n self.active_sh_degree = 0\n self.L = L\n self.max_sh_degree = sh_degree \n self._xyz = torch.empty(0)\n self._features_dc = torch.empty(0)\n self._features_rest = torch.empty(0)\n self._scaling = torch.empty(0)\n self._rotation = torch.empty(0)\n self._opacity = torch.empty(0)\n self.max_radii2D = torch.empty(0)\n self.xyz_gradient_accum = torch.empty(0)\n self.denom = torch.empty(0)\n self.optimizer = None\n self.percent_dense = 0\n self.spatial_lr_scale = 0\n self.setup_functions()\n\n def capture(self):\n return (\n self.active_sh_degree,\n self._xyz,\n self._features_dc,\n self._features_rest,\n self._scaling,\n self._rotation,\n self._opacity,\n self.max_radii2D,\n self.xyz_gradient_accum,\n self.denom,\n self.optimizer.state_dict(),\n self.spatial_lr_scale,\n )\n \n def restore(self, model_args, training_args):\n (self.active_sh_degree, \n self._xyz,","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.capture","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.capture#L62-L76","kind":"function","name":"capture","path":"scene/gaussian_model.py","language":"python","start_line":62,"end_line":76,"context_start_line":42,"context_end_line":96,"code":"\n\n def __init__(self, sh_degree : int, L: int):\n self.active_sh_degree = 0\n self.L = L\n self.max_sh_degree = sh_degree \n self._xyz = torch.empty(0)\n self._features_dc = torch.empty(0)\n self._features_rest = torch.empty(0)\n self._scaling = torch.empty(0)\n self._rotation = torch.empty(0)\n self._opacity = torch.empty(0)\n self.max_radii2D = torch.empty(0)\n self.xyz_gradient_accum = torch.empty(0)\n self.denom = torch.empty(0)\n self.optimizer = None\n self.percent_dense = 0\n self.spatial_lr_scale = 0\n self.setup_functions()\n\n def capture(self):\n return (\n self.active_sh_degree,\n self._xyz,\n self._features_dc,\n self._features_rest,\n self._scaling,\n self._rotation,\n self._opacity,\n self.max_radii2D,\n self.xyz_gradient_accum,\n self.denom,\n self.optimizer.state_dict(),\n self.spatial_lr_scale,\n )\n \n def restore(self, model_args, training_args):\n (self.active_sh_degree, \n self._xyz,\n self._features_dc, \n self._features_rest,\n self._scaling, \n self._rotation,\n self._opacity,\n self.max_radii2D, \n xyz_gradient_accum, \n denom,\n opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.restore","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.restore#L78-L97","kind":"function","name":"restore","path":"scene/gaussian_model.py","language":"python","start_line":78,"end_line":97,"context_start_line":58,"context_end_line":117,"code":" self.percent_dense = 0\n self.spatial_lr_scale = 0\n self.setup_functions()\n\n def capture(self):\n return (\n self.active_sh_degree,\n self._xyz,\n self._features_dc,\n self._features_rest,\n self._scaling,\n self._rotation,\n self._opacity,\n self.max_radii2D,\n self.xyz_gradient_accum,\n self.denom,\n self.optimizer.state_dict(),\n self.spatial_lr_scale,\n )\n \n def restore(self, model_args, training_args):\n (self.active_sh_degree, \n self._xyz,\n self._features_dc, \n self._features_rest,\n self._scaling, \n self._rotation,\n self._opacity,\n self.max_radii2D, \n xyz_gradient_accum, \n denom,\n opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n ","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.get_scaling","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.get_scaling#L100-L101","kind":"function","name":"get_scaling","path":"scene/gaussian_model.py","language":"python","start_line":100,"end_line":101,"context_start_line":80,"context_end_line":121,"code":" self._xyz,\n self._features_dc, \n self._features_rest,\n self._scaling, \n self._rotation,\n self._opacity,\n self.max_radii2D, \n xyz_gradient_accum, \n denom,\n opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n ","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.get_rotation","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.get_rotation#L104-L106","kind":"function","name":"get_rotation","path":"scene/gaussian_model.py","language":"python","start_line":104,"end_line":106,"context_start_line":84,"context_end_line":126,"code":" self._rotation,\n self._opacity,\n self.max_radii2D, \n xyz_gradient_accum, \n denom,\n opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.get_xyz","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.get_xyz#L109-L110","kind":"function","name":"get_xyz","path":"scene/gaussian_model.py","language":"python","start_line":109,"end_line":110,"context_start_line":89,"context_end_line":130,"code":" opt_dict,\n self.spatial_lr_scale) = model_args\n time_length = self._xyz.shape[1]\n # self._xyz = nn.Parameter(model_args[1].repeat(1, time_length, 1).requires_grad_(True))\n # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.get_features","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.get_features#L113-L116","kind":"function","name":"get_features","path":"scene/gaussian_model.py","language":"python","start_line":113,"end_line":116,"context_start_line":93,"context_end_line":136,"code":" # self._rotation = nn.Parameter(model_args[5].repeat(1, time_length, 1).requires_grad_(True))\n self.training_setup(training_args)\n self.xyz_gradient_accum = xyz_gradient_accum\n self.denom = denom\n self.optimizer.load_state_dict(opt_dict)\n\n @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.get_opacity","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.get_opacity#L119-L120","kind":"function","name":"get_opacity","path":"scene/gaussian_model.py","language":"python","start_line":119,"end_line":120,"context_start_line":99,"context_end_line":140,"code":" @property\n def get_scaling(self):\n return self.scaling_activation(self._scaling)\n \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.get_covariance","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.get_covariance#L122-L123","kind":"function","name":"get_covariance","path":"scene/gaussian_model.py","language":"python","start_line":122,"end_line":123,"context_start_line":102,"context_end_line":143,"code":" \n @property\n def get_rotation(self):\n # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n rots = torch.zeros((fused_point_cloud.shape[0], fused_point_cloud.shape[1], 4), device=\"cuda\")\n rots[:, 0, 0] = 1\n # rots[:, 3, 0] = 1","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.oneupSHdegree","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.oneupSHdegree#L125-L127","kind":"function","name":"oneupSHdegree","path":"scene/gaussian_model.py","language":"python","start_line":125,"end_line":127,"context_start_line":105,"context_end_line":147,"code":" # return self._rotation\n return self.rotation_activation(self._rotation, dim=-1)\n \n @property\n def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n rots = torch.zeros((fused_point_cloud.shape[0], fused_point_cloud.shape[1], 4), device=\"cuda\")\n rots[:, 0, 0] = 1\n # rots[:, 3, 0] = 1\n\n opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device=\"cuda\"))\n\n self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.create_from_pcd","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.create_from_pcd#L129-L153","kind":"function","name":"create_from_pcd","path":"scene/gaussian_model.py","language":"python","start_line":129,"end_line":153,"context_start_line":109,"context_end_line":173,"code":" def get_xyz(self):\n return self._xyz\n \n @property\n def get_features(self):\n features_dc = self._features_dc\n features_rest = self._features_rest\n return torch.cat((features_dc, features_rest), dim=1)\n \n @property\n def get_opacity(self):\n return self.opacity_activation(self._opacity)\n \n def get_covariance(self, scaling_modifier = 1):\n return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n def oneupSHdegree(self):\n if self.active_sh_degree < self.max_sh_degree:\n self.active_sh_degree += 1\n\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n self.spatial_lr_scale = spatial_lr_scale\n fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n features[:, :3, 0 ] = fused_color\n features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n rots = torch.zeros((fused_point_cloud.shape[0], fused_point_cloud.shape[1], 4), device=\"cuda\")\n rots[:, 0, 0] = 1\n # rots[:, 3, 0] = 1\n\n opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device=\"cuda\"))\n\n self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))\n self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))\n self._scaling = nn.Parameter(scales.requires_grad_(True))\n self._rotation = nn.Parameter(rots.requires_grad_(True))\n self._opacity = nn.Parameter(opacities.requires_grad_(True))\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def training_setup(self, training_args):\n self.percent_dense = training_args.percent_dense\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n\n l = [\n {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, \"name\": \"xyz\"},\n {'params': [self._features_dc], 'lr': training_args.feature_lr, \"name\": \"f_dc\"},\n {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n ]\n\n self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n lr_delay_mult=training_args.position_lr_delay_mult,\n max_steps=training_args.position_lr_max_steps)","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.training_setup","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.training_setup#L155-L173","kind":"function","name":"training_setup","path":"scene/gaussian_model.py","language":"python","start_line":155,"end_line":173,"context_start_line":135,"context_end_line":193,"code":" features[:, 3:, 1:] = 0.0\n\n print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points[:, 0, :])).float().cuda()), 0.0000001)\n scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n rots = torch.zeros((fused_point_cloud.shape[0], fused_point_cloud.shape[1], 4), device=\"cuda\")\n rots[:, 0, 0] = 1\n # rots[:, 3, 0] = 1\n\n opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device=\"cuda\"))\n\n self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))\n self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))\n self._scaling = nn.Parameter(scales.requires_grad_(True))\n self._rotation = nn.Parameter(rots.requires_grad_(True))\n self._opacity = nn.Parameter(opacities.requires_grad_(True))\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def training_setup(self, training_args):\n self.percent_dense = training_args.percent_dense\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n\n l = [\n {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, \"name\": \"xyz\"},\n {'params': [self._features_dc], 'lr': training_args.feature_lr, \"name\": \"f_dc\"},\n {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n ]\n\n self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n lr_delay_mult=training_args.position_lr_delay_mult,\n max_steps=training_args.position_lr_max_steps)\n\n def update_learning_rate(self, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in self.optimizer.param_groups:\n if param_group[\"name\"] == \"xyz\":\n lr = self.xyz_scheduler_args(iteration)\n param_group['lr'] = lr\n return lr\n\n def construct_list_of_attributes(self):\n l = []\n for t in range(self._xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.update_learning_rate","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.update_learning_rate#L175-L181","kind":"function","name":"update_learning_rate","path":"scene/gaussian_model.py","language":"python","start_line":175,"end_line":181,"context_start_line":155,"context_end_line":201,"code":" def training_setup(self, training_args):\n self.percent_dense = training_args.percent_dense\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n\n l = [\n {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, \"name\": \"xyz\"},\n {'params': [self._features_dc], 'lr': training_args.feature_lr, \"name\": \"f_dc\"},\n {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n ]\n\n self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n lr_delay_mult=training_args.position_lr_delay_mult,\n max_steps=training_args.position_lr_max_steps)\n\n def update_learning_rate(self, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in self.optimizer.param_groups:\n if param_group[\"name\"] == \"xyz\":\n lr = self.xyz_scheduler_args(iteration)\n param_group['lr'] = lr\n return lr\n\n def construct_list_of_attributes(self):\n l = []\n for t in range(self._xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(self._scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(self._rotation.shape[-1]):\n for t in range(self._rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n return l\n\n def save_ply(self, path):","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.construct_list_of_attributes","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.construct_list_of_attributes#L183-L199","kind":"function","name":"construct_list_of_attributes","path":"scene/gaussian_model.py","language":"python","start_line":183,"end_line":199,"context_start_line":163,"context_end_line":219,"code":" {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n ]\n\n self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n lr_delay_mult=training_args.position_lr_delay_mult,\n max_steps=training_args.position_lr_max_steps)\n\n def update_learning_rate(self, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in self.optimizer.param_groups:\n if param_group[\"name\"] == \"xyz\":\n lr = self.xyz_scheduler_args(iteration)\n param_group['lr'] = lr\n return lr\n\n def construct_list_of_attributes(self):\n l = []\n for t in range(self._xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(self._scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(self._rotation.shape[-1]):\n for t in range(self._rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n return l\n\n def save_ply(self, path):\n mkdir_p(os.path.dirname(path))\n\n xyz = self._xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = self._opacity.detach().cpu().numpy()\n scale = self._scaling.detach().cpu().numpy()\n rotation = self._rotation.detach().flatten(start_dim=1).cpu().numpy()\n\n dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.save_ply","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.save_ply#L201-L219","kind":"function","name":"save_ply","path":"scene/gaussian_model.py","language":"python","start_line":201,"end_line":219,"context_start_line":181,"context_end_line":239,"code":" return lr\n\n def construct_list_of_attributes(self):\n l = []\n for t in range(self._xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))\n for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n l.append('f_rest_{}'.format(i))\n l.append('opacity')\n for i in range(self._scaling.shape[1]):\n l.append('scale_{}'.format(i))\n for i in range(self._rotation.shape[-1]):\n for t in range(self._rotation.shape[-2]):\n l.append(f'rot_{t:03}_{i}')\n return l\n\n def save_ply(self, path):\n mkdir_p(os.path.dirname(path))\n\n xyz = self._xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = self._opacity.detach().cpu().numpy()\n scale = self._scaling.detach().cpu().numpy()\n rotation = self._rotation.detach().flatten(start_dim=1).cpu().numpy()\n\n dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\n def reset_opacity(self):\n opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))\n optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, \"opacity\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load_ply(self, path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.reset_opacity","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.reset_opacity#L221-L224","kind":"function","name":"reset_opacity","path":"scene/gaussian_model.py","language":"python","start_line":221,"end_line":224,"context_start_line":201,"context_end_line":244,"code":" def save_ply(self, path):\n mkdir_p(os.path.dirname(path))\n\n xyz = self._xyz.detach().flatten(start_dim=1).cpu().numpy()\n normals = np.zeros((xyz.shape[0], 3))\n f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = self._opacity.detach().cpu().numpy()\n scale = self._scaling.detach().cpu().numpy()\n rotation = self._rotation.detach().flatten(start_dim=1).cpu().numpy()\n\n dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\n def reset_opacity(self):\n opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))\n optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, \"opacity\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load_ply(self, path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.load_ply","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.load_ply#L226-L283","kind":"function","name":"load_ply","path":"scene/gaussian_model.py","language":"python","start_line":226,"end_line":283,"context_start_line":206,"context_end_line":303,"code":" f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n opacities = self._opacity.detach().cpu().numpy()\n scale = self._scaling.detach().cpu().numpy()\n rotation = self._rotation.detach().flatten(start_dim=1).cpu().numpy()\n\n dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n elements = np.empty(xyz.shape[0], dtype=dtype_full)\n\n attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n elements[:] = list(map(tuple, attributes))\n el = PlyElement.describe(elements, 'vertex')\n PlyData([el]).write(path)\n\n def reset_opacity(self):\n opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))\n optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, \"opacity\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load_ply(self, path):\n plydata = PlyData.read(path)\n\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((opacities.shape[0], len(x_names)))\n y = np.zeros((opacities.shape[0], len(y_names)))\n z = np.zeros((opacities.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n xyz = np.stack((x, y, z), axis=-1)\n opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n\n features_dc = np.zeros((xyz.shape[0], 3, 1))\n features_dc[:, 0, 0] = np.asarray(plydata.elements[0][\"f_dc_0\"])\n features_dc[:, 1, 0] = np.asarray(plydata.elements[0][\"f_dc_1\"])\n features_dc[:, 2, 0] = np.asarray(plydata.elements[0][\"f_dc_2\"])\n\n extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"f_rest_\")]\n extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))\n assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3\n features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))\n for idx, attr_name in enumerate(extra_f_names):\n features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)\n features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))\n\n scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"scale_\")]\n scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))\n scales = np.zeros((xyz.shape[0], len(scale_names)))\n for idx, attr_name in enumerate(scale_names):\n scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n rot_names = sorted(rot_names, key = lambda x: (int(x.split('_')[-1]), int(x.split('_')[-2])))\n rots = np.zeros((xyz.shape[0], len(rot_names)))\n for idx, attr_name in enumerate(rot_names):\n rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n rots = rots.reshape(xyz.shape[0], -1, 4)\n\n self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n\n self.active_sh_degree = self.max_sh_degree\n\n def replace_tensor_to_optimizer(self, tensor, name):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n if group[\"name\"] == name:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n stored_state[\"exp_avg\"] = torch.zeros_like(tensor)\n stored_state[\"exp_avg_sq\"] = torch.zeros_like(tensor)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(tensor.requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def _prune_optimizer(self, mask):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n stored_state = self.optimizer.state.get(group['params'][0], None)","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.replace_tensor_to_optimizer","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.replace_tensor_to_optimizer#L285-L298","kind":"function","name":"replace_tensor_to_optimizer","path":"scene/gaussian_model.py","language":"python","start_line":285,"end_line":298,"context_start_line":265,"context_end_line":318,"code":" scales = np.zeros((xyz.shape[0], len(scale_names)))\n for idx, attr_name in enumerate(scale_names):\n scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n rot_names = sorted(rot_names, key = lambda x: (int(x.split('_')[-1]), int(x.split('_')[-2])))\n rots = np.zeros((xyz.shape[0], len(rot_names)))\n for idx, attr_name in enumerate(rot_names):\n rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n rots = rots.reshape(xyz.shape[0], -1, 4)\n\n self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n\n self.active_sh_degree = self.max_sh_degree\n\n def replace_tensor_to_optimizer(self, tensor, name):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n if group[\"name\"] == name:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n stored_state[\"exp_avg\"] = torch.zeros_like(tensor)\n stored_state[\"exp_avg_sq\"] = torch.zeros_like(tensor)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(tensor.requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def _prune_optimizer(self, mask):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = stored_state[\"exp_avg\"][mask]\n stored_state[\"exp_avg_sq\"] = stored_state[\"exp_avg_sq\"][mask]\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter((group[\"params\"][0][mask].requires_grad_(True)))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def prune_points(self, mask):","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model._prune_optimizer","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model._prune_optimizer#L300-L316","kind":"function","name":"_prune_optimizer","path":"scene/gaussian_model.py","language":"python","start_line":300,"end_line":316,"context_start_line":280,"context_end_line":336,"code":" self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n\n self.active_sh_degree = self.max_sh_degree\n\n def replace_tensor_to_optimizer(self, tensor, name):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n if group[\"name\"] == name:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n stored_state[\"exp_avg\"] = torch.zeros_like(tensor)\n stored_state[\"exp_avg_sq\"] = torch.zeros_like(tensor)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(tensor.requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def _prune_optimizer(self, mask):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = stored_state[\"exp_avg\"][mask]\n stored_state[\"exp_avg_sq\"] = stored_state[\"exp_avg_sq\"][mask]\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter((group[\"params\"][0][mask].requires_grad_(True)))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def prune_points(self, mask):\n valid_points_mask = ~mask\n optimizable_tensors = self._prune_optimizer(valid_points_mask)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n\n self.denom = self.denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n\n def cat_tensors_to_optimizer(self, tensors_dict):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.prune_points","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.prune_points#L318-L332","kind":"function","name":"prune_points","path":"scene/gaussian_model.py","language":"python","start_line":318,"end_line":332,"context_start_line":298,"context_end_line":352,"code":" return optimizable_tensors\n\n def _prune_optimizer(self, mask):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = stored_state[\"exp_avg\"][mask]\n stored_state[\"exp_avg_sq\"] = stored_state[\"exp_avg_sq\"][mask]\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter((group[\"params\"][0][mask].requires_grad_(True)))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def prune_points(self, mask):\n valid_points_mask = ~mask\n optimizable_tensors = self._prune_optimizer(valid_points_mask)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n\n self.denom = self.denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n\n def cat_tensors_to_optimizer(self, tensors_dict):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n assert len(group[\"params\"]) == 1\n extension_tensor = tensors_dict[group[\"name\"]]\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = torch.cat((stored_state[\"exp_avg\"], torch.zeros_like(extension_tensor)), dim=0)\n stored_state[\"exp_avg_sq\"] = torch.cat((stored_state[\"exp_avg_sq\"], torch.zeros_like(extension_tensor)), dim=0)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.cat_tensors_to_optimizer","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.cat_tensors_to_optimizer#L334-L353","kind":"function","name":"cat_tensors_to_optimizer","path":"scene/gaussian_model.py","language":"python","start_line":334,"end_line":353,"context_start_line":314,"context_end_line":373,"code":" group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n return optimizable_tensors\n\n def prune_points(self, mask):\n valid_points_mask = ~mask\n optimizable_tensors = self._prune_optimizer(valid_points_mask)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n\n self.denom = self.denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n\n def cat_tensors_to_optimizer(self, tensors_dict):\n optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n assert len(group[\"params\"]) == 1\n extension_tensor = tensors_dict[group[\"name\"]]\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = torch.cat((stored_state[\"exp_avg\"], torch.zeros_like(extension_tensor)), dim=0)\n stored_state[\"exp_avg_sq\"] = torch.cat((stored_state[\"exp_avg_sq\"], torch.zeros_like(extension_tensor)), dim=0)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n\n return optimizable_tensors\n\n def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n d = {\"xyz\": new_xyz,\n \"f_dc\": new_features_dc,\n \"f_rest\": new_features_rest,\n \"opacity\": new_opacities,\n \"scaling\" : new_scaling,\n \"rotation\" : new_rotation}\n\n optimizable_tensors = self.cat_tensors_to_optimizer(d)\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.densification_postfix","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.densification_postfix#L355-L373","kind":"function","name":"densification_postfix","path":"scene/gaussian_model.py","language":"python","start_line":355,"end_line":373,"context_start_line":335,"context_end_line":393,"code":" optimizable_tensors = {}\n for group in self.optimizer.param_groups:\n assert len(group[\"params\"]) == 1\n extension_tensor = tensors_dict[group[\"name\"]]\n stored_state = self.optimizer.state.get(group['params'][0], None)\n if stored_state is not None:\n stored_state[\"exp_avg\"] = torch.cat((stored_state[\"exp_avg\"], torch.zeros_like(extension_tensor)), dim=0)\n stored_state[\"exp_avg_sq\"] = torch.cat((stored_state[\"exp_avg_sq\"], torch.zeros_like(extension_tensor)), dim=0)\n\n del self.optimizer.state[group['params'][0]]\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n self.optimizer.state[group['params'][0]] = stored_state\n\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n else:\n group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n\n return optimizable_tensors\n\n def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n d = {\"xyz\": new_xyz,\n \"f_dc\": new_features_dc,\n \"f_rest\": new_features_rest,\n \"opacity\": new_opacities,\n \"scaling\" : new_scaling,\n \"rotation\" : new_rotation}\n\n optimizable_tensors = self.cat_tensors_to_optimizer(d)\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n n_init_points = self.get_xyz.shape[0]\n # Extract points that satisfy the gradient condition\n padded_grad = torch.zeros((n_init_points), device=\"cuda\")\n padded_grad[:grads.shape[0]] = grads.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)\n\n # print(grads.shape)\n # print(selected_pts_mask.shape)\n stds = self.get_scaling[selected_pts_mask].repeat(N*self.get_xyz.shape[1],1)\n means = torch.zeros((stds.size(0), 3),device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1,1).reshape(-1, 3, 3)\n\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1).unsqueeze(1).reshape(-1, self.get_xyz.shape[1], 3) + self.get_xyz[selected_pts_mask].repeat(N, 1, 1)\n new_xyz[:, 1:, :] = self.get_xyz[selected_pts_mask].repeat(N, 1, 1)[:, 1:, :]\n new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.densify_and_split","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.densify_and_split#L375-L402","kind":"function","name":"densify_and_split","path":"scene/gaussian_model.py","language":"python","start_line":375,"end_line":402,"context_start_line":355,"context_end_line":422,"code":" def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n d = {\"xyz\": new_xyz,\n \"f_dc\": new_features_dc,\n \"f_rest\": new_features_rest,\n \"opacity\": new_opacities,\n \"scaling\" : new_scaling,\n \"rotation\" : new_rotation}\n\n optimizable_tensors = self.cat_tensors_to_optimizer(d)\n self._xyz = optimizable_tensors[\"xyz\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n\n self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n n_init_points = self.get_xyz.shape[0]\n # Extract points that satisfy the gradient condition\n padded_grad = torch.zeros((n_init_points), device=\"cuda\")\n padded_grad[:grads.shape[0]] = grads.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)\n\n # print(grads.shape)\n # print(selected_pts_mask.shape)\n stds = self.get_scaling[selected_pts_mask].repeat(N*self.get_xyz.shape[1],1)\n means = torch.zeros((stds.size(0), 3),device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1,1).reshape(-1, 3, 3)\n\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1).unsqueeze(1).reshape(-1, self.get_xyz.shape[1], 3) + self.get_xyz[selected_pts_mask].repeat(N, 1, 1)\n new_xyz[:, 1:, :] = self.get_xyz[selected_pts_mask].repeat(N, 1, 1)[:, 1:, :]\n new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))\n new_rotation = self._rotation[selected_pts_mask].repeat(N,1,1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)\n new_opacity = self._opacity[selected_pts_mask].repeat(N,1)\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)\n\n prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool)))\n self.prune_points(prune_filter)\n\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n # Extract points that satisfy the gradient condition\n selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)\n \n new_xyz = self._xyz[selected_pts_mask]\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n new_opacities = self._opacity[selected_pts_mask]\n new_scaling = self._scaling[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)\n\n def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size):\n grads = self.xyz_gradient_accum / self.denom\n grads[grads.isnan()] = 0.0\n","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.densify_and_clone","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.densify_and_clone#L404-L417","kind":"function","name":"densify_and_clone","path":"scene/gaussian_model.py","language":"python","start_line":404,"end_line":417,"context_start_line":384,"context_end_line":437,"code":" # print(grads.shape)\n # print(selected_pts_mask.shape)\n stds = self.get_scaling[selected_pts_mask].repeat(N*self.get_xyz.shape[1],1)\n means = torch.zeros((stds.size(0), 3),device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1,1).reshape(-1, 3, 3)\n\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1).unsqueeze(1).reshape(-1, self.get_xyz.shape[1], 3) + self.get_xyz[selected_pts_mask].repeat(N, 1, 1)\n new_xyz[:, 1:, :] = self.get_xyz[selected_pts_mask].repeat(N, 1, 1)[:, 1:, :]\n new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))\n new_rotation = self._rotation[selected_pts_mask].repeat(N,1,1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)\n new_opacity = self._opacity[selected_pts_mask].repeat(N,1)\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)\n\n prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool)))\n self.prune_points(prune_filter)\n\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n # Extract points that satisfy the gradient condition\n selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)\n \n new_xyz = self._xyz[selected_pts_mask]\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n new_opacities = self._opacity[selected_pts_mask]\n new_scaling = self._scaling[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)\n\n def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size):\n grads = self.xyz_gradient_accum / self.denom\n grads[grads.isnan()] = 0.0\n\n self.densify_and_clone(grads, max_grad, extent)\n self.densify_and_split(grads, max_grad, extent)\n\n prune_mask = (self.get_opacity < min_opacity).squeeze()\n if max_screen_size:\n big_points_vs = self.max_radii2D > max_screen_size\n big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent\n prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)\n self.prune_points(prune_mask)\n\n torch.cuda.empty_cache()\n\n def add_densification_stats(self, viewspace_point_tensor, update_filter):\n self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)\n self.denom[update_filter] += 1","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.densify_and_prune","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.densify_and_prune#L419-L433","kind":"function","name":"densify_and_prune","path":"scene/gaussian_model.py","language":"python","start_line":419,"end_line":433,"context_start_line":399,"context_end_line":437,"code":" self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)\n\n prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool)))\n self.prune_points(prune_filter)\n\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n # Extract points that satisfy the gradient condition\n selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(selected_pts_mask,\n torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)\n \n new_xyz = self._xyz[selected_pts_mask]\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n new_opacities = self._opacity[selected_pts_mask]\n new_scaling = self._scaling[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)\n\n def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size):\n grads = self.xyz_gradient_accum / self.denom\n grads[grads.isnan()] = 0.0\n\n self.densify_and_clone(grads, max_grad, extent)\n self.densify_and_split(grads, max_grad, extent)\n\n prune_mask = (self.get_opacity < min_opacity).squeeze()\n if max_screen_size:\n big_points_vs = self.max_radii2D > max_screen_size\n big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent\n prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)\n self.prune_points(prune_mask)\n\n torch.cuda.empty_cache()\n\n def add_densification_stats(self, viewspace_point_tensor, update_filter):\n self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)\n self.denom[update_filter] += 1","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.add_densification_stats","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.add_densification_stats#L435-L437","kind":"function","name":"add_densification_stats","path":"scene/gaussian_model.py","language":"python","start_line":435,"end_line":437,"context_start_line":415,"context_end_line":437,"code":" new_rotation = self._rotation[selected_pts_mask]\n\n self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)\n\n def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size):\n grads = self.xyz_gradient_accum / self.denom\n grads[grads.isnan()] = 0.0\n\n self.densify_and_clone(grads, max_grad, extent)\n self.densify_and_split(grads, max_grad, extent)\n\n prune_mask = (self.get_opacity < min_opacity).squeeze()\n if max_screen_size:\n big_points_vs = self.max_radii2D > max_screen_size\n big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent\n prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)\n self.prune_points(prune_mask)\n\n torch.cuda.empty_cache()\n\n def add_densification_stats(self, viewspace_point_tensor, update_filter):\n self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)\n self.denom[update_filter] += 1","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.gaussian_model.build_covariance_from_scaling_rotation","uri":"program://EfficientDynamic3DGaussian/function/scene.gaussian_model.build_covariance_from_scaling_rotation#L27-L31","kind":"function","name":"build_covariance_from_scaling_rotation","path":"scene/gaussian_model.py","language":"python","start_line":27,"end_line":31,"context_start_line":7,"context_end_line":51,"code":"# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport numpy as np\nfrom utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation\nfrom torch import nn\nimport os\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import RGB2SH\nfrom simple_knn._C import distCUDA2\nfrom utils.graphics_utils import BasicPointCloud\nfrom utils.general_utils import strip_symmetric, build_scaling_rotation\n\nclass GaussianModel:\n\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n actual_covariance = L @ L.transpose(1, 2)\n symm = strip_symmetric(actual_covariance)\n return symm\n \n self.scaling_activation = torch.exp\n self.scaling_inverse_activation = torch.log\n\n self.covariance_activation = build_covariance_from_scaling_rotation\n\n self.opacity_activation = torch.sigmoid\n self.inverse_opacity_activation = inverse_sigmoid\n\n self.rotation_activation = torch.nn.functional.normalize\n\n\n def __init__(self, sh_degree : int, L: int):\n self.active_sh_degree = 0\n self.L = L\n self.max_sh_degree = sh_degree \n self._xyz = torch.empty(0)\n self._features_dc = torch.empty(0)\n self._features_rest = torch.empty(0)\n self._scaling = torch.empty(0)","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera","uri":"program://EfficientDynamic3DGaussian/module/scene.hyper_camera#L1-L430","kind":"module","name":"scene.hyper_camera","path":"scene/hyper_camera.py","language":"python","start_line":1,"end_line":430,"context_start_line":1,"context_end_line":430,"code":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Class for handling cameras.\"\"\"\nimport pathlib\n\nimport copy\nimport json\nfrom typing import Tuple, Union, Optional, Text\n\n\nimport numpy as np\n\nPathType = Union[Text, pathlib.PurePosixPath]\n\nfrom pathlib import PurePosixPath as GPath\n\n\ndef _compute_residual_and_jacobian(\n x: np.ndarray,\n y: np.ndarray,\n xd: np.ndarray,\n yd: np.ndarray,\n k1: float = 0.0,\n k2: float = 0.0,\n k3: float = 0.0,\n p1: float = 0.0,\n p2: float = 0.0,\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n np.ndarray]:\n \"\"\"Auxiliary function of radial_and_tangential_undistort().\"\"\"\n # let r(x, y) = x^2 + y^2;\n # d(x, y) = 1 + k1 * r(x, y) + k2 * r(x, y) ^2 + k3 * r(x, y)^3;\n r = x * x + y * y\n d = 1.0 + r * (k1 + r * (k2 + k3 * r))\n\n # The perfect projection is:\n # xd = x * d(x, y) + 2 * p1 * x * y + p2 * (r(x, y) + 2 * x^2);\n # yd = y * d(x, y) + 2 * p2 * x * y + p1 * (r(x, y) + 2 * y^2);\n #\n # Let's define\n #\n # fx(x, y) = x * d(x, y) + 2 * p1 * x * y + p2 * (r(x, y) + 2 * x^2) - xd;\n # fy(x, y) = y * d(x, y) + 2 * p2 * x * y + p1 * (r(x, y) + 2 * y^2) - yd;\n #\n # We are looking for a solution that satisfies\n # fx(x, y) = fy(x, y) = 0;\n fx = d * x + 2 * p1 * x * y + p2 * (r + 2 * x * x) - xd\n fy = d * y + 2 * p2 * x * y + p1 * (r + 2 * y * y) - yd\n\n # Compute derivative of d over [x, y]\n d_r = (k1 + r * (2.0 * k2 + 3.0 * k3 * r))\n d_x = 2.0 * x * d_r\n d_y = 2.0 * y * d_r\n\n # Compute derivative of fx over x and y.\n fx_x = d + d_x * x + 2.0 * p1 * y + 6.0 * p2 * x\n fx_y = d_y * x + 2.0 * p1 * x + 2.0 * p2 * y\n\n # Compute derivative of fy over x and y.\n fy_x = d_x * y + 2.0 * p2 * y + 2.0 * p1 * x\n fy_y = d + d_y * y + 2.0 * p2 * x + 6.0 * p1 * y\n\n return fx, fy, fx_x, fx_y, fy_x, fy_y\n\n\ndef _radial_and_tangential_undistort(\n xd: np.ndarray,\n yd: np.ndarray,\n k1: float = 0,\n k2: float = 0,\n k3: float = 0,\n p1: float = 0,\n p2: float = 0,\n eps: float = 1e-9,\n max_iterations=10) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Computes undistorted (x, y) from (xd, yd).\"\"\"\n # Initialize from the distorted point.\n x = xd.copy()\n y = yd.copy()\n\n for _ in range(max_iterations):\n fx, fy, fx_x, fx_y, fy_x, fy_y = _compute_residual_and_jacobian(\n x=x, y=y, xd=xd, yd=yd, k1=k1, k2=k2, k3=k3, p1=p1, p2=p2)\n denominator = fy_x * fx_y - fx_x * fy_y\n x_numerator = fx * fy_y - fy * fx_y\n y_numerator = fy * fx_x - fx * fy_x\n step_x = np.where(\n np.abs(denominator) > eps, x_numerator / denominator,\n np.zeros_like(denominator))\n step_y = np.where(\n np.abs(denominator) > eps, y_numerator / denominator,\n np.zeros_like(denominator))\n\n x = x + step_x\n y = y + step_y\n\n return x, y\n\n\nclass Camera:\n \"\"\"Class to handle camera geometry.\"\"\"\n\n def __init__(self,\n orientation: np.ndarray,\n position: np.ndarray,\n focal_length: Union[np.ndarray, float],\n principal_point: np.ndarray,\n image_size: np.ndarray,\n skew: Union[np.ndarray, float] = 0.0,\n pixel_aspect_ratio: Union[np.ndarray, float] = 1.0,\n radial_distortion: Optional[np.ndarray] = None,\n tangential_distortion: Optional[np.ndarray] = None,\n dtype=np.float32):\n \"\"\"Constructor for camera class.\"\"\"\n if radial_distortion is None:\n radial_distortion = np.array([0.0, 0.0, 0.0], dtype)\n if tangential_distortion is None:\n tangential_distortion = np.array([0.0, 0.0], dtype)\n\n self.orientation = np.array(orientation, dtype)\n self.position = np.array(position, dtype)\n self.focal_length = np.array(focal_length, dtype)\n self.principal_point = np.array(principal_point, dtype)\n self.skew = np.array(skew, dtype)\n self.pixel_aspect_ratio = np.array(pixel_aspect_ratio, dtype)\n self.radial_distortion = np.array(radial_distortion, dtype)\n self.tangential_distortion = np.array(tangential_distortion, dtype)\n self.image_size = np.array(image_size, np.uint32)\n self.dtype = dtype\n\n @classmethod\n def from_json(cls, path: PathType):\n \"\"\"Loads a JSON camera into memory.\"\"\"\n with open(path, 'r') as fp:\n camera_json = json.load(fp)\n\n # Fix old camera JSON.\n if 'tangential' in camera_json:\n camera_json['tangential_distortion'] = camera_json['tangential']\n\n return cls(\n orientation=np.asarray(camera_json['orientation']),\n position=np.asarray(camera_json['position']),\n focal_length=camera_json['focal_length'],\n principal_point=np.asarray(camera_json['principal_point']),\n skew=camera_json['skew'],\n pixel_aspect_ratio=camera_json['pixel_aspect_ratio'],\n radial_distortion=np.asarray(camera_json['radial_distortion']),\n tangential_distortion=np.asarray(camera_json['tangential_distortion']),\n image_size=np.asarray(camera_json['image_size']),\n )\n\n def to_json(self):\n return {\n k: (v.tolist() if hasattr(v, 'tolist') else v)\n for k, v in self.get_parameters().items()\n }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],\n k2=self.radial_distortion[1],\n k3=self.radial_distortion[2],\n p1=self.tangential_distortion[0],\n p2=self.tangential_distortion[1])\n\n dirs = np.stack([x, y, np.ones_like(x)], axis=-1)\n return dirs / np.linalg.norm(dirs, axis=-1, keepdims=True)\n\n def pixels_to_rays(self, pixels: np.ndarray) -> np.ndarray:\n \"\"\"Returns the rays for the provided pixels.\n\n Args:\n pixels: [A1, ..., An, 2] tensor or np.array containing 2d pixel positions.\n\n Returns:\n An array containing the normalized ray directions in world coordinates.\n \"\"\"\n if pixels.shape[-1] != 2:\n raise ValueError('The last dimension of pixels must be 2.')\n if pixels.dtype != self.dtype:\n raise ValueError(f'pixels dtype ({pixels.dtype!r}) must match camera '\n f'dtype ({self.dtype!r})')\n\n batch_shape = pixels.shape[:-1]\n pixels = np.reshape(pixels, (-1, 2))\n\n local_rays_dir = self.pixel_to_local_rays(pixels)\n rays_dir = np.matmul(self.orientation.T, local_rays_dir[..., np.newaxis])\n rays_dir = np.squeeze(rays_dir, axis=-1)\n\n # Normalize rays.\n rays_dir /= np.linalg.norm(rays_dir, axis=-1, keepdims=True)\n rays_dir = rays_dir.reshape((*batch_shape, 3))\n return rays_dir\n\n def pixels_to_points(self, pixels: np.ndarray, depth: np.ndarray):\n rays_through_pixels = self.pixels_to_rays(pixels)\n cosa = np.matmul(rays_through_pixels, self.optical_axis)\n points = (\n rays_through_pixels * depth[..., np.newaxis] / cosa[..., np.newaxis] +\n self.position)\n return points\n\n def points_to_local_points(self, points: np.ndarray):\n translated_points = points - self.position\n local_points = (np.matmul(self.orientation, translated_points.T)).T\n return local_points\n\n def project(self, points: np.ndarray):\n \"\"\"Projects a 3D point (x,y,z) to a pixel position (x,y).\"\"\"\n batch_shape = points.shape[:-1]\n points = points.reshape((-1, 3))\n local_points = self.points_to_local_points(points)\n\n # Get normalized local pixel positions.\n x = local_points[..., 0] / local_points[..., 2]\n y = local_points[..., 1] / local_points[..., 2]\n r2 = x**2 + y**2\n\n # Apply radial distortion.\n distortion = 1.0 + r2 * (\n self.radial_distortion[0] + r2 *\n (self.radial_distortion[1] + self.radial_distortion[2] * r2))\n\n # Apply tangential distortion.\n x_times_y = x * y\n x = (\n x * distortion + 2.0 * self.tangential_distortion[0] * x_times_y +\n self.tangential_distortion[1] * (r2 + 2.0 * x**2))\n y = (\n y * distortion + 2.0 * self.tangential_distortion[1] * x_times_y +\n self.tangential_distortion[0] * (r2 + 2.0 * y**2))\n\n # Map the distorted ray to the image plane and return the depth.\n pixel_x = self.focal_length * x + self.skew * y + self.principal_point_x\n pixel_y = (self.focal_length * self.pixel_aspect_ratio * y\n + self.principal_point_y)\n\n pixels = np.stack([pixel_x, pixel_y], axis=-1)\n return pixels.reshape((*batch_shape, 2))\n\n def get_pixel_centers(self):\n \"\"\"Returns the pixel centers.\"\"\"\n xx, yy = np.meshgrid(np.arange(self.image_size_x, dtype=self.dtype),\n np.arange(self.image_size_y, dtype=self.dtype))\n return np.stack([xx, yy], axis=-1) + 0.5\n\n def scale(self, scale: float):\n \"\"\"Scales the camera.\"\"\"\n if scale <= 0:\n raise ValueError('scale needs to be positive.')\n\n new_camera = Camera(\n orientation=self.orientation.copy(),\n position=self.position.copy(),\n focal_length=self.focal_length * scale,\n principal_point=self.principal_point.copy() * scale,\n skew=self.skew,\n pixel_aspect_ratio=self.pixel_aspect_ratio,\n radial_distortion=self.radial_distortion.copy(),\n tangential_distortion=self.tangential_distortion.copy(),\n image_size=np.array((int(round(self.image_size[0] * scale)),\n int(round(self.image_size[1] * scale)))),\n )\n return new_camera\n\n def look_at(self, position, look_at, up, eps=1e-6):\n \"\"\"Creates a copy of the camera which looks at a given point.\n\n Copies the provided vision_sfm camera and returns a new camera that is\n positioned at `camera_position` while looking at `look_at_position`.\n Camera intrinsics are copied by this method. A common value for the\n up_vector is (0, 1, 0).\n\n Args:\n position: A (3,) numpy array representing the position of the camera.\n look_at: A (3,) numpy array representing the location the camera\n looks at.\n up: A (3,) numpy array representing the up direction, whose\n projection is parallel to the y-axis of the image plane.\n eps: a small number to prevent divides by zero.\n\n Returns:\n A new camera that is copied from the original but is positioned and\n looks at the provided coordinates.\n\n Raises:\n ValueError: If the camera position and look at position are very close\n to each other or if the up-vector is parallel to the requested optical\n axis.\n \"\"\"\n\n look_at_camera = self.copy()\n optical_axis = look_at - position\n norm = np.linalg.norm(optical_axis)\n if norm < eps:\n raise ValueError('The camera center and look at position are too close.')\n optical_axis /= norm\n\n right_vector = np.cross(optical_axis, up)\n norm = np.linalg.norm(right_vector)\n if norm < eps:\n raise ValueError('The up-vector is parallel to the optical axis.')\n right_vector /= norm\n\n # The three directions here are orthogonal to each other and form a right\n # handed coordinate system.\n camera_rotation = np.identity(3)\n camera_rotation[0, :] = right_vector\n camera_rotation[1, :] = np.cross(optical_axis, right_vector)\n camera_rotation[2, :] = optical_axis\n\n look_at_camera.position = position\n look_at_camera.orientation = camera_rotation\n return look_at_camera\n\n def crop_image_domain(\n self, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0):\n \"\"\"Returns a copy of the camera with adjusted image bounds.\n\n Args:\n left: number of pixels by which to reduce (or augment, if negative) the\n image domain at the associated boundary.\n right: likewise.\n top: likewise.\n bottom: likewise.\n\n The crop parameters may not cause the camera image domain dimensions to\n become non-positive.\n\n Returns:\n A camera with adjusted image dimensions. The focal length is unchanged,\n and the principal point is updated to preserve the original principal\n axis.\n \"\"\"\n\n crop_left_top = np.array([left, top])\n crop_right_bottom = np.array([right, bottom])\n new_resolution = self.image_size - crop_left_top - crop_right_bottom\n new_principal_point = self.principal_point - crop_left_top\n if np.any(new_resolution <= 0):\n raise ValueError('Crop would result in non-positive image dimensions.')\n\n new_camera = self.copy()\n new_camera.image_size = np.array([int(new_resolution[0]),\n int(new_resolution[1])])\n new_camera.principal_point = np.array([new_principal_point[0],\n new_principal_point[1]])\n return new_camera\n\n def copy(self):\n return copy.deepcopy(self)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera._compute_residual_and_jacobian","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera._compute_residual_and_jacobian#L30-L75","kind":"function","name":"_compute_residual_and_jacobian","path":"scene/hyper_camera.py","language":"python","start_line":30,"end_line":75,"context_start_line":10,"context_end_line":95,"code":"# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Class for handling cameras.\"\"\"\nimport pathlib\n\nimport copy\nimport json\nfrom typing import Tuple, Union, Optional, Text\n\n\nimport numpy as np\n\nPathType = Union[Text, pathlib.PurePosixPath]\n\nfrom pathlib import PurePosixPath as GPath\n\n\ndef _compute_residual_and_jacobian(\n x: np.ndarray,\n y: np.ndarray,\n xd: np.ndarray,\n yd: np.ndarray,\n k1: float = 0.0,\n k2: float = 0.0,\n k3: float = 0.0,\n p1: float = 0.0,\n p2: float = 0.0,\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,\n np.ndarray]:\n \"\"\"Auxiliary function of radial_and_tangential_undistort().\"\"\"\n # let r(x, y) = x^2 + y^2;\n # d(x, y) = 1 + k1 * r(x, y) + k2 * r(x, y) ^2 + k3 * r(x, y)^3;\n r = x * x + y * y\n d = 1.0 + r * (k1 + r * (k2 + k3 * r))\n\n # The perfect projection is:\n # xd = x * d(x, y) + 2 * p1 * x * y + p2 * (r(x, y) + 2 * x^2);\n # yd = y * d(x, y) + 2 * p2 * x * y + p1 * (r(x, y) + 2 * y^2);\n #\n # Let's define\n #\n # fx(x, y) = x * d(x, y) + 2 * p1 * x * y + p2 * (r(x, y) + 2 * x^2) - xd;\n # fy(x, y) = y * d(x, y) + 2 * p2 * x * y + p1 * (r(x, y) + 2 * y^2) - yd;\n #\n # We are looking for a solution that satisfies\n # fx(x, y) = fy(x, y) = 0;\n fx = d * x + 2 * p1 * x * y + p2 * (r + 2 * x * x) - xd\n fy = d * y + 2 * p2 * x * y + p1 * (r + 2 * y * y) - yd\n\n # Compute derivative of d over [x, y]\n d_r = (k1 + r * (2.0 * k2 + 3.0 * k3 * r))\n d_x = 2.0 * x * d_r\n d_y = 2.0 * y * d_r\n\n # Compute derivative of fx over x and y.\n fx_x = d + d_x * x + 2.0 * p1 * y + 6.0 * p2 * x\n fx_y = d_y * x + 2.0 * p1 * x + 2.0 * p2 * y\n\n # Compute derivative of fy over x and y.\n fy_x = d_x * y + 2.0 * p2 * y + 2.0 * p1 * x\n fy_y = d + d_y * y + 2.0 * p2 * x + 6.0 * p1 * y\n\n return fx, fy, fx_x, fx_y, fy_x, fy_y\n\n\ndef _radial_and_tangential_undistort(\n xd: np.ndarray,\n yd: np.ndarray,\n k1: float = 0,\n k2: float = 0,\n k3: float = 0,\n p1: float = 0,\n p2: float = 0,\n eps: float = 1e-9,\n max_iterations=10) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Computes undistorted (x, y) from (xd, yd).\"\"\"\n # Initialize from the distorted point.\n x = xd.copy()\n y = yd.copy()\n\n for _ in range(max_iterations):\n fx, fy, fx_x, fx_y, fy_x, fy_y = _compute_residual_and_jacobian(\n x=x, y=y, xd=xd, yd=yd, k1=k1, k2=k2, k3=k3, p1=p1, p2=p2)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera._radial_and_tangential_undistort","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera._radial_and_tangential_undistort#L78-L109","kind":"function","name":"_radial_and_tangential_undistort","path":"scene/hyper_camera.py","language":"python","start_line":78,"end_line":109,"context_start_line":58,"context_end_line":129,"code":" # fx(x, y) = fy(x, y) = 0;\n fx = d * x + 2 * p1 * x * y + p2 * (r + 2 * x * x) - xd\n fy = d * y + 2 * p2 * x * y + p1 * (r + 2 * y * y) - yd\n\n # Compute derivative of d over [x, y]\n d_r = (k1 + r * (2.0 * k2 + 3.0 * k3 * r))\n d_x = 2.0 * x * d_r\n d_y = 2.0 * y * d_r\n\n # Compute derivative of fx over x and y.\n fx_x = d + d_x * x + 2.0 * p1 * y + 6.0 * p2 * x\n fx_y = d_y * x + 2.0 * p1 * x + 2.0 * p2 * y\n\n # Compute derivative of fy over x and y.\n fy_x = d_x * y + 2.0 * p2 * y + 2.0 * p1 * x\n fy_y = d + d_y * y + 2.0 * p2 * x + 6.0 * p1 * y\n\n return fx, fy, fx_x, fx_y, fy_x, fy_y\n\n\ndef _radial_and_tangential_undistort(\n xd: np.ndarray,\n yd: np.ndarray,\n k1: float = 0,\n k2: float = 0,\n k3: float = 0,\n p1: float = 0,\n p2: float = 0,\n eps: float = 1e-9,\n max_iterations=10) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Computes undistorted (x, y) from (xd, yd).\"\"\"\n # Initialize from the distorted point.\n x = xd.copy()\n y = yd.copy()\n\n for _ in range(max_iterations):\n fx, fy, fx_x, fx_y, fy_x, fy_y = _compute_residual_and_jacobian(\n x=x, y=y, xd=xd, yd=yd, k1=k1, k2=k2, k3=k3, p1=p1, p2=p2)\n denominator = fy_x * fx_y - fx_x * fy_y\n x_numerator = fx * fy_y - fy * fx_y\n y_numerator = fy * fx_x - fx * fy_x\n step_x = np.where(\n np.abs(denominator) > eps, x_numerator / denominator,\n np.zeros_like(denominator))\n step_y = np.where(\n np.abs(denominator) > eps, y_numerator / denominator,\n np.zeros_like(denominator))\n\n x = x + step_x\n y = y + step_y\n\n return x, y\n\n\nclass Camera:\n \"\"\"Class to handle camera geometry.\"\"\"\n\n def __init__(self,\n orientation: np.ndarray,\n position: np.ndarray,\n focal_length: Union[np.ndarray, float],\n principal_point: np.ndarray,\n image_size: np.ndarray,\n skew: Union[np.ndarray, float] = 0.0,\n pixel_aspect_ratio: Union[np.ndarray, float] = 1.0,\n radial_distortion: Optional[np.ndarray] = None,\n tangential_distortion: Optional[np.ndarray] = None,\n dtype=np.float32):\n \"\"\"Constructor for camera class.\"\"\"\n if radial_distortion is None:\n radial_distortion = np.array([0.0, 0.0, 0.0], dtype)\n if tangential_distortion is None:","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.Camera","uri":"program://EfficientDynamic3DGaussian/class/scene.hyper_camera.Camera#L112-L430","kind":"class","name":"Camera","path":"scene/hyper_camera.py","language":"python","start_line":112,"end_line":430,"context_start_line":92,"context_end_line":430,"code":"\n for _ in range(max_iterations):\n fx, fy, fx_x, fx_y, fy_x, fy_y = _compute_residual_and_jacobian(\n x=x, y=y, xd=xd, yd=yd, k1=k1, k2=k2, k3=k3, p1=p1, p2=p2)\n denominator = fy_x * fx_y - fx_x * fy_y\n x_numerator = fx * fy_y - fy * fx_y\n y_numerator = fy * fx_x - fx * fy_x\n step_x = np.where(\n np.abs(denominator) > eps, x_numerator / denominator,\n np.zeros_like(denominator))\n step_y = np.where(\n np.abs(denominator) > eps, y_numerator / denominator,\n np.zeros_like(denominator))\n\n x = x + step_x\n y = y + step_y\n\n return x, y\n\n\nclass Camera:\n \"\"\"Class to handle camera geometry.\"\"\"\n\n def __init__(self,\n orientation: np.ndarray,\n position: np.ndarray,\n focal_length: Union[np.ndarray, float],\n principal_point: np.ndarray,\n image_size: np.ndarray,\n skew: Union[np.ndarray, float] = 0.0,\n pixel_aspect_ratio: Union[np.ndarray, float] = 1.0,\n radial_distortion: Optional[np.ndarray] = None,\n tangential_distortion: Optional[np.ndarray] = None,\n dtype=np.float32):\n \"\"\"Constructor for camera class.\"\"\"\n if radial_distortion is None:\n radial_distortion = np.array([0.0, 0.0, 0.0], dtype)\n if tangential_distortion is None:\n tangential_distortion = np.array([0.0, 0.0], dtype)\n\n self.orientation = np.array(orientation, dtype)\n self.position = np.array(position, dtype)\n self.focal_length = np.array(focal_length, dtype)\n self.principal_point = np.array(principal_point, dtype)\n self.skew = np.array(skew, dtype)\n self.pixel_aspect_ratio = np.array(pixel_aspect_ratio, dtype)\n self.radial_distortion = np.array(radial_distortion, dtype)\n self.tangential_distortion = np.array(tangential_distortion, dtype)\n self.image_size = np.array(image_size, np.uint32)\n self.dtype = dtype\n\n @classmethod\n def from_json(cls, path: PathType):\n \"\"\"Loads a JSON camera into memory.\"\"\"\n with open(path, 'r') as fp:\n camera_json = json.load(fp)\n\n # Fix old camera JSON.\n if 'tangential' in camera_json:\n camera_json['tangential_distortion'] = camera_json['tangential']\n\n return cls(\n orientation=np.asarray(camera_json['orientation']),\n position=np.asarray(camera_json['position']),\n focal_length=camera_json['focal_length'],\n principal_point=np.asarray(camera_json['principal_point']),\n skew=camera_json['skew'],\n pixel_aspect_ratio=camera_json['pixel_aspect_ratio'],\n radial_distortion=np.asarray(camera_json['radial_distortion']),\n tangential_distortion=np.asarray(camera_json['tangential_distortion']),\n image_size=np.asarray(camera_json['image_size']),\n )\n\n def to_json(self):\n return {\n k: (v.tolist() if hasattr(v, 'tolist') else v)\n for k, v in self.get_parameters().items()\n }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],\n k2=self.radial_distortion[1],\n k3=self.radial_distortion[2],\n p1=self.tangential_distortion[0],\n p2=self.tangential_distortion[1])\n\n dirs = np.stack([x, y, np.ones_like(x)], axis=-1)\n return dirs / np.linalg.norm(dirs, axis=-1, keepdims=True)\n\n def pixels_to_rays(self, pixels: np.ndarray) -> np.ndarray:\n \"\"\"Returns the rays for the provided pixels.\n\n Args:\n pixels: [A1, ..., An, 2] tensor or np.array containing 2d pixel positions.\n\n Returns:\n An array containing the normalized ray directions in world coordinates.\n \"\"\"\n if pixels.shape[-1] != 2:\n raise ValueError('The last dimension of pixels must be 2.')\n if pixels.dtype != self.dtype:\n raise ValueError(f'pixels dtype ({pixels.dtype!r}) must match camera '\n f'dtype ({self.dtype!r})')\n\n batch_shape = pixels.shape[:-1]\n pixels = np.reshape(pixels, (-1, 2))\n\n local_rays_dir = self.pixel_to_local_rays(pixels)\n rays_dir = np.matmul(self.orientation.T, local_rays_dir[..., np.newaxis])\n rays_dir = np.squeeze(rays_dir, axis=-1)\n\n # Normalize rays.\n rays_dir /= np.linalg.norm(rays_dir, axis=-1, keepdims=True)\n rays_dir = rays_dir.reshape((*batch_shape, 3))\n return rays_dir\n\n def pixels_to_points(self, pixels: np.ndarray, depth: np.ndarray):\n rays_through_pixels = self.pixels_to_rays(pixels)\n cosa = np.matmul(rays_through_pixels, self.optical_axis)\n points = (\n rays_through_pixels * depth[..., np.newaxis] / cosa[..., np.newaxis] +\n self.position)\n return points\n\n def points_to_local_points(self, points: np.ndarray):\n translated_points = points - self.position\n local_points = (np.matmul(self.orientation, translated_points.T)).T\n return local_points\n\n def project(self, points: np.ndarray):\n \"\"\"Projects a 3D point (x,y,z) to a pixel position (x,y).\"\"\"\n batch_shape = points.shape[:-1]\n points = points.reshape((-1, 3))\n local_points = self.points_to_local_points(points)\n\n # Get normalized local pixel positions.\n x = local_points[..., 0] / local_points[..., 2]\n y = local_points[..., 1] / local_points[..., 2]\n r2 = x**2 + y**2\n\n # Apply radial distortion.\n distortion = 1.0 + r2 * (\n self.radial_distortion[0] + r2 *\n (self.radial_distortion[1] + self.radial_distortion[2] * r2))\n\n # Apply tangential distortion.\n x_times_y = x * y\n x = (\n x * distortion + 2.0 * self.tangential_distortion[0] * x_times_y +\n self.tangential_distortion[1] * (r2 + 2.0 * x**2))\n y = (\n y * distortion + 2.0 * self.tangential_distortion[1] * x_times_y +\n self.tangential_distortion[0] * (r2 + 2.0 * y**2))\n\n # Map the distorted ray to the image plane and return the depth.\n pixel_x = self.focal_length * x + self.skew * y + self.principal_point_x\n pixel_y = (self.focal_length * self.pixel_aspect_ratio * y\n + self.principal_point_y)\n\n pixels = np.stack([pixel_x, pixel_y], axis=-1)\n return pixels.reshape((*batch_shape, 2))\n\n def get_pixel_centers(self):\n \"\"\"Returns the pixel centers.\"\"\"\n xx, yy = np.meshgrid(np.arange(self.image_size_x, dtype=self.dtype),\n np.arange(self.image_size_y, dtype=self.dtype))\n return np.stack([xx, yy], axis=-1) + 0.5\n\n def scale(self, scale: float):\n \"\"\"Scales the camera.\"\"\"\n if scale <= 0:\n raise ValueError('scale needs to be positive.')\n\n new_camera = Camera(\n orientation=self.orientation.copy(),\n position=self.position.copy(),\n focal_length=self.focal_length * scale,\n principal_point=self.principal_point.copy() * scale,\n skew=self.skew,\n pixel_aspect_ratio=self.pixel_aspect_ratio,\n radial_distortion=self.radial_distortion.copy(),\n tangential_distortion=self.tangential_distortion.copy(),\n image_size=np.array((int(round(self.image_size[0] * scale)),\n int(round(self.image_size[1] * scale)))),\n )\n return new_camera\n\n def look_at(self, position, look_at, up, eps=1e-6):\n \"\"\"Creates a copy of the camera which looks at a given point.\n\n Copies the provided vision_sfm camera and returns a new camera that is\n positioned at `camera_position` while looking at `look_at_position`.\n Camera intrinsics are copied by this method. A common value for the\n up_vector is (0, 1, 0).\n\n Args:\n position: A (3,) numpy array representing the position of the camera.\n look_at: A (3,) numpy array representing the location the camera\n looks at.\n up: A (3,) numpy array representing the up direction, whose\n projection is parallel to the y-axis of the image plane.\n eps: a small number to prevent divides by zero.\n\n Returns:\n A new camera that is copied from the original but is positioned and\n looks at the provided coordinates.\n\n Raises:\n ValueError: If the camera position and look at position are very close\n to each other or if the up-vector is parallel to the requested optical\n axis.\n \"\"\"\n\n look_at_camera = self.copy()\n optical_axis = look_at - position\n norm = np.linalg.norm(optical_axis)\n if norm < eps:\n raise ValueError('The camera center and look at position are too close.')\n optical_axis /= norm\n\n right_vector = np.cross(optical_axis, up)\n norm = np.linalg.norm(right_vector)\n if norm < eps:\n raise ValueError('The up-vector is parallel to the optical axis.')\n right_vector /= norm\n\n # The three directions here are orthogonal to each other and form a right\n # handed coordinate system.\n camera_rotation = np.identity(3)\n camera_rotation[0, :] = right_vector\n camera_rotation[1, :] = np.cross(optical_axis, right_vector)\n camera_rotation[2, :] = optical_axis\n\n look_at_camera.position = position\n look_at_camera.orientation = camera_rotation\n return look_at_camera\n\n def crop_image_domain(\n self, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0):\n \"\"\"Returns a copy of the camera with adjusted image bounds.\n\n Args:\n left: number of pixels by which to reduce (or augment, if negative) the\n image domain at the associated boundary.\n right: likewise.\n top: likewise.\n bottom: likewise.\n\n The crop parameters may not cause the camera image domain dimensions to\n become non-positive.\n\n Returns:\n A camera with adjusted image dimensions. The focal length is unchanged,\n and the principal point is updated to preserve the original principal\n axis.\n \"\"\"\n\n crop_left_top = np.array([left, top])\n crop_right_bottom = np.array([right, bottom])\n new_resolution = self.image_size - crop_left_top - crop_right_bottom\n new_principal_point = self.principal_point - crop_left_top\n if np.any(new_resolution <= 0):\n raise ValueError('Crop would result in non-positive image dimensions.')\n\n new_camera = self.copy()\n new_camera.image_size = np.array([int(new_resolution[0]),\n int(new_resolution[1])])\n new_camera.principal_point = np.array([new_principal_point[0],\n new_principal_point[1]])\n return new_camera\n\n def copy(self):\n return copy.deepcopy(self)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.__init__","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.__init__#L115-L141","kind":"function","name":"__init__","path":"scene/hyper_camera.py","language":"python","start_line":115,"end_line":141,"context_start_line":95,"context_end_line":161,"code":" x=x, y=y, xd=xd, yd=yd, k1=k1, k2=k2, k3=k3, p1=p1, p2=p2)\n denominator = fy_x * fx_y - fx_x * fy_y\n x_numerator = fx * fy_y - fy * fx_y\n y_numerator = fy * fx_x - fx * fy_x\n step_x = np.where(\n np.abs(denominator) > eps, x_numerator / denominator,\n np.zeros_like(denominator))\n step_y = np.where(\n np.abs(denominator) > eps, y_numerator / denominator,\n np.zeros_like(denominator))\n\n x = x + step_x\n y = y + step_y\n\n return x, y\n\n\nclass Camera:\n \"\"\"Class to handle camera geometry.\"\"\"\n\n def __init__(self,\n orientation: np.ndarray,\n position: np.ndarray,\n focal_length: Union[np.ndarray, float],\n principal_point: np.ndarray,\n image_size: np.ndarray,\n skew: Union[np.ndarray, float] = 0.0,\n pixel_aspect_ratio: Union[np.ndarray, float] = 1.0,\n radial_distortion: Optional[np.ndarray] = None,\n tangential_distortion: Optional[np.ndarray] = None,\n dtype=np.float32):\n \"\"\"Constructor for camera class.\"\"\"\n if radial_distortion is None:\n radial_distortion = np.array([0.0, 0.0, 0.0], dtype)\n if tangential_distortion is None:\n tangential_distortion = np.array([0.0, 0.0], dtype)\n\n self.orientation = np.array(orientation, dtype)\n self.position = np.array(position, dtype)\n self.focal_length = np.array(focal_length, dtype)\n self.principal_point = np.array(principal_point, dtype)\n self.skew = np.array(skew, dtype)\n self.pixel_aspect_ratio = np.array(pixel_aspect_ratio, dtype)\n self.radial_distortion = np.array(radial_distortion, dtype)\n self.tangential_distortion = np.array(tangential_distortion, dtype)\n self.image_size = np.array(image_size, np.uint32)\n self.dtype = dtype\n\n @classmethod\n def from_json(cls, path: PathType):\n \"\"\"Loads a JSON camera into memory.\"\"\"\n with open(path, 'r') as fp:\n camera_json = json.load(fp)\n\n # Fix old camera JSON.\n if 'tangential' in camera_json:\n camera_json['tangential_distortion'] = camera_json['tangential']\n\n return cls(\n orientation=np.asarray(camera_json['orientation']),\n position=np.asarray(camera_json['position']),\n focal_length=camera_json['focal_length'],\n principal_point=np.asarray(camera_json['principal_point']),\n skew=camera_json['skew'],\n pixel_aspect_ratio=camera_json['pixel_aspect_ratio'],\n radial_distortion=np.asarray(camera_json['radial_distortion']),\n tangential_distortion=np.asarray(camera_json['tangential_distortion']),","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.from_json","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.from_json#L144-L163","kind":"function","name":"from_json","path":"scene/hyper_camera.py","language":"python","start_line":144,"end_line":163,"context_start_line":124,"context_end_line":183,"code":" tangential_distortion: Optional[np.ndarray] = None,\n dtype=np.float32):\n \"\"\"Constructor for camera class.\"\"\"\n if radial_distortion is None:\n radial_distortion = np.array([0.0, 0.0, 0.0], dtype)\n if tangential_distortion is None:\n tangential_distortion = np.array([0.0, 0.0], dtype)\n\n self.orientation = np.array(orientation, dtype)\n self.position = np.array(position, dtype)\n self.focal_length = np.array(focal_length, dtype)\n self.principal_point = np.array(principal_point, dtype)\n self.skew = np.array(skew, dtype)\n self.pixel_aspect_ratio = np.array(pixel_aspect_ratio, dtype)\n self.radial_distortion = np.array(radial_distortion, dtype)\n self.tangential_distortion = np.array(tangential_distortion, dtype)\n self.image_size = np.array(image_size, np.uint32)\n self.dtype = dtype\n\n @classmethod\n def from_json(cls, path: PathType):\n \"\"\"Loads a JSON camera into memory.\"\"\"\n with open(path, 'r') as fp:\n camera_json = json.load(fp)\n\n # Fix old camera JSON.\n if 'tangential' in camera_json:\n camera_json['tangential_distortion'] = camera_json['tangential']\n\n return cls(\n orientation=np.asarray(camera_json['orientation']),\n position=np.asarray(camera_json['position']),\n focal_length=camera_json['focal_length'],\n principal_point=np.asarray(camera_json['principal_point']),\n skew=camera_json['skew'],\n pixel_aspect_ratio=camera_json['pixel_aspect_ratio'],\n radial_distortion=np.asarray(camera_json['radial_distortion']),\n tangential_distortion=np.asarray(camera_json['tangential_distortion']),\n image_size=np.asarray(camera_json['image_size']),\n )\n\n def to_json(self):\n return {\n k: (v.tolist() if hasattr(v, 'tolist') else v)\n for k, v in self.get_parameters().items()\n }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.to_json","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.to_json#L165-L169","kind":"function","name":"to_json","path":"scene/hyper_camera.py","language":"python","start_line":165,"end_line":169,"context_start_line":145,"context_end_line":189,"code":" \"\"\"Loads a JSON camera into memory.\"\"\"\n with open(path, 'r') as fp:\n camera_json = json.load(fp)\n\n # Fix old camera JSON.\n if 'tangential' in camera_json:\n camera_json['tangential_distortion'] = camera_json['tangential']\n\n return cls(\n orientation=np.asarray(camera_json['orientation']),\n position=np.asarray(camera_json['position']),\n focal_length=camera_json['focal_length'],\n principal_point=np.asarray(camera_json['principal_point']),\n skew=camera_json['skew'],\n pixel_aspect_ratio=camera_json['pixel_aspect_ratio'],\n radial_distortion=np.asarray(camera_json['radial_distortion']),\n tangential_distortion=np.asarray(camera_json['tangential_distortion']),\n image_size=np.asarray(camera_json['image_size']),\n )\n\n def to_json(self):\n return {\n k: (v.tolist() if hasattr(v, 'tolist') else v)\n for k, v in self.get_parameters().items()\n }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.get_parameters","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.get_parameters#L171-L182","kind":"function","name":"get_parameters","path":"scene/hyper_camera.py","language":"python","start_line":171,"end_line":182,"context_start_line":151,"context_end_line":202,"code":" camera_json['tangential_distortion'] = camera_json['tangential']\n\n return cls(\n orientation=np.asarray(camera_json['orientation']),\n position=np.asarray(camera_json['position']),\n focal_length=camera_json['focal_length'],\n principal_point=np.asarray(camera_json['principal_point']),\n skew=camera_json['skew'],\n pixel_aspect_ratio=camera_json['pixel_aspect_ratio'],\n radial_distortion=np.asarray(camera_json['radial_distortion']),\n tangential_distortion=np.asarray(camera_json['tangential_distortion']),\n image_size=np.asarray(camera_json['image_size']),\n )\n\n def to_json(self):\n return {\n k: (v.tolist() if hasattr(v, 'tolist') else v)\n for k, v in self.get_parameters().items()\n }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.scale_factor_x","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.scale_factor_x#L185-L186","kind":"function","name":"scale_factor_x","path":"scene/hyper_camera.py","language":"python","start_line":185,"end_line":186,"context_start_line":165,"context_end_line":206,"code":" def to_json(self):\n return {\n k: (v.tolist() if hasattr(v, 'tolist') else v)\n for k, v in self.get_parameters().items()\n }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.scale_factor_y","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.scale_factor_y#L189-L190","kind":"function","name":"scale_factor_y","path":"scene/hyper_camera.py","language":"python","start_line":189,"end_line":190,"context_start_line":169,"context_end_line":210,"code":" }\n\n def get_parameters(self):\n return {\n 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.principal_point_x","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.principal_point_x#L193-L194","kind":"function","name":"principal_point_x","path":"scene/hyper_camera.py","language":"python","start_line":193,"end_line":194,"context_start_line":173,"context_end_line":214,"code":" 'orientation': self.orientation,\n 'position': self.position,\n 'focal_length': self.focal_length,\n 'principal_point': self.principal_point,\n 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.principal_point_y","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.principal_point_y#L197-L198","kind":"function","name":"principal_point_y","path":"scene/hyper_camera.py","language":"python","start_line":197,"end_line":198,"context_start_line":177,"context_end_line":218,"code":" 'skew': self.skew,\n 'pixel_aspect_ratio': self.pixel_aspect_ratio,\n 'radial_distortion': self.radial_distortion,\n 'tangential_distortion': self.tangential_distortion,\n 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.has_tangential_distortion","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.has_tangential_distortion#L201-L202","kind":"function","name":"has_tangential_distortion","path":"scene/hyper_camera.py","language":"python","start_line":201,"end_line":202,"context_start_line":181,"context_end_line":222,"code":" 'image_size': self.image_size,\n }\n\n @property\n def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.has_radial_distortion","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.has_radial_distortion#L205-L206","kind":"function","name":"has_radial_distortion","path":"scene/hyper_camera.py","language":"python","start_line":205,"end_line":206,"context_start_line":185,"context_end_line":226,"code":" def scale_factor_x(self):\n return self.focal_length\n\n @property\n def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.image_size_y","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.image_size_y#L209-L210","kind":"function","name":"image_size_y","path":"scene/hyper_camera.py","language":"python","start_line":209,"end_line":210,"context_start_line":189,"context_end_line":230,"code":" def scale_factor_y(self):\n return self.focal_length * self.pixel_aspect_ratio\n\n @property\n def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.image_size_x","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.image_size_x#L213-L214","kind":"function","name":"image_size_x","path":"scene/hyper_camera.py","language":"python","start_line":213,"end_line":214,"context_start_line":193,"context_end_line":234,"code":" def principal_point_x(self):\n return self.principal_point[0]\n\n @property\n def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.image_shape","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.image_shape#L217-L218","kind":"function","name":"image_shape","path":"scene/hyper_camera.py","language":"python","start_line":217,"end_line":218,"context_start_line":197,"context_end_line":238,"code":" def principal_point_y(self):\n return self.principal_point[1]\n\n @property\n def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.optical_axis","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.optical_axis#L221-L222","kind":"function","name":"optical_axis","path":"scene/hyper_camera.py","language":"python","start_line":221,"end_line":222,"context_start_line":201,"context_end_line":242,"code":" def has_tangential_distortion(self):\n return any(self.tangential_distortion != 0.0)\n\n @property\n def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],\n k2=self.radial_distortion[1],\n k3=self.radial_distortion[2],\n p1=self.tangential_distortion[0],\n p2=self.tangential_distortion[1])","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.translation","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.translation#L225-L226","kind":"function","name":"translation","path":"scene/hyper_camera.py","language":"python","start_line":225,"end_line":226,"context_start_line":205,"context_end_line":246,"code":" def has_radial_distortion(self):\n return any(self.radial_distortion != 0.0)\n\n @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],\n k2=self.radial_distortion[1],\n k3=self.radial_distortion[2],\n p1=self.tangential_distortion[0],\n p2=self.tangential_distortion[1])\n\n dirs = np.stack([x, y, np.ones_like(x)], axis=-1)\n return dirs / np.linalg.norm(dirs, axis=-1, keepdims=True)\n","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.pixel_to_local_rays","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.pixel_to_local_rays#L228-L245","kind":"function","name":"pixel_to_local_rays","path":"scene/hyper_camera.py","language":"python","start_line":228,"end_line":245,"context_start_line":208,"context_end_line":265,"code":" @property\n def image_size_y(self):\n return self.image_size[1]\n\n @property\n def image_size_x(self):\n return self.image_size[0]\n\n @property\n def image_shape(self):\n return self.image_size_y, self.image_size_x\n\n @property\n def optical_axis(self):\n return self.orientation[2, :]\n\n @property\n def translation(self):\n return -np.matmul(self.orientation, self.position)\n\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],\n k2=self.radial_distortion[1],\n k3=self.radial_distortion[2],\n p1=self.tangential_distortion[0],\n p2=self.tangential_distortion[1])\n\n dirs = np.stack([x, y, np.ones_like(x)], axis=-1)\n return dirs / np.linalg.norm(dirs, axis=-1, keepdims=True)\n\n def pixels_to_rays(self, pixels: np.ndarray) -> np.ndarray:\n \"\"\"Returns the rays for the provided pixels.\n\n Args:\n pixels: [A1, ..., An, 2] tensor or np.array containing 2d pixel positions.\n\n Returns:\n An array containing the normalized ray directions in world coordinates.\n \"\"\"\n if pixels.shape[-1] != 2:\n raise ValueError('The last dimension of pixels must be 2.')\n if pixels.dtype != self.dtype:\n raise ValueError(f'pixels dtype ({pixels.dtype!r}) must match camera '\n f'dtype ({self.dtype!r})')\n\n batch_shape = pixels.shape[:-1]\n pixels = np.reshape(pixels, (-1, 2))\n\n local_rays_dir = self.pixel_to_local_rays(pixels)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.pixels_to_rays","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.pixels_to_rays#L247-L272","kind":"function","name":"pixels_to_rays","path":"scene/hyper_camera.py","language":"python","start_line":247,"end_line":272,"context_start_line":227,"context_end_line":292,"code":"\n def pixel_to_local_rays(self, pixels: np.ndarray):\n \"\"\"Returns the local ray directions for the provided pixels.\"\"\"\n y = ((pixels[..., 1] - self.principal_point_y) / self.scale_factor_y)\n x = ((pixels[..., 0] - self.principal_point_x - y * self.skew) /\n self.scale_factor_x)\n\n if self.has_radial_distortion or self.has_tangential_distortion:\n x, y = _radial_and_tangential_undistort(\n x,\n y,\n k1=self.radial_distortion[0],\n k2=self.radial_distortion[1],\n k3=self.radial_distortion[2],\n p1=self.tangential_distortion[0],\n p2=self.tangential_distortion[1])\n\n dirs = np.stack([x, y, np.ones_like(x)], axis=-1)\n return dirs / np.linalg.norm(dirs, axis=-1, keepdims=True)\n\n def pixels_to_rays(self, pixels: np.ndarray) -> np.ndarray:\n \"\"\"Returns the rays for the provided pixels.\n\n Args:\n pixels: [A1, ..., An, 2] tensor or np.array containing 2d pixel positions.\n\n Returns:\n An array containing the normalized ray directions in world coordinates.\n \"\"\"\n if pixels.shape[-1] != 2:\n raise ValueError('The last dimension of pixels must be 2.')\n if pixels.dtype != self.dtype:\n raise ValueError(f'pixels dtype ({pixels.dtype!r}) must match camera '\n f'dtype ({self.dtype!r})')\n\n batch_shape = pixels.shape[:-1]\n pixels = np.reshape(pixels, (-1, 2))\n\n local_rays_dir = self.pixel_to_local_rays(pixels)\n rays_dir = np.matmul(self.orientation.T, local_rays_dir[..., np.newaxis])\n rays_dir = np.squeeze(rays_dir, axis=-1)\n\n # Normalize rays.\n rays_dir /= np.linalg.norm(rays_dir, axis=-1, keepdims=True)\n rays_dir = rays_dir.reshape((*batch_shape, 3))\n return rays_dir\n\n def pixels_to_points(self, pixels: np.ndarray, depth: np.ndarray):\n rays_through_pixels = self.pixels_to_rays(pixels)\n cosa = np.matmul(rays_through_pixels, self.optical_axis)\n points = (\n rays_through_pixels * depth[..., np.newaxis] / cosa[..., np.newaxis] +\n self.position)\n return points\n\n def points_to_local_points(self, points: np.ndarray):\n translated_points = points - self.position\n local_points = (np.matmul(self.orientation, translated_points.T)).T\n return local_points\n\n def project(self, points: np.ndarray):\n \"\"\"Projects a 3D point (x,y,z) to a pixel position (x,y).\"\"\"\n batch_shape = points.shape[:-1]\n points = points.reshape((-1, 3))\n local_points = self.points_to_local_points(points)\n","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.pixels_to_points","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.pixels_to_points#L274-L280","kind":"function","name":"pixels_to_points","path":"scene/hyper_camera.py","language":"python","start_line":274,"end_line":280,"context_start_line":254,"context_end_line":300,"code":" An array containing the normalized ray directions in world coordinates.\n \"\"\"\n if pixels.shape[-1] != 2:\n raise ValueError('The last dimension of pixels must be 2.')\n if pixels.dtype != self.dtype:\n raise ValueError(f'pixels dtype ({pixels.dtype!r}) must match camera '\n f'dtype ({self.dtype!r})')\n\n batch_shape = pixels.shape[:-1]\n pixels = np.reshape(pixels, (-1, 2))\n\n local_rays_dir = self.pixel_to_local_rays(pixels)\n rays_dir = np.matmul(self.orientation.T, local_rays_dir[..., np.newaxis])\n rays_dir = np.squeeze(rays_dir, axis=-1)\n\n # Normalize rays.\n rays_dir /= np.linalg.norm(rays_dir, axis=-1, keepdims=True)\n rays_dir = rays_dir.reshape((*batch_shape, 3))\n return rays_dir\n\n def pixels_to_points(self, pixels: np.ndarray, depth: np.ndarray):\n rays_through_pixels = self.pixels_to_rays(pixels)\n cosa = np.matmul(rays_through_pixels, self.optical_axis)\n points = (\n rays_through_pixels * depth[..., np.newaxis] / cosa[..., np.newaxis] +\n self.position)\n return points\n\n def points_to_local_points(self, points: np.ndarray):\n translated_points = points - self.position\n local_points = (np.matmul(self.orientation, translated_points.T)).T\n return local_points\n\n def project(self, points: np.ndarray):\n \"\"\"Projects a 3D point (x,y,z) to a pixel position (x,y).\"\"\"\n batch_shape = points.shape[:-1]\n points = points.reshape((-1, 3))\n local_points = self.points_to_local_points(points)\n\n # Get normalized local pixel positions.\n x = local_points[..., 0] / local_points[..., 2]\n y = local_points[..., 1] / local_points[..., 2]\n r2 = x**2 + y**2\n\n # Apply radial distortion.\n distortion = 1.0 + r2 * (\n self.radial_distortion[0] + r2 *","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.points_to_local_points","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.points_to_local_points#L282-L285","kind":"function","name":"points_to_local_points","path":"scene/hyper_camera.py","language":"python","start_line":282,"end_line":285,"context_start_line":262,"context_end_line":305,"code":" batch_shape = pixels.shape[:-1]\n pixels = np.reshape(pixels, (-1, 2))\n\n local_rays_dir = self.pixel_to_local_rays(pixels)\n rays_dir = np.matmul(self.orientation.T, local_rays_dir[..., np.newaxis])\n rays_dir = np.squeeze(rays_dir, axis=-1)\n\n # Normalize rays.\n rays_dir /= np.linalg.norm(rays_dir, axis=-1, keepdims=True)\n rays_dir = rays_dir.reshape((*batch_shape, 3))\n return rays_dir\n\n def pixels_to_points(self, pixels: np.ndarray, depth: np.ndarray):\n rays_through_pixels = self.pixels_to_rays(pixels)\n cosa = np.matmul(rays_through_pixels, self.optical_axis)\n points = (\n rays_through_pixels * depth[..., np.newaxis] / cosa[..., np.newaxis] +\n self.position)\n return points\n\n def points_to_local_points(self, points: np.ndarray):\n translated_points = points - self.position\n local_points = (np.matmul(self.orientation, translated_points.T)).T\n return local_points\n\n def project(self, points: np.ndarray):\n \"\"\"Projects a 3D point (x,y,z) to a pixel position (x,y).\"\"\"\n batch_shape = points.shape[:-1]\n points = points.reshape((-1, 3))\n local_points = self.points_to_local_points(points)\n\n # Get normalized local pixel positions.\n x = local_points[..., 0] / local_points[..., 2]\n y = local_points[..., 1] / local_points[..., 2]\n r2 = x**2 + y**2\n\n # Apply radial distortion.\n distortion = 1.0 + r2 * (\n self.radial_distortion[0] + r2 *\n (self.radial_distortion[1] + self.radial_distortion[2] * r2))\n\n # Apply tangential distortion.\n x_times_y = x * y\n x = (","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.project","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.project#L287-L318","kind":"function","name":"project","path":"scene/hyper_camera.py","language":"python","start_line":287,"end_line":318,"context_start_line":267,"context_end_line":338,"code":" rays_dir = np.squeeze(rays_dir, axis=-1)\n\n # Normalize rays.\n rays_dir /= np.linalg.norm(rays_dir, axis=-1, keepdims=True)\n rays_dir = rays_dir.reshape((*batch_shape, 3))\n return rays_dir\n\n def pixels_to_points(self, pixels: np.ndarray, depth: np.ndarray):\n rays_through_pixels = self.pixels_to_rays(pixels)\n cosa = np.matmul(rays_through_pixels, self.optical_axis)\n points = (\n rays_through_pixels * depth[..., np.newaxis] / cosa[..., np.newaxis] +\n self.position)\n return points\n\n def points_to_local_points(self, points: np.ndarray):\n translated_points = points - self.position\n local_points = (np.matmul(self.orientation, translated_points.T)).T\n return local_points\n\n def project(self, points: np.ndarray):\n \"\"\"Projects a 3D point (x,y,z) to a pixel position (x,y).\"\"\"\n batch_shape = points.shape[:-1]\n points = points.reshape((-1, 3))\n local_points = self.points_to_local_points(points)\n\n # Get normalized local pixel positions.\n x = local_points[..., 0] / local_points[..., 2]\n y = local_points[..., 1] / local_points[..., 2]\n r2 = x**2 + y**2\n\n # Apply radial distortion.\n distortion = 1.0 + r2 * (\n self.radial_distortion[0] + r2 *\n (self.radial_distortion[1] + self.radial_distortion[2] * r2))\n\n # Apply tangential distortion.\n x_times_y = x * y\n x = (\n x * distortion + 2.0 * self.tangential_distortion[0] * x_times_y +\n self.tangential_distortion[1] * (r2 + 2.0 * x**2))\n y = (\n y * distortion + 2.0 * self.tangential_distortion[1] * x_times_y +\n self.tangential_distortion[0] * (r2 + 2.0 * y**2))\n\n # Map the distorted ray to the image plane and return the depth.\n pixel_x = self.focal_length * x + self.skew * y + self.principal_point_x\n pixel_y = (self.focal_length * self.pixel_aspect_ratio * y\n + self.principal_point_y)\n\n pixels = np.stack([pixel_x, pixel_y], axis=-1)\n return pixels.reshape((*batch_shape, 2))\n\n def get_pixel_centers(self):\n \"\"\"Returns the pixel centers.\"\"\"\n xx, yy = np.meshgrid(np.arange(self.image_size_x, dtype=self.dtype),\n np.arange(self.image_size_y, dtype=self.dtype))\n return np.stack([xx, yy], axis=-1) + 0.5\n\n def scale(self, scale: float):\n \"\"\"Scales the camera.\"\"\"\n if scale <= 0:\n raise ValueError('scale needs to be positive.')\n\n new_camera = Camera(\n orientation=self.orientation.copy(),\n position=self.position.copy(),\n focal_length=self.focal_length * scale,\n principal_point=self.principal_point.copy() * scale,\n skew=self.skew,\n pixel_aspect_ratio=self.pixel_aspect_ratio,\n radial_distortion=self.radial_distortion.copy(),","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.get_pixel_centers","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.get_pixel_centers#L320-L324","kind":"function","name":"get_pixel_centers","path":"scene/hyper_camera.py","language":"python","start_line":320,"end_line":324,"context_start_line":300,"context_end_line":344,"code":" self.radial_distortion[0] + r2 *\n (self.radial_distortion[1] + self.radial_distortion[2] * r2))\n\n # Apply tangential distortion.\n x_times_y = x * y\n x = (\n x * distortion + 2.0 * self.tangential_distortion[0] * x_times_y +\n self.tangential_distortion[1] * (r2 + 2.0 * x**2))\n y = (\n y * distortion + 2.0 * self.tangential_distortion[1] * x_times_y +\n self.tangential_distortion[0] * (r2 + 2.0 * y**2))\n\n # Map the distorted ray to the image plane and return the depth.\n pixel_x = self.focal_length * x + self.skew * y + self.principal_point_x\n pixel_y = (self.focal_length * self.pixel_aspect_ratio * y\n + self.principal_point_y)\n\n pixels = np.stack([pixel_x, pixel_y], axis=-1)\n return pixels.reshape((*batch_shape, 2))\n\n def get_pixel_centers(self):\n \"\"\"Returns the pixel centers.\"\"\"\n xx, yy = np.meshgrid(np.arange(self.image_size_x, dtype=self.dtype),\n np.arange(self.image_size_y, dtype=self.dtype))\n return np.stack([xx, yy], axis=-1) + 0.5\n\n def scale(self, scale: float):\n \"\"\"Scales the camera.\"\"\"\n if scale <= 0:\n raise ValueError('scale needs to be positive.')\n\n new_camera = Camera(\n orientation=self.orientation.copy(),\n position=self.position.copy(),\n focal_length=self.focal_length * scale,\n principal_point=self.principal_point.copy() * scale,\n skew=self.skew,\n pixel_aspect_ratio=self.pixel_aspect_ratio,\n radial_distortion=self.radial_distortion.copy(),\n tangential_distortion=self.tangential_distortion.copy(),\n image_size=np.array((int(round(self.image_size[0] * scale)),\n int(round(self.image_size[1] * scale)))),\n )\n return new_camera\n","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.scale","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.scale#L326-L343","kind":"function","name":"scale","path":"scene/hyper_camera.py","language":"python","start_line":326,"end_line":343,"context_start_line":306,"context_end_line":363,"code":" x * distortion + 2.0 * self.tangential_distortion[0] * x_times_y +\n self.tangential_distortion[1] * (r2 + 2.0 * x**2))\n y = (\n y * distortion + 2.0 * self.tangential_distortion[1] * x_times_y +\n self.tangential_distortion[0] * (r2 + 2.0 * y**2))\n\n # Map the distorted ray to the image plane and return the depth.\n pixel_x = self.focal_length * x + self.skew * y + self.principal_point_x\n pixel_y = (self.focal_length * self.pixel_aspect_ratio * y\n + self.principal_point_y)\n\n pixels = np.stack([pixel_x, pixel_y], axis=-1)\n return pixels.reshape((*batch_shape, 2))\n\n def get_pixel_centers(self):\n \"\"\"Returns the pixel centers.\"\"\"\n xx, yy = np.meshgrid(np.arange(self.image_size_x, dtype=self.dtype),\n np.arange(self.image_size_y, dtype=self.dtype))\n return np.stack([xx, yy], axis=-1) + 0.5\n\n def scale(self, scale: float):\n \"\"\"Scales the camera.\"\"\"\n if scale <= 0:\n raise ValueError('scale needs to be positive.')\n\n new_camera = Camera(\n orientation=self.orientation.copy(),\n position=self.position.copy(),\n focal_length=self.focal_length * scale,\n principal_point=self.principal_point.copy() * scale,\n skew=self.skew,\n pixel_aspect_ratio=self.pixel_aspect_ratio,\n radial_distortion=self.radial_distortion.copy(),\n tangential_distortion=self.tangential_distortion.copy(),\n image_size=np.array((int(round(self.image_size[0] * scale)),\n int(round(self.image_size[1] * scale)))),\n )\n return new_camera\n\n def look_at(self, position, look_at, up, eps=1e-6):\n \"\"\"Creates a copy of the camera which looks at a given point.\n\n Copies the provided vision_sfm camera and returns a new camera that is\n positioned at `camera_position` while looking at `look_at_position`.\n Camera intrinsics are copied by this method. A common value for the\n up_vector is (0, 1, 0).\n\n Args:\n position: A (3,) numpy array representing the position of the camera.\n look_at: A (3,) numpy array representing the location the camera\n looks at.\n up: A (3,) numpy array representing the up direction, whose\n projection is parallel to the y-axis of the image plane.\n eps: a small number to prevent divides by zero.\n\n Returns:\n A new camera that is copied from the original but is positioned and\n looks at the provided coordinates.","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.look_at","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.look_at#L345-L393","kind":"function","name":"look_at","path":"scene/hyper_camera.py","language":"python","start_line":345,"end_line":393,"context_start_line":325,"context_end_line":413,"code":"\n def scale(self, scale: float):\n \"\"\"Scales the camera.\"\"\"\n if scale <= 0:\n raise ValueError('scale needs to be positive.')\n\n new_camera = Camera(\n orientation=self.orientation.copy(),\n position=self.position.copy(),\n focal_length=self.focal_length * scale,\n principal_point=self.principal_point.copy() * scale,\n skew=self.skew,\n pixel_aspect_ratio=self.pixel_aspect_ratio,\n radial_distortion=self.radial_distortion.copy(),\n tangential_distortion=self.tangential_distortion.copy(),\n image_size=np.array((int(round(self.image_size[0] * scale)),\n int(round(self.image_size[1] * scale)))),\n )\n return new_camera\n\n def look_at(self, position, look_at, up, eps=1e-6):\n \"\"\"Creates a copy of the camera which looks at a given point.\n\n Copies the provided vision_sfm camera and returns a new camera that is\n positioned at `camera_position` while looking at `look_at_position`.\n Camera intrinsics are copied by this method. A common value for the\n up_vector is (0, 1, 0).\n\n Args:\n position: A (3,) numpy array representing the position of the camera.\n look_at: A (3,) numpy array representing the location the camera\n looks at.\n up: A (3,) numpy array representing the up direction, whose\n projection is parallel to the y-axis of the image plane.\n eps: a small number to prevent divides by zero.\n\n Returns:\n A new camera that is copied from the original but is positioned and\n looks at the provided coordinates.\n\n Raises:\n ValueError: If the camera position and look at position are very close\n to each other or if the up-vector is parallel to the requested optical\n axis.\n \"\"\"\n\n look_at_camera = self.copy()\n optical_axis = look_at - position\n norm = np.linalg.norm(optical_axis)\n if norm < eps:\n raise ValueError('The camera center and look at position are too close.')\n optical_axis /= norm\n\n right_vector = np.cross(optical_axis, up)\n norm = np.linalg.norm(right_vector)\n if norm < eps:\n raise ValueError('The up-vector is parallel to the optical axis.')\n right_vector /= norm\n\n # The three directions here are orthogonal to each other and form a right\n # handed coordinate system.\n camera_rotation = np.identity(3)\n camera_rotation[0, :] = right_vector\n camera_rotation[1, :] = np.cross(optical_axis, right_vector)\n camera_rotation[2, :] = optical_axis\n\n look_at_camera.position = position\n look_at_camera.orientation = camera_rotation\n return look_at_camera\n\n def crop_image_domain(\n self, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0):\n \"\"\"Returns a copy of the camera with adjusted image bounds.\n\n Args:\n left: number of pixels by which to reduce (or augment, if negative) the\n image domain at the associated boundary.\n right: likewise.\n top: likewise.\n bottom: likewise.\n\n The crop parameters may not cause the camera image domain dimensions to\n become non-positive.\n\n Returns:\n A camera with adjusted image dimensions. The focal length is unchanged,\n and the principal point is updated to preserve the original principal\n axis.\n \"\"\"","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.crop_image_domain","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.crop_image_domain#L395-L427","kind":"function","name":"crop_image_domain","path":"scene/hyper_camera.py","language":"python","start_line":395,"end_line":427,"context_start_line":375,"context_end_line":430,"code":" raise ValueError('The camera center and look at position are too close.')\n optical_axis /= norm\n\n right_vector = np.cross(optical_axis, up)\n norm = np.linalg.norm(right_vector)\n if norm < eps:\n raise ValueError('The up-vector is parallel to the optical axis.')\n right_vector /= norm\n\n # The three directions here are orthogonal to each other and form a right\n # handed coordinate system.\n camera_rotation = np.identity(3)\n camera_rotation[0, :] = right_vector\n camera_rotation[1, :] = np.cross(optical_axis, right_vector)\n camera_rotation[2, :] = optical_axis\n\n look_at_camera.position = position\n look_at_camera.orientation = camera_rotation\n return look_at_camera\n\n def crop_image_domain(\n self, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0):\n \"\"\"Returns a copy of the camera with adjusted image bounds.\n\n Args:\n left: number of pixels by which to reduce (or augment, if negative) the\n image domain at the associated boundary.\n right: likewise.\n top: likewise.\n bottom: likewise.\n\n The crop parameters may not cause the camera image domain dimensions to\n become non-positive.\n\n Returns:\n A camera with adjusted image dimensions. The focal length is unchanged,\n and the principal point is updated to preserve the original principal\n axis.\n \"\"\"\n\n crop_left_top = np.array([left, top])\n crop_right_bottom = np.array([right, bottom])\n new_resolution = self.image_size - crop_left_top - crop_right_bottom\n new_principal_point = self.principal_point - crop_left_top\n if np.any(new_resolution <= 0):\n raise ValueError('Crop would result in non-positive image dimensions.')\n\n new_camera = self.copy()\n new_camera.image_size = np.array([int(new_resolution[0]),\n int(new_resolution[1])])\n new_camera.principal_point = np.array([new_principal_point[0],\n new_principal_point[1]])\n return new_camera\n\n def copy(self):\n return copy.deepcopy(self)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.hyper_camera.copy","uri":"program://EfficientDynamic3DGaussian/function/scene.hyper_camera.copy#L429-L430","kind":"function","name":"copy","path":"scene/hyper_camera.py","language":"python","start_line":429,"end_line":430,"context_start_line":409,"context_end_line":430,"code":" Returns:\n A camera with adjusted image dimensions. The focal length is unchanged,\n and the principal point is updated to preserve the original principal\n axis.\n \"\"\"\n\n crop_left_top = np.array([left, top])\n crop_right_bottom = np.array([right, bottom])\n new_resolution = self.image_size - crop_left_top - crop_right_bottom\n new_principal_point = self.principal_point - crop_left_top\n if np.any(new_resolution <= 0):\n raise ValueError('Crop would result in non-positive image dimensions.')\n\n new_camera = self.copy()\n new_camera.image_size = np.array([int(new_resolution[0]),\n int(new_resolution[1])])\n new_camera.principal_point = np.array([new_principal_point[0],\n new_principal_point[1]])\n return new_camera\n\n def copy(self):\n return copy.deepcopy(self)","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers","uri":"program://EfficientDynamic3DGaussian/module/scene.dataset_readers#L1-L763","kind":"module","name":"scene.dataset_readers","path":"scene/dataset_readers.py","language":"python","start_line":1,"end_line":763,"context_start_line":1,"context_end_line":763,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\nimport torch\nimport os\nimport sys\nimport glob\nfrom PIL import Image\nfrom typing import NamedTuple\nfrom scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \\\n read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text\nfrom utils.graphics_utils import getWorld2View2, focal2fov, fov2focal\nimport numpy as np\nimport json\nfrom pathlib import Path\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import SH2RGB\nfrom scene.gaussian_model import BasicPointCloud\nfrom scene.hyper_camera import Camera as HyperNeRFCamera\n\n\nclass CameraInfo(NamedTuple):\n uid: int\n R: np.array\n T: np.array\n FovY: np.array\n FovX: np.array\n image: np.array\n image_path: str\n image_name: str\n width: int\n height: int\n time: float\n\nclass SceneInfo(NamedTuple):\n point_cloud: BasicPointCloud\n train_cameras: list\n test_cameras: list\n vis_cameras: list\n nerf_normalization: dict\n ply_path: str\n time_delta: float\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n pose_avg: (3, 4) the average pose\n \"\"\"\n # 1. Compute the center\n center = poses[..., 3].mean(0) # (3)\n\n # 2. Compute the z axis\n z = normalize(poses[..., 2].mean(0)) # (3)\n\n # 3. Compute axis y' (no need to normalize as it's not the final output)\n y_ = poses[..., 1].mean(0) # (3)\n\n # 4. Compute the x axis\n x = normalize(np.cross(z, y_)) # (3)\n\n # 5. Compute the y axis (as z and x are normalized, y is already of norm 1)\n y = np.cross(x, z) # (3)\n\n pose_avg = np.stack([x, y, z, center], 1) # (3, 4)\n\n return pose_avg\n\n\ndef center_poses(poses, blender2opencv):\n \"\"\"\n Center the poses so that we can use NDC.\n See https://github.com/bmild/nerf/issues/34\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n poses_centered: (N_images, 3, 4) the centered poses\n pose_avg: (3, 4) the average pose\n \"\"\"\n poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\n\ndef getNerfppNorm(cam_info):\n def get_center_and_diag(cam_centers):\n cam_centers = np.hstack(cam_centers)\n avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)\n center = avg_cam_center\n dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)\n diagonal = np.max(dist)\n return center.flatten(), diagonal\n\n cam_centers = []\n\n for cam in cam_info:\n W2C = getWorld2View2(cam.R, cam.T)\n C2W = np.linalg.inv(W2C)\n cam_centers.append(C2W[:3, 3:4])\n\n center, diagonal = get_center_and_diag(cam_centers)\n radius = diagonal * 1.1\n\n translate = -center\n\n return {\"translate\": translate, \"radius\": radius}\n\ndef readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder):\n cam_infos = []\n for idx, key in enumerate(cam_extrinsics):\n sys.stdout.write('\\r')\n # the exact output you're looking for:\n sys.stdout.write(\"Reading camera {}/{}\".format(idx+1, len(cam_extrinsics)))\n sys.stdout.flush()\n\n extr = cam_extrinsics[key]\n intr = cam_intrinsics[extr.camera_id]\n height = intr.height\n width = intr.width\n\n uid = intr.id\n R = np.transpose(qvec2rotmat(extr.qvec))\n T = np.array(extr.tvec)\n\n if intr.model==\"SIMPLE_PINHOLE\":\n focal_length_x = intr.params[0]\n FovY = focal2fov(focal_length_x, height)\n FovX = focal2fov(focal_length_x, width)\n elif intr.model==\"PINHOLE\":\n focal_length_x = intr.params[0]\n focal_length_y = intr.params[1]\n FovY = focal2fov(focal_length_y, height)\n FovX = focal2fov(focal_length_x, width)\n else:\n assert False, \"Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!\"\n\n image_path = os.path.join(images_folder, os.path.basename(extr.name))\n image_name = os.path.basename(image_path).split(\".\")[0]\n image = Image.open(image_path)\n\n cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=0)\n cam_infos.append(cam_info)\n sys.stdout.write('\\n')\n return cam_infos\n\ndef fetchPly(path):\n plydata = PlyData.read(path)\n vertices = plydata['vertex']\n\n colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0\n normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((colors.shape[0], len(x_names)))\n y = np.zeros((colors.shape[0], len(y_names)))\n z = np.zeros((colors.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T\n positions = np.stack([x, y, z], axis=-1)\n assert len(positions.shape) == 3\n assert positions.shape[-1] == 3\n return BasicPointCloud(points=positions, colors=colors, normals=normals)\n\ndef storePly(path, xyz, rgb):\n # Define the dtype for the structured array\n dtype = []\n for t in range(xyz.shape[1]):\n dtype.extend([(f'x{t}', 'f4'), (f'y{t}', 'f4'), (f'z{t}', 'f4')])\n dtype = dtype + [('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'),\n ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]\n \n normals = np.zeros_like(xyz[:, 0, :])\n\n elements = np.empty(xyz.shape[0], dtype=dtype)\n attributes = np.concatenate((xyz.reshape(xyz.shape[0], -1), normals, rgb), axis=1)\n elements[:] = list(map(tuple, attributes))\n\n # Create the PlyData object and write to file\n vertex_element = PlyElement.describe(elements, 'vertex')\n ply_data = PlyData([vertex_element])\n ply_data.write(path)\n\ndef readColmapSceneInfo(path, images, eval, llffhold=8):\n try:\n cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.bin\")\n cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.bin\")\n cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)\n cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file)\n except:\n cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.txt\")\n cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.txt\")\n cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file)\n cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file)\n\n reading_dir = \"images\" if images == None else images\n cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir))\n cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name)\n\n if eval:\n train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0]\n test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0]\n else:\n train_cam_infos = cam_infos\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"sparse/0/points3D_ours.ply\")\n bin_path = os.path.join(path, \"sparse/0/points3D.bin\")\n txt_path = os.path.join(path, \"sparse/0/points3D.txt\")\n if not os.path.exists(ply_path):\n print(\"Converting point3d.bin to .ply, will happen only the first time you open the scene.\")\n try:\n xyz, rgb, _ = read_points3D_binary(bin_path)\n except:\n xyz, rgb, _ = read_points3D_text(txt_path)\n xyz = xyz[:, None, :]\n storePly(ply_path, xyz, rgb)\n try:\n pcd = fetchPly(ply_path)\n except:\n pcd = None\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path)\n return scene_info\n\ndef readCamerasFromTransforms(path, transformsfile, white_background, extension=\".png\"):\n cam_infos = []\n\n with open(os.path.join(path, transformsfile)) as json_file:\n contents = json.load(json_file)\n fovx = contents[\"camera_angle_x\"]\n\n frames = contents[\"frames\"]\n # if 'time' in frames[0]:\n # times = np.array([frame['time'] for idx, frame in enumerate(frames)])\n # time_idx = times.argsort()\n # else:\n # time_idx = [0 for f in frames]\n # print(times)\n # print(time_idx)\n for idx, frame in enumerate(frames):\n cam_name = os.path.join(path, frame[\"file_path\"] + extension)\n\n # NeRF 'transform_matrix' is a camera-to-world transform\n c2w = np.array(frame[\"transform_matrix\"])\n # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward)\n c2w[:3, 1:3] *= -1\n\n # get the world-to-camera transform and set R, T\n w2c = np.linalg.inv(c2w)\n R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code\n T = w2c[:3, 3]\n\n image_path = os.path.join(path, cam_name)\n image_name = Path(cam_name).stem\n image = Image.open(image_path)\n\n im_data = np.array(image.convert(\"RGBA\"))\n\n bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0])\n\n norm_data = im_data / 255.0\n arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4])\n image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), \"RGB\")\n\n fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1])\n FovY = fovy \n FovX = fovx\n time = frame['time'] if 'time' in frame else 0\n\n cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name,\n width=image.size[0], height=image.size[1], time=time))\n \n return cam_infos\n\n\n# https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\ntrans_t = lambda t : torch.Tensor([\n [1,0,0,0],\n [0,1,0,0],\n [0,0,1,t],\n [0,0,0,1]]).float()\n\nrot_phi = lambda phi : torch.Tensor([\n [1,0,0,0],\n [0,np.cos(phi),-np.sin(phi),0],\n [0,np.sin(phi), np.cos(phi),0],\n [0,0,0,1]]).float()\n\nrot_theta = lambda th : torch.Tensor([\n [np.cos(th),0,-np.sin(th),0],\n [0,1,0,0],\n [np.sin(th),0, np.cos(th),0],\n [0,0,0,1]]).float()\n\ndef pose_spherical(theta, phi, radius):\n # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\n c2w = trans_t(radius)\n c2w = rot_phi(phi/180.*np.pi) @ c2w\n c2w = rot_theta(theta/180.*np.pi) @ c2w\n c2w = torch.Tensor(np.array([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])) @ c2w\n return c2w\n\ndef generateCamerasFromTransforms(path, transformsfile, extension=\".png\"):\n cam_infos = []\n\n # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\n render_poses = torch.stack([pose_spherical(angle, -30.0, 4.0) for angle in np.linspace(-180,180,40+1)[:-1]], 0)\n render_times = torch.linspace(0., 1., render_poses.shape[0]) \n\n with open(os.path.join(path, transformsfile)) as json_file:\n contents = json.load(json_file)\n fovx = contents[\"camera_angle_x\"]\n\n frames = contents[\"frames\"]\n cam_name = os.path.join(path, frames[0][\"file_path\"] + extension) \n image_path = os.path.join(path, cam_name)\n image_name = Path(cam_name).stem\n image = Image.open(image_path)\n width = image.size[0]\n height = image.size[1]\n\n for idx, (c2w, time) in enumerate(zip(render_poses, render_times)):\n c2w[:3, 1:3] *= -1\n\n # get the world-to-camera transform and set R, T\n w2c = np.linalg.inv(c2w)\n R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code\n T = w2c[:3, 3]\n\n fovy = focal2fov(fov2focal(fovx, width), height)\n FovY = fovy \n FovX = fovx\n\n cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, \n image=None, image_path=None, image_name=None,\n width=width, height=height, time=time))\n \n return cam_infos\n\n\ndef init_random_points(ply_path):\n if not os.path.exists(ply_path):\n # Since this data set has no colmap data, we start with random points\n num_pts = 100_000\n print(f\"Generating random point cloud ({num_pts})...\")\n \n # We create random points inside the bounds of the synthetic Blender scenes\n # time_length = max([c.time for c in train_cam_infos]) + 1\n # time_length = 2\n # xyz = np.random.random((num_pts, 1, 3)) * 2.6 - 1.3\n # xyz = np.tile(xyz, (1, time_length, 1))\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 16, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 3, 3)), np.ones((num_pts, 1, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n storePly(ply_path, xyz, SH2RGB(shs) * 255)\n # try:\n pcd = fetchPly(ply_path)\n # except:\n # pcd = None\n return pcd\n\ndef readNerfSyntheticInfo(path, white_background, eval, extension=\".png\"):\n print(\"Reading Training Transforms\")\n train_cam_infos = readCamerasFromTransforms(path, \"transforms_train.json\", white_background, extension)\n print(\"Reading Test Transforms\")\n test_cam_infos = readCamerasFromTransforms(path, \"transforms_test.json\", white_background, extension)\n \n vis_cam_infos = generateCamerasFromTransforms(path, \"transforms_train.json\")\n\n if not eval:\n train_cam_infos.extend(test_cam_infos)\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"points3d_ours.ply\")\n pcd = init_random_points(ply_path)\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras=vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/len(train_cam_infos))\n return scene_info\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"\n Generate a set of poses using NeRF's spiral camera trajectory as validation poses.\n \"\"\"\n # center pose\n c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\ndef readDynerfSceneInfo(path, eval):\n blender2opencv = np.eye(4)\n downsample = 2\n\n poses_arr = np.load(os.path.join(path, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(path, \"cam??\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / downsample\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, blender2opencv\n ) # Re-center poses so that the average is near the center.\n \n near_original = near_fars.min()\n scale_factor = near_original * 0.75\n near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n # print(scale_factor)\n poses[..., 3] /= scale_factor\n \n image_dirs = [video.replace('.mp4', '') for video in videos]\n val_index = [0]\n images = [sorted(glob.glob(os.path.join(d, \"*.png\")), key=lambda x:int(os.path.splitext(os.path.basename(x))\n# ... truncated ...","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":true} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.CameraInfo","uri":"program://EfficientDynamic3DGaussian/class/scene.dataset_readers.CameraInfo#L29-L40","kind":"class","name":"CameraInfo","path":"scene/dataset_readers.py","language":"python","start_line":29,"end_line":40,"context_start_line":9,"context_end_line":60,"code":"# For inquiries contact george.drettakis@inria.fr\n#\nimport torch\nimport os\nimport sys\nimport glob\nfrom PIL import Image\nfrom typing import NamedTuple\nfrom scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \\\n read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text\nfrom utils.graphics_utils import getWorld2View2, focal2fov, fov2focal\nimport numpy as np\nimport json\nfrom pathlib import Path\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import SH2RGB\nfrom scene.gaussian_model import BasicPointCloud\nfrom scene.hyper_camera import Camera as HyperNeRFCamera\n\n\nclass CameraInfo(NamedTuple):\n uid: int\n R: np.array\n T: np.array\n FovY: np.array\n FovX: np.array\n image: np.array\n image_path: str\n image_name: str\n width: int\n height: int\n time: float\n\nclass SceneInfo(NamedTuple):\n point_cloud: BasicPointCloud\n train_cameras: list\n test_cameras: list\n vis_cameras: list\n nerf_normalization: dict\n ply_path: str\n time_delta: float\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.SceneInfo","uri":"program://EfficientDynamic3DGaussian/class/scene.dataset_readers.SceneInfo#L42-L49","kind":"class","name":"SceneInfo","path":"scene/dataset_readers.py","language":"python","start_line":42,"end_line":49,"context_start_line":22,"context_end_line":69,"code":"from pathlib import Path\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import SH2RGB\nfrom scene.gaussian_model import BasicPointCloud\nfrom scene.hyper_camera import Camera as HyperNeRFCamera\n\n\nclass CameraInfo(NamedTuple):\n uid: int\n R: np.array\n T: np.array\n FovY: np.array\n FovX: np.array\n image: np.array\n image_path: str\n image_name: str\n width: int\n height: int\n time: float\n\nclass SceneInfo(NamedTuple):\n point_cloud: BasicPointCloud\n train_cameras: list\n test_cameras: list\n vis_cameras: list\n nerf_normalization: dict\n ply_path: str\n time_delta: float\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.normalize","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.normalize#L51-L53","kind":"function","name":"normalize","path":"scene/dataset_readers.py","language":"python","start_line":51,"end_line":53,"context_start_line":31,"context_end_line":73,"code":" R: np.array\n T: np.array\n FovY: np.array\n FovX: np.array\n image: np.array\n image_path: str\n image_name: str\n width: int\n height: int\n time: float\n\nclass SceneInfo(NamedTuple):\n point_cloud: BasicPointCloud\n train_cameras: list\n test_cameras: list\n vis_cameras: list\n nerf_normalization: dict\n ply_path: str\n time_delta: float\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n pose_avg: (3, 4) the average pose\n \"\"\"\n # 1. Compute the center","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.average_poses","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.average_poses#L56-L90","kind":"function","name":"average_poses","path":"scene/dataset_readers.py","language":"python","start_line":56,"end_line":90,"context_start_line":36,"context_end_line":110,"code":" image_path: str\n image_name: str\n width: int\n height: int\n time: float\n\nclass SceneInfo(NamedTuple):\n point_cloud: BasicPointCloud\n train_cameras: list\n test_cameras: list\n vis_cameras: list\n nerf_normalization: dict\n ply_path: str\n time_delta: float\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):\n \"\"\"\n Calculate the average pose, which is then used to center all poses\n using @center_poses. Its computation is as follows:\n 1. Compute the center: the average of pose centers.\n 2. Compute the z axis: the normalized average z axis.\n 3. Compute axis y': the average y axis.\n 4. Compute x' = y' cross product z, then normalize it as the x axis.\n 5. Compute the y axis: z cross product x.\n\n Note that at step 3, we cannot directly use y' as y axis since it's\n not necessarily orthogonal to z axis. We need to pass from x to y.\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n pose_avg: (3, 4) the average pose\n \"\"\"\n # 1. Compute the center\n center = poses[..., 3].mean(0) # (3)\n\n # 2. Compute the z axis\n z = normalize(poses[..., 2].mean(0)) # (3)\n\n # 3. Compute axis y' (no need to normalize as it's not the final output)\n y_ = poses[..., 1].mean(0) # (3)\n\n # 4. Compute the x axis\n x = normalize(np.cross(z, y_)) # (3)\n\n # 5. Compute the y axis (as z and x are normalized, y is already of norm 1)\n y = np.cross(x, z) # (3)\n\n pose_avg = np.stack([x, y, z, center], 1) # (3, 4)\n\n return pose_avg\n\n\ndef center_poses(poses, blender2opencv):\n \"\"\"\n Center the poses so that we can use NDC.\n See https://github.com/bmild/nerf/issues/34\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n poses_centered: (N_images, 3, 4) the centered poses\n pose_avg: (3, 4) the average pose\n \"\"\"\n poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.center_poses","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.center_poses#L93-L120","kind":"function","name":"center_poses","path":"scene/dataset_readers.py","language":"python","start_line":93,"end_line":120,"context_start_line":73,"context_end_line":140,"code":" # 1. Compute the center\n center = poses[..., 3].mean(0) # (3)\n\n # 2. Compute the z axis\n z = normalize(poses[..., 2].mean(0)) # (3)\n\n # 3. Compute axis y' (no need to normalize as it's not the final output)\n y_ = poses[..., 1].mean(0) # (3)\n\n # 4. Compute the x axis\n x = normalize(np.cross(z, y_)) # (3)\n\n # 5. Compute the y axis (as z and x are normalized, y is already of norm 1)\n y = np.cross(x, z) # (3)\n\n pose_avg = np.stack([x, y, z, center], 1) # (3, 4)\n\n return pose_avg\n\n\ndef center_poses(poses, blender2opencv):\n \"\"\"\n Center the poses so that we can use NDC.\n See https://github.com/bmild/nerf/issues/34\n Inputs:\n poses: (N_images, 3, 4)\n Outputs:\n poses_centered: (N_images, 3, 4) the centered poses\n pose_avg: (3, 4) the average pose\n \"\"\"\n poses = poses @ blender2opencv\n pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\n\ndef getNerfppNorm(cam_info):\n def get_center_and_diag(cam_centers):\n cam_centers = np.hstack(cam_centers)\n avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)\n center = avg_cam_center\n dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)\n diagonal = np.max(dist)\n return center.flatten(), diagonal\n\n cam_centers = []\n\n for cam in cam_info:\n W2C = getWorld2View2(cam.R, cam.T)\n C2W = np.linalg.inv(W2C)\n cam_centers.append(C2W[:3, 3:4])\n\n center, diagonal = get_center_and_diag(cam_centers)","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.getNerfppNorm","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.getNerfppNorm#L124-L145","kind":"function","name":"getNerfppNorm","path":"scene/dataset_readers.py","language":"python","start_line":124,"end_line":145,"context_start_line":104,"context_end_line":165,"code":" pose_avg = average_poses(poses) # (3, 4)\n pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\n\ndef getNerfppNorm(cam_info):\n def get_center_and_diag(cam_centers):\n cam_centers = np.hstack(cam_centers)\n avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)\n center = avg_cam_center\n dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)\n diagonal = np.max(dist)\n return center.flatten(), diagonal\n\n cam_centers = []\n\n for cam in cam_info:\n W2C = getWorld2View2(cam.R, cam.T)\n C2W = np.linalg.inv(W2C)\n cam_centers.append(C2W[:3, 3:4])\n\n center, diagonal = get_center_and_diag(cam_centers)\n radius = diagonal * 1.1\n\n translate = -center\n\n return {\"translate\": translate, \"radius\": radius}\n\ndef readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder):\n cam_infos = []\n for idx, key in enumerate(cam_extrinsics):\n sys.stdout.write('\\r')\n # the exact output you're looking for:\n sys.stdout.write(\"Reading camera {}/{}\".format(idx+1, len(cam_extrinsics)))\n sys.stdout.flush()\n\n extr = cam_extrinsics[key]\n intr = cam_intrinsics[extr.camera_id]\n height = intr.height\n width = intr.width\n\n uid = intr.id\n R = np.transpose(qvec2rotmat(extr.qvec))\n T = np.array(extr.tvec)\n\n if intr.model==\"SIMPLE_PINHOLE\":\n focal_length_x = intr.params[0]","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readColmapCameras","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readColmapCameras#L147-L184","kind":"function","name":"readColmapCameras","path":"scene/dataset_readers.py","language":"python","start_line":147,"end_line":184,"context_start_line":127,"context_end_line":204,"code":" avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)\n center = avg_cam_center\n dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)\n diagonal = np.max(dist)\n return center.flatten(), diagonal\n\n cam_centers = []\n\n for cam in cam_info:\n W2C = getWorld2View2(cam.R, cam.T)\n C2W = np.linalg.inv(W2C)\n cam_centers.append(C2W[:3, 3:4])\n\n center, diagonal = get_center_and_diag(cam_centers)\n radius = diagonal * 1.1\n\n translate = -center\n\n return {\"translate\": translate, \"radius\": radius}\n\ndef readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder):\n cam_infos = []\n for idx, key in enumerate(cam_extrinsics):\n sys.stdout.write('\\r')\n # the exact output you're looking for:\n sys.stdout.write(\"Reading camera {}/{}\".format(idx+1, len(cam_extrinsics)))\n sys.stdout.flush()\n\n extr = cam_extrinsics[key]\n intr = cam_intrinsics[extr.camera_id]\n height = intr.height\n width = intr.width\n\n uid = intr.id\n R = np.transpose(qvec2rotmat(extr.qvec))\n T = np.array(extr.tvec)\n\n if intr.model==\"SIMPLE_PINHOLE\":\n focal_length_x = intr.params[0]\n FovY = focal2fov(focal_length_x, height)\n FovX = focal2fov(focal_length_x, width)\n elif intr.model==\"PINHOLE\":\n focal_length_x = intr.params[0]\n focal_length_y = intr.params[1]\n FovY = focal2fov(focal_length_y, height)\n FovX = focal2fov(focal_length_x, width)\n else:\n assert False, \"Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!\"\n\n image_path = os.path.join(images_folder, os.path.basename(extr.name))\n image_name = os.path.basename(image_path).split(\".\")[0]\n image = Image.open(image_path)\n\n cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=0)\n cam_infos.append(cam_info)\n sys.stdout.write('\\n')\n return cam_infos\n\ndef fetchPly(path):\n plydata = PlyData.read(path)\n vertices = plydata['vertex']\n\n colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0\n normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((colors.shape[0], len(x_names)))\n y = np.zeros((colors.shape[0], len(y_names)))\n z = np.zeros((colors.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.fetchPly","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.fetchPly#L186-L212","kind":"function","name":"fetchPly","path":"scene/dataset_readers.py","language":"python","start_line":186,"end_line":212,"context_start_line":166,"context_end_line":232,"code":" FovY = focal2fov(focal_length_x, height)\n FovX = focal2fov(focal_length_x, width)\n elif intr.model==\"PINHOLE\":\n focal_length_x = intr.params[0]\n focal_length_y = intr.params[1]\n FovY = focal2fov(focal_length_y, height)\n FovX = focal2fov(focal_length_x, width)\n else:\n assert False, \"Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!\"\n\n image_path = os.path.join(images_folder, os.path.basename(extr.name))\n image_name = os.path.basename(image_path).split(\".\")[0]\n image = Image.open(image_path)\n\n cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=0)\n cam_infos.append(cam_info)\n sys.stdout.write('\\n')\n return cam_infos\n\ndef fetchPly(path):\n plydata = PlyData.read(path)\n vertices = plydata['vertex']\n\n colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0\n normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T\n x_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"x\")]\n y_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"y\")]\n z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((colors.shape[0], len(x_names)))\n y = np.zeros((colors.shape[0], len(y_names)))\n z = np.zeros((colors.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T\n positions = np.stack([x, y, z], axis=-1)\n assert len(positions.shape) == 3\n assert positions.shape[-1] == 3\n return BasicPointCloud(points=positions, colors=colors, normals=normals)\n\ndef storePly(path, xyz, rgb):\n # Define the dtype for the structured array\n dtype = []\n for t in range(xyz.shape[1]):\n dtype.extend([(f'x{t}', 'f4'), (f'y{t}', 'f4'), (f'z{t}', 'f4')])\n dtype = dtype + [('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'),\n ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]\n \n normals = np.zeros_like(xyz[:, 0, :])\n\n elements = np.empty(xyz.shape[0], dtype=dtype)\n attributes = np.concatenate((xyz.reshape(xyz.shape[0], -1), normals, rgb), axis=1)\n elements[:] = list(map(tuple, attributes))\n\n # Create the PlyData object and write to file\n vertex_element = PlyElement.describe(elements, 'vertex')\n ply_data = PlyData([vertex_element])\n ply_data.write(path)\n","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.storePly","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.storePly#L214-L231","kind":"function","name":"storePly","path":"scene/dataset_readers.py","language":"python","start_line":214,"end_line":231,"context_start_line":194,"context_end_line":251,"code":" z_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"z\")]\n x_names = sorted(x_names, key = lambda x: int(x.replace('x', '')))\n y_names = sorted(y_names, key = lambda y: int(y.replace('y', '')))\n z_names = sorted(z_names, key = lambda z: int(z.replace('z', '')))\n assert len(x_names) == len(y_names) == len(z_names)\n x = np.zeros((colors.shape[0], len(x_names)))\n y = np.zeros((colors.shape[0], len(y_names)))\n z = np.zeros((colors.shape[0], len(z_names)))\n for idx, attr_name in enumerate(x_names):\n x[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(y_names):\n y[:, idx] = np.asarray(plydata.elements[0][attr_name])\n for idx, attr_name in enumerate(z_names):\n z[:, idx] = np.asarray(plydata.elements[0][attr_name])\n # positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T\n positions = np.stack([x, y, z], axis=-1)\n assert len(positions.shape) == 3\n assert positions.shape[-1] == 3\n return BasicPointCloud(points=positions, colors=colors, normals=normals)\n\ndef storePly(path, xyz, rgb):\n # Define the dtype for the structured array\n dtype = []\n for t in range(xyz.shape[1]):\n dtype.extend([(f'x{t}', 'f4'), (f'y{t}', 'f4'), (f'z{t}', 'f4')])\n dtype = dtype + [('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'),\n ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]\n \n normals = np.zeros_like(xyz[:, 0, :])\n\n elements = np.empty(xyz.shape[0], dtype=dtype)\n attributes = np.concatenate((xyz.reshape(xyz.shape[0], -1), normals, rgb), axis=1)\n elements[:] = list(map(tuple, attributes))\n\n # Create the PlyData object and write to file\n vertex_element = PlyElement.describe(elements, 'vertex')\n ply_data = PlyData([vertex_element])\n ply_data.write(path)\n\ndef readColmapSceneInfo(path, images, eval, llffhold=8):\n try:\n cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.bin\")\n cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.bin\")\n cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)\n cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file)\n except:\n cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.txt\")\n cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.txt\")\n cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file)\n cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file)\n\n reading_dir = \"images\" if images == None else images\n cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir))\n cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name)\n\n if eval:\n train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0]\n test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0]","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readColmapSceneInfo","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readColmapSceneInfo#L233-L279","kind":"function","name":"readColmapSceneInfo","path":"scene/dataset_readers.py","language":"python","start_line":233,"end_line":279,"context_start_line":213,"context_end_line":299,"code":"\ndef storePly(path, xyz, rgb):\n # Define the dtype for the structured array\n dtype = []\n for t in range(xyz.shape[1]):\n dtype.extend([(f'x{t}', 'f4'), (f'y{t}', 'f4'), (f'z{t}', 'f4')])\n dtype = dtype + [('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'),\n ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]\n \n normals = np.zeros_like(xyz[:, 0, :])\n\n elements = np.empty(xyz.shape[0], dtype=dtype)\n attributes = np.concatenate((xyz.reshape(xyz.shape[0], -1), normals, rgb), axis=1)\n elements[:] = list(map(tuple, attributes))\n\n # Create the PlyData object and write to file\n vertex_element = PlyElement.describe(elements, 'vertex')\n ply_data = PlyData([vertex_element])\n ply_data.write(path)\n\ndef readColmapSceneInfo(path, images, eval, llffhold=8):\n try:\n cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.bin\")\n cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.bin\")\n cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)\n cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file)\n except:\n cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.txt\")\n cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.txt\")\n cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file)\n cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file)\n\n reading_dir = \"images\" if images == None else images\n cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir))\n cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name)\n\n if eval:\n train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0]\n test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0]\n else:\n train_cam_infos = cam_infos\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"sparse/0/points3D_ours.ply\")\n bin_path = os.path.join(path, \"sparse/0/points3D.bin\")\n txt_path = os.path.join(path, \"sparse/0/points3D.txt\")\n if not os.path.exists(ply_path):\n print(\"Converting point3d.bin to .ply, will happen only the first time you open the scene.\")\n try:\n xyz, rgb, _ = read_points3D_binary(bin_path)\n except:\n xyz, rgb, _ = read_points3D_text(txt_path)\n xyz = xyz[:, None, :]\n storePly(ply_path, xyz, rgb)\n try:\n pcd = fetchPly(ply_path)\n except:\n pcd = None\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path)\n return scene_info\n\ndef readCamerasFromTransforms(path, transformsfile, white_background, extension=\".png\"):\n cam_infos = []\n\n with open(os.path.join(path, transformsfile)) as json_file:\n contents = json.load(json_file)\n fovx = contents[\"camera_angle_x\"]\n\n frames = contents[\"frames\"]\n # if 'time' in frames[0]:\n # times = np.array([frame['time'] for idx, frame in enumerate(frames)])\n # time_idx = times.argsort()\n # else:\n # time_idx = [0 for f in frames]\n # print(times)\n # print(time_idx)\n for idx, frame in enumerate(frames):\n cam_name = os.path.join(path, frame[\"file_path\"] + extension)\n\n # NeRF 'transform_matrix' is a camera-to-world transform","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readCamerasFromTransforms","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readCamerasFromTransforms#L281-L330","kind":"function","name":"readCamerasFromTransforms","path":"scene/dataset_readers.py","language":"python","start_line":281,"end_line":330,"context_start_line":261,"context_end_line":350,"code":" if not os.path.exists(ply_path):\n print(\"Converting point3d.bin to .ply, will happen only the first time you open the scene.\")\n try:\n xyz, rgb, _ = read_points3D_binary(bin_path)\n except:\n xyz, rgb, _ = read_points3D_text(txt_path)\n xyz = xyz[:, None, :]\n storePly(ply_path, xyz, rgb)\n try:\n pcd = fetchPly(ply_path)\n except:\n pcd = None\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path)\n return scene_info\n\ndef readCamerasFromTransforms(path, transformsfile, white_background, extension=\".png\"):\n cam_infos = []\n\n with open(os.path.join(path, transformsfile)) as json_file:\n contents = json.load(json_file)\n fovx = contents[\"camera_angle_x\"]\n\n frames = contents[\"frames\"]\n # if 'time' in frames[0]:\n # times = np.array([frame['time'] for idx, frame in enumerate(frames)])\n # time_idx = times.argsort()\n # else:\n # time_idx = [0 for f in frames]\n # print(times)\n # print(time_idx)\n for idx, frame in enumerate(frames):\n cam_name = os.path.join(path, frame[\"file_path\"] + extension)\n\n # NeRF 'transform_matrix' is a camera-to-world transform\n c2w = np.array(frame[\"transform_matrix\"])\n # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward)\n c2w[:3, 1:3] *= -1\n\n # get the world-to-camera transform and set R, T\n w2c = np.linalg.inv(c2w)\n R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code\n T = w2c[:3, 3]\n\n image_path = os.path.join(path, cam_name)\n image_name = Path(cam_name).stem\n image = Image.open(image_path)\n\n im_data = np.array(image.convert(\"RGBA\"))\n\n bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0])\n\n norm_data = im_data / 255.0\n arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4])\n image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), \"RGB\")\n\n fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1])\n FovY = fovy \n FovX = fovx\n time = frame['time'] if 'time' in frame else 0\n\n cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name,\n width=image.size[0], height=image.size[1], time=time))\n \n return cam_infos\n\n\n# https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\ntrans_t = lambda t : torch.Tensor([\n [1,0,0,0],\n [0,1,0,0],\n [0,0,1,t],\n [0,0,0,1]]).float()\n\nrot_phi = lambda phi : torch.Tensor([\n [1,0,0,0],\n [0,np.cos(phi),-np.sin(phi),0],\n [0,np.sin(phi), np.cos(phi),0],\n [0,0,0,1]]).float()\n\nrot_theta = lambda th : torch.Tensor([\n [np.cos(th),0,-np.sin(th),0],\n [0,1,0,0],\n [np.sin(th),0, np.cos(th),0],\n [0,0,0,1]]).float()","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.pose_spherical","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.pose_spherical#L352-L358","kind":"function","name":"pose_spherical","path":"scene/dataset_readers.py","language":"python","start_line":352,"end_line":358,"context_start_line":332,"context_end_line":378,"code":"\n# https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\ntrans_t = lambda t : torch.Tensor([\n [1,0,0,0],\n [0,1,0,0],\n [0,0,1,t],\n [0,0,0,1]]).float()\n\nrot_phi = lambda phi : torch.Tensor([\n [1,0,0,0],\n [0,np.cos(phi),-np.sin(phi),0],\n [0,np.sin(phi), np.cos(phi),0],\n [0,0,0,1]]).float()\n\nrot_theta = lambda th : torch.Tensor([\n [np.cos(th),0,-np.sin(th),0],\n [0,1,0,0],\n [np.sin(th),0, np.cos(th),0],\n [0,0,0,1]]).float()\n\ndef pose_spherical(theta, phi, radius):\n # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\n c2w = trans_t(radius)\n c2w = rot_phi(phi/180.*np.pi) @ c2w\n c2w = rot_theta(theta/180.*np.pi) @ c2w\n c2w = torch.Tensor(np.array([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])) @ c2w\n return c2w\n\ndef generateCamerasFromTransforms(path, transformsfile, extension=\".png\"):\n cam_infos = []\n\n # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\n render_poses = torch.stack([pose_spherical(angle, -30.0, 4.0) for angle in np.linspace(-180,180,40+1)[:-1]], 0)\n render_times = torch.linspace(0., 1., render_poses.shape[0]) \n\n with open(os.path.join(path, transformsfile)) as json_file:\n contents = json.load(json_file)\n fovx = contents[\"camera_angle_x\"]\n\n frames = contents[\"frames\"]\n cam_name = os.path.join(path, frames[0][\"file_path\"] + extension) \n image_path = os.path.join(path, cam_name)\n image_name = Path(cam_name).stem\n image = Image.open(image_path)\n width = image.size[0]\n height = image.size[1]\n","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.generateCamerasFromTransforms","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.generateCamerasFromTransforms#L360-L395","kind":"function","name":"generateCamerasFromTransforms","path":"scene/dataset_readers.py","language":"python","start_line":360,"end_line":395,"context_start_line":340,"context_end_line":415,"code":"rot_phi = lambda phi : torch.Tensor([\n [1,0,0,0],\n [0,np.cos(phi),-np.sin(phi),0],\n [0,np.sin(phi), np.cos(phi),0],\n [0,0,0,1]]).float()\n\nrot_theta = lambda th : torch.Tensor([\n [np.cos(th),0,-np.sin(th),0],\n [0,1,0,0],\n [np.sin(th),0, np.cos(th),0],\n [0,0,0,1]]).float()\n\ndef pose_spherical(theta, phi, radius):\n # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\n c2w = trans_t(radius)\n c2w = rot_phi(phi/180.*np.pi) @ c2w\n c2w = rot_theta(theta/180.*np.pi) @ c2w\n c2w = torch.Tensor(np.array([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])) @ c2w\n return c2w\n\ndef generateCamerasFromTransforms(path, transformsfile, extension=\".png\"):\n cam_infos = []\n\n # https://github.com/albertpumarola/D-NeRF/blob/main/load_blender.py\n render_poses = torch.stack([pose_spherical(angle, -30.0, 4.0) for angle in np.linspace(-180,180,40+1)[:-1]], 0)\n render_times = torch.linspace(0., 1., render_poses.shape[0]) \n\n with open(os.path.join(path, transformsfile)) as json_file:\n contents = json.load(json_file)\n fovx = contents[\"camera_angle_x\"]\n\n frames = contents[\"frames\"]\n cam_name = os.path.join(path, frames[0][\"file_path\"] + extension) \n image_path = os.path.join(path, cam_name)\n image_name = Path(cam_name).stem\n image = Image.open(image_path)\n width = image.size[0]\n height = image.size[1]\n\n for idx, (c2w, time) in enumerate(zip(render_poses, render_times)):\n c2w[:3, 1:3] *= -1\n\n # get the world-to-camera transform and set R, T\n w2c = np.linalg.inv(c2w)\n R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code\n T = w2c[:3, 3]\n\n fovy = focal2fov(fov2focal(fovx, width), height)\n FovY = fovy \n FovX = fovx\n\n cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, \n image=None, image_path=None, image_name=None,\n width=width, height=height, time=time))\n \n return cam_infos\n\n\ndef init_random_points(ply_path):\n if not os.path.exists(ply_path):\n # Since this data set has no colmap data, we start with random points\n num_pts = 100_000\n print(f\"Generating random point cloud ({num_pts})...\")\n \n # We create random points inside the bounds of the synthetic Blender scenes\n # time_length = max([c.time for c in train_cam_infos]) + 1\n # time_length = 2\n # xyz = np.random.random((num_pts, 1, 3)) * 2.6 - 1.3\n # xyz = np.tile(xyz, (1, time_length, 1))\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 16, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 3, 3)), np.ones((num_pts, 1, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.init_random_points","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.init_random_points#L398-L421","kind":"function","name":"init_random_points","path":"scene/dataset_readers.py","language":"python","start_line":398,"end_line":421,"context_start_line":378,"context_end_line":441,"code":"\n for idx, (c2w, time) in enumerate(zip(render_poses, render_times)):\n c2w[:3, 1:3] *= -1\n\n # get the world-to-camera transform and set R, T\n w2c = np.linalg.inv(c2w)\n R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code\n T = w2c[:3, 3]\n\n fovy = focal2fov(fov2focal(fovx, width), height)\n FovY = fovy \n FovX = fovx\n\n cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, \n image=None, image_path=None, image_name=None,\n width=width, height=height, time=time))\n \n return cam_infos\n\n\ndef init_random_points(ply_path):\n if not os.path.exists(ply_path):\n # Since this data set has no colmap data, we start with random points\n num_pts = 100_000\n print(f\"Generating random point cloud ({num_pts})...\")\n \n # We create random points inside the bounds of the synthetic Blender scenes\n # time_length = max([c.time for c in train_cam_infos]) + 1\n # time_length = 2\n # xyz = np.random.random((num_pts, 1, 3)) * 2.6 - 1.3\n # xyz = np.tile(xyz, (1, time_length, 1))\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 16, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 3, 3)), np.ones((num_pts, 1, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n storePly(ply_path, xyz, SH2RGB(shs) * 255)\n # try:\n pcd = fetchPly(ply_path)\n # except:\n # pcd = None\n return pcd\n\ndef readNerfSyntheticInfo(path, white_background, eval, extension=\".png\"):\n print(\"Reading Training Transforms\")\n train_cam_infos = readCamerasFromTransforms(path, \"transforms_train.json\", white_background, extension)\n print(\"Reading Test Transforms\")\n test_cam_infos = readCamerasFromTransforms(path, \"transforms_test.json\", white_background, extension)\n \n vis_cam_infos = generateCamerasFromTransforms(path, \"transforms_train.json\")\n\n if not eval:\n train_cam_infos.extend(test_cam_infos)\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"points3d_ours.ply\")\n pcd = init_random_points(ply_path)\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readNerfSyntheticInfo","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readNerfSyntheticInfo#L423-L446","kind":"function","name":"readNerfSyntheticInfo","path":"scene/dataset_readers.py","language":"python","start_line":423,"end_line":446,"context_start_line":403,"context_end_line":466,"code":" \n # We create random points inside the bounds of the synthetic Blender scenes\n # time_length = max([c.time for c in train_cam_infos]) + 1\n # time_length = 2\n # xyz = np.random.random((num_pts, 1, 3)) * 2.6 - 1.3\n # xyz = np.tile(xyz, (1, time_length, 1))\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 16, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 3, 3)), np.ones((num_pts, 1, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3)), np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n storePly(ply_path, xyz, SH2RGB(shs) * 255)\n # try:\n pcd = fetchPly(ply_path)\n # except:\n # pcd = None\n return pcd\n\ndef readNerfSyntheticInfo(path, white_background, eval, extension=\".png\"):\n print(\"Reading Training Transforms\")\n train_cam_infos = readCamerasFromTransforms(path, \"transforms_train.json\", white_background, extension)\n print(\"Reading Test Transforms\")\n test_cam_infos = readCamerasFromTransforms(path, \"transforms_test.json\", white_background, extension)\n \n vis_cam_infos = generateCamerasFromTransforms(path, \"transforms_train.json\")\n\n if not eval:\n train_cam_infos.extend(test_cam_infos)\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"points3d_ours.ply\")\n pcd = init_random_points(ply_path)\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras=vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/len(train_cam_infos))\n return scene_info\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.viewmatrix","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.viewmatrix#L449-L456","kind":"function","name":"viewmatrix","path":"scene/dataset_readers.py","language":"python","start_line":449,"end_line":456,"context_start_line":429,"context_end_line":476,"code":" vis_cam_infos = generateCamerasFromTransforms(path, \"transforms_train.json\")\n\n if not eval:\n train_cam_infos.extend(test_cam_infos)\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"points3d_ours.ply\")\n pcd = init_random_points(ply_path)\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras=vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/len(train_cam_infos))\n return scene_info\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.render_path_spiral","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.render_path_spiral#L459-L471","kind":"function","name":"render_path_spiral","path":"scene/dataset_readers.py","language":"python","start_line":459,"end_line":471,"context_start_line":439,"context_end_line":491,"code":"\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras=vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/len(train_cam_infos))\n return scene_info\n\n\ndef viewmatrix(z, up, pos):\n vec2 = normalize(z)\n vec1_avg = up\n vec0 = normalize(np.cross(vec1_avg, vec2))\n vec1 = normalize(np.cross(vec2, vec0))\n m = np.eye(4)\n m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"\n Generate a set of poses using NeRF's spiral camera trajectory as validation poses.\n \"\"\"\n # center pose\n c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.get_spiral","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.get_spiral#L475-L497","kind":"function","name":"get_spiral","path":"scene/dataset_readers.py","language":"python","start_line":475,"end_line":497,"context_start_line":455,"context_end_line":517,"code":" m[:3] = np.stack([-vec0, vec1, vec2, pos], 1)\n return m\n\n\ndef render_path_spiral(c2w, up, rads, focal, zdelta, zrate, N_rots=2, N=120):\n render_poses = []\n rads = np.array(list(rads) + [1.0])\n\n for theta in np.linspace(0.0, 2.0 * np.pi * N_rots, N + 1)[:-1]:\n c = np.dot(\n c2w[:3, :4],\n np.array([np.cos(theta), -np.sin(theta), -np.sin(theta * zrate), 1.0])\n * rads,\n )\n z = normalize(c - np.dot(c2w[:3, :4], np.array([0, 0, -focal, 1.0])))\n render_poses.append(viewmatrix(z, up, c))\n return render_poses\n\n\n\ndef get_spiral(c2ws_all, near_fars, rads_scale=1.0, N_views=120):\n \"\"\"\n Generate a set of poses using NeRF's spiral camera trajectory as validation poses.\n \"\"\"\n # center pose\n c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\ndef readDynerfSceneInfo(path, eval):\n blender2opencv = np.eye(4)\n downsample = 2\n\n poses_arr = np.load(os.path.join(path, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(path, \"cam??\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / downsample\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, blender2opencv\n ) # Re-center poses so that the average is near the center.\n ","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readDynerfSceneInfo","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readDynerfSceneInfo#L500-L636","kind":"function","name":"readDynerfSceneInfo","path":"scene/dataset_readers.py","language":"python","start_line":500,"end_line":636,"context_start_line":480,"context_end_line":656,"code":" c2w = average_poses(c2ws_all)\n\n # Get average pose\n up = normalize(c2ws_all[:, :3, 1].sum(0))\n\n # Find a reasonable \"focus depth\" for this dataset\n dt = 0.75\n close_depth, inf_depth = near_fars.min() * 0.9, near_fars.max() * 5.0\n focal = 1.0 / ((1.0 - dt) / close_depth + dt / inf_depth)\n\n # Get radii for spiral path\n zdelta = near_fars.min() * 0.2\n tt = c2ws_all[:, :3, 3]\n rads = np.percentile(np.abs(tt), 90, 0) * rads_scale\n render_poses = render_path_spiral(\n c2w, up, rads, focal, zdelta, zrate=0.5, N=N_views\n )\n return np.stack(render_poses)\n\n\ndef readDynerfSceneInfo(path, eval):\n blender2opencv = np.eye(4)\n downsample = 2\n\n poses_arr = np.load(os.path.join(path, \"poses_bounds.npy\"))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]) # (N_cams, 3, 5)\n near_fars = poses_arr[:, -2:]\n videos = glob.glob(os.path.join(path, \"cam??\"))\n videos = sorted(videos)\n assert len(videos) == poses_arr.shape[0]\n\n H, W, focal = poses[0, :, -1]\n focal = focal / downsample\n poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1)\n poses, pose_avg = center_poses(\n poses, blender2opencv\n ) # Re-center poses so that the average is near the center.\n \n near_original = near_fars.min()\n scale_factor = near_original * 0.75\n near_fars /= (\n scale_factor # rescale nearest plane so that it is at z = 4/3.\n )\n # print(scale_factor)\n poses[..., 3] /= scale_factor\n \n image_dirs = [video.replace('.mp4', '') for video in videos]\n val_index = [0]\n images = [sorted(glob.glob(os.path.join(d, \"*.png\")), key=lambda x:int(os.path.splitext(os.path.basename(x))[0]))[:300] for d in image_dirs]\n train_cam_infos = []\n for idx, image_paths in enumerate(images):\n if idx in val_index:\n continue\n p = poses[idx]\n for image_path in image_paths:\n image_name = os.path.basename(image_path).split(\".\")[0]\n time = float(image_name) / 300\n image = Image.open(image_path)\n uid = idx * 1000 + int(image_name)\n pose = np.eye(4)\n pose[:3, :] = p[:3, :]\n R = -pose[:3, :3]\n R[:, 0] = -R[:, 0]\n T = -pose[:3, 3].dot(R)\n height = image.height\n width = image.width\n FovY = focal2fov(focal, height)\n FovX = focal2fov(focal, width)\n # R = pose[:3, :3]\n # T = pose[:3, 3]\n\n cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=time)\n train_cam_infos.append(cam_info)\n\n test_cam_infos = []\n for idx, image_paths in enumerate(images):\n if idx not in val_index:\n continue\n p = poses[idx]\n for image_path in image_paths:\n image_name = os.path.basename(image_path).split(\".\")[0]\n time = float(image_name) / 300\n image = Image.open(image_path)\n uid = idx * 1000 + int(image_name)\n pose = np.eye(4)\n pose[:3, :] = p[:3, :]\n R = -pose[:3, :3]\n R[:, 0] = -R[:, 0]\n T = -pose[:3, 3].dot(R)\n # R = pose[:3, :3]\n # T = pose[:3, 3]\n \n height = image.height\n width = image.width\n FovY = focal2fov(focal, height)\n FovX = focal2fov(focal, width)\n\n cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=time)\n test_cam_infos.append(cam_info)\n if not eval:\n train_cam_infos.extend(test_cam_infos)\n test_cam_infos = []\n\n widht, height = train_cam_infos[0].width, train_cam_infos[0].height\n # Sample N_views poses for validation - NeRF-like camera trajectory.\n N_views = 120\n val_poses = get_spiral(poses, near_fars, N_views=N_views)\n val_times = torch.linspace(0.0, 1.0, val_poses.shape[0])\n vis_cam_infos = []\n for idx, (pose, time) in enumerate(zip(val_poses, val_times)):\n p = pose\n uid = idx\n pose = np.eye(4)\n pose[:3, :] = p[:3, :]\n R = -pose[:3, :3]\n R[:, 0] = -R[:, 0]\n T = -pose[:3, 3].dot(R)\n # R = pose[:3, :3]\n # T = pose[:3, 3]\n \n FovY = focal2fov(focal, height)\n FovX = focal2fov(focal, width)\n\n cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=None, image_name=None, width=width, height=height, time=time)\n vis_cam_infos.append(cam_info)\n\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"points3d_ours.ply\")\n if not os.path.exists(ply_path):\n # Since this data set has no colmap data, we start with random points\n num_pts = 2_000 # 100_000\n print(f\"Generating random point cloud ({num_pts})...\")\n threshold = 3\n xyz_max = np.array([1.5*threshold, 1.5*threshold, -0*threshold])\n xyz_min = np.array([-1.5*threshold, -1.5*threshold, -1.5*threshold]) \n xyz = np.concatenate([(np.random.random((num_pts, 1, 3)))* (xyz_max-xyz_min) + xyz_min, np.zeros((num_pts, 16, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n storePly(ply_path, xyz, SH2RGB(shs) * 255)\n\n pcd = fetchPly(ply_path)\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras =vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/300)\n return scene_info\n\n\n\ndef readHypernerfCamera(uid, camera, image_path, time):\n height, width = int(camera.image_shape[0]), int(camera.image_shape[1])\n image_name = os.path.basename(image_path).split(\".\")[0]\n R = camera.orientation.T\n # T = camera.translation.T\n T = - camera.position @ R\n image = Image.open(image_path) \n FovY = focal2fov(camera.focal_length, height)\n FovX = focal2fov(camera.focal_length, width)\n return CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=time) \n\n\ndef readHypernerfSceneInfo(path, eval):\n # borrow code from https://github.com/hustvl/TiNeuVox/blob/main/lib/load_hyper.py\n use_bg_points = False\n with open(f'{path}/scene.json', 'r') as f:","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readHypernerfCamera","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readHypernerfCamera#L640-L650","kind":"function","name":"readHypernerfCamera","path":"scene/dataset_readers.py","language":"python","start_line":640,"end_line":650,"context_start_line":620,"context_end_line":670,"code":" xyz = np.concatenate([(np.random.random((num_pts, 1, 3)))* (xyz_max-xyz_min) + xyz_min, np.zeros((num_pts, 16, 3))], axis=1)\n # xyz = np.concatenate([np.random.random((num_pts, 1, 3)) * 2.6 - 1.3, np.zeros((num_pts, 2, 3))], axis=1)\n\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n storePly(ply_path, xyz, SH2RGB(shs) * 255)\n\n pcd = fetchPly(ply_path)\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras =vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/300)\n return scene_info\n\n\n\ndef readHypernerfCamera(uid, camera, image_path, time):\n height, width = int(camera.image_shape[0]), int(camera.image_shape[1])\n image_name = os.path.basename(image_path).split(\".\")[0]\n R = camera.orientation.T\n # T = camera.translation.T\n T = - camera.position @ R\n image = Image.open(image_path) \n FovY = focal2fov(camera.focal_length, height)\n FovX = focal2fov(camera.focal_length, width)\n return CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=time) \n\n\ndef readHypernerfSceneInfo(path, eval):\n # borrow code from https://github.com/hustvl/TiNeuVox/blob/main/lib/load_hyper.py\n use_bg_points = False\n with open(f'{path}/scene.json', 'r') as f:\n scene_json = json.load(f)\n with open(f'{path}/metadata.json', 'r') as f:\n meta_json = json.load(f)\n with open(f'{path}/dataset.json', 'r') as f:\n dataset_json = json.load(f) \n \n near = scene_json['near']\n far = scene_json['far']\n coord_scale = scene_json['scale']\n scene_center = scene_json['center']\n \n all_imgs = dataset_json['ids']\n val_ids = dataset_json['val_ids']\n add_cam = False","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.readHypernerfSceneInfo","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.readHypernerfSceneInfo#L653-L754","kind":"function","name":"readHypernerfSceneInfo","path":"scene/dataset_readers.py","language":"python","start_line":653,"end_line":754,"context_start_line":633,"context_end_line":763,"code":" vis_cameras =vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/300)\n return scene_info\n\n\n\ndef readHypernerfCamera(uid, camera, image_path, time):\n height, width = int(camera.image_shape[0]), int(camera.image_shape[1])\n image_name = os.path.basename(image_path).split(\".\")[0]\n R = camera.orientation.T\n # T = camera.translation.T\n T = - camera.position @ R\n image = Image.open(image_path) \n FovY = focal2fov(camera.focal_length, height)\n FovX = focal2fov(camera.focal_length, width)\n return CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=width, height=height, time=time) \n\n\ndef readHypernerfSceneInfo(path, eval):\n # borrow code from https://github.com/hustvl/TiNeuVox/blob/main/lib/load_hyper.py\n use_bg_points = False\n with open(f'{path}/scene.json', 'r') as f:\n scene_json = json.load(f)\n with open(f'{path}/metadata.json', 'r') as f:\n meta_json = json.load(f)\n with open(f'{path}/dataset.json', 'r') as f:\n dataset_json = json.load(f) \n \n near = scene_json['near']\n far = scene_json['far']\n coord_scale = scene_json['scale']\n scene_center = scene_json['center']\n \n all_imgs = dataset_json['ids']\n val_ids = dataset_json['val_ids']\n add_cam = False\n if len(val_ids) == 0:\n i_train = np.array([i for i in np.arange(len(all_imgs)) if (i%4 == 0)])\n i_test = i_train+2\n i_test = i_test[:-1,]\n else:\n add_cam = True\n train_ids = dataset_json['train_ids']\n i_test = []\n i_train = []\n for i in range(len(all_imgs)):\n id = all_imgs[i]\n if id in val_ids:\n i_test.append(i)\n if id in train_ids:\n i_train.append(i)\n\n print('i_train',i_train)\n print('i_test',i_test)\n all_cams = [meta_json[i]['camera_id'] for i in all_imgs]\n all_times = [meta_json[i]['time_id'] for i in all_imgs]\n max_time = max(all_times)\n all_times = [meta_json[i]['time_id']/max_time for i in all_imgs]\n selected_time = set(all_times)\n ratio = 0.5\n\n all_cam_params = []\n for im in all_imgs:\n camera = HyperNeRFCamera.from_json(f'{path}/camera/{im}.json')\n camera = camera.scale(ratio)\n camera.position = camera.position - scene_center\n camera.position = camera.position * coord_scale\n all_cam_params.append(camera)\n\n all_imgs = [f'{path}/rgb/{int(1/ratio)}x/{i}.png' for i in all_imgs]\n h, w = all_cam_params[0].image_shape\n if use_bg_points:\n with open(f'{path}/points.npy', 'rb') as f:\n points = np.load(f)\n bg_points = (points - scene_center) * coord_scale\n bg_points = torch.tensor(bg_points).float() \n\n train_cam_infos = [readHypernerfCamera(i, all_cam_params[i], all_imgs[i], all_times[i]) for i in i_train]\n test_cam_infos = [readHypernerfCamera(i, all_cam_params[i], all_imgs[i], all_times[i]) for i in i_test]\n\n vis_cam_infos = [readHypernerfCamera(i, all_cam_params[i], all_imgs[i], all_times[i]) for i in np.argsort(all_cams, kind='stable')]\n\n if not eval:\n train_cam_infos.extend(test_cam_infos)\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n # ply_path = os.path.join(path, \"points3d_ours.ply\")\n # if not os.path.exists(ply_path):\n # # Since this data set has no colmap data, we start with random points\n # num_pts = 100_000\n # print(f\"Generating random point cloud ({num_pts})...\")\n # threshold = 3\n # xyz_max = np.array([1.5*threshold, 1.5*threshold, 1.5*threshold])\n # xyz_min = np.array([-1.5*threshold, -1.5*threshold, -1.5*threshold]) \n # xyz = np.concatenate([(np.random.random((num_pts, 1, 3)))* (xyz_max-xyz_min) + xyz_min, np.zeros((num_pts, 10, 3))], axis=1)\n\n # shs = np.random.random((num_pts, 3)) / 255.0\n # pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n # storePly(ply_path, xyz, SH2RGB(shs) * 255)\n\n # pcd = fetchPly(ply_path)\n\n ply_path = os.path.join(path, \"points.npy\")\n xyz = np.load(ply_path, allow_pickle=True)\n xyz = (xyz - scene_center) * coord_scale\n xyz = xyz.astype(np.float32)[:, None, :]\n xyz = np.concatenate([xyz, np.zeros((xyz.shape[0], 12, 3))], axis=1)\n shs = np.random.random((xyz.shape[0], 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((xyz.shape[0], 3))) \n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n vis_cameras=vis_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path, time_delta=1/max_time)\n return scene_info\n\n\n\nsceneLoadTypeCallbacks = {\n \"Colmap\": readColmapSceneInfo,\n \"Blender\" : readNerfSyntheticInfo,\n \"DyNeRF\": readDynerfSceneInfo,\n \"HyperNeRF\": readHypernerfSceneInfo,\n}","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:scene.dataset_readers.get_center_and_diag","uri":"program://EfficientDynamic3DGaussian/function/scene.dataset_readers.get_center_and_diag#L125-L131","kind":"function","name":"get_center_and_diag","path":"scene/dataset_readers.py","language":"python","start_line":125,"end_line":131,"context_start_line":105,"context_end_line":151,"code":" pose_avg_homo = np.eye(4)\n pose_avg_homo[\n :3\n ] = pose_avg # convert to homogeneous coordinate for faster computation\n pose_avg_homo = pose_avg_homo\n # by simply adding 0, 0, 0, 1 as the last row\n last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4)\n poses_homo = np.concatenate(\n [poses, last_row], 1\n ) # (N_images, 4, 4) homogeneous coordinate\n\n poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4)\n # poses_centered = poses_centered @ blender2opencv\n poses_centered = poses_centered[:, :3] # (N_images, 3, 4)\n\n return poses_centered, pose_avg_homo\n\n\n\ndef getNerfppNorm(cam_info):\n def get_center_and_diag(cam_centers):\n cam_centers = np.hstack(cam_centers)\n avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)\n center = avg_cam_center\n dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)\n diagonal = np.max(dist)\n return center.flatten(), diagonal\n\n cam_centers = []\n\n for cam in cam_info:\n W2C = getWorld2View2(cam.R, cam.T)\n C2W = np.linalg.inv(W2C)\n cam_centers.append(C2W[:3, 3:4])\n\n center, diagonal = get_center_and_diag(cam_centers)\n radius = diagonal * 1.1\n\n translate = -center\n\n return {\"translate\": translate, \"radius\": radius}\n\ndef readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder):\n cam_infos = []\n for idx, key in enumerate(cam_extrinsics):\n sys.stdout.write('\\r')\n # the exact output you're looking for:","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.system_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.system_utils#L1-L28","kind":"module","name":"utils.system_utils","path":"utils/system_utils.py","language":"python","start_line":1,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom errno import EEXIST\nfrom os import makedirs, path\nimport os\n\ndef mkdir_p(folder_path):\n # Creates a directory. equivalent to using mkdir -p on the command line\n try:\n makedirs(folder_path)\n except OSError as exc: # Python >2.5\n if exc.errno == EEXIST and path.isdir(folder_path):\n pass\n else:\n raise\n\ndef searchForMaxIteration(folder):\n saved_iters = [int(fname.split(\"_\")[-1]) for fname in os.listdir(folder)]\n return max(saved_iters)","source_hash":"be01c02d3118c5d53808bc04efccd00c35a705a43a87c3583ea2f4752bc48553","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.system_utils.mkdir_p","uri":"program://EfficientDynamic3DGaussian/function/utils.system_utils.mkdir_p#L16-L24","kind":"function","name":"mkdir_p","path":"utils/system_utils.py","language":"python","start_line":16,"end_line":24,"context_start_line":1,"context_end_line":28,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom errno import EEXIST\nfrom os import makedirs, path\nimport os\n\ndef mkdir_p(folder_path):\n # Creates a directory. equivalent to using mkdir -p on the command line\n try:\n makedirs(folder_path)\n except OSError as exc: # Python >2.5\n if exc.errno == EEXIST and path.isdir(folder_path):\n pass\n else:\n raise\n\ndef searchForMaxIteration(folder):\n saved_iters = [int(fname.split(\"_\")[-1]) for fname in os.listdir(folder)]\n return max(saved_iters)","source_hash":"be01c02d3118c5d53808bc04efccd00c35a705a43a87c3583ea2f4752bc48553","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.system_utils.searchForMaxIteration","uri":"program://EfficientDynamic3DGaussian/function/utils.system_utils.searchForMaxIteration#L26-L28","kind":"function","name":"searchForMaxIteration","path":"utils/system_utils.py","language":"python","start_line":26,"end_line":28,"context_start_line":6,"context_end_line":28,"code":"# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom errno import EEXIST\nfrom os import makedirs, path\nimport os\n\ndef mkdir_p(folder_path):\n # Creates a directory. equivalent to using mkdir -p on the command line\n try:\n makedirs(folder_path)\n except OSError as exc: # Python >2.5\n if exc.errno == EEXIST and path.isdir(folder_path):\n pass\n else:\n raise\n\ndef searchForMaxIteration(folder):\n saved_iters = [int(fname.split(\"_\")[-1]) for fname in os.listdir(folder)]\n return max(saved_iters)","source_hash":"be01c02d3118c5d53808bc04efccd00c35a705a43a87c3583ea2f4752bc48553","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.graphics_utils#L1-L77","kind":"module","name":"utils.graphics_utils","path":"utils/graphics_utils.py","language":"python","start_line":1,"end_line":77,"context_start_line":1,"context_end_line":77,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport math\nimport numpy as np\nfrom typing import NamedTuple\n\nclass BasicPointCloud(NamedTuple):\n points : np.array\n colors : np.array\n normals : np.array\n\ndef geom_transform_points(points, transf_matrix):\n P, _ = points.shape\n ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)\n points_hom = torch.cat([points, ones], dim=1)\n points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))\n\n denom = points_out[..., 3:] + 0.0000001\n return (points_out[..., :3] / denom).squeeze(dim=0)\n\ndef getWorld2View(R, t):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)\n\ndef getProjectionMatrix(znear, zfar, fovX, fovY):\n tanHalfFovY = math.tan((fovY / 2))\n tanHalfFovX = math.tan((fovX / 2))\n\n top = tanHalfFovY * znear\n bottom = -top\n right = tanHalfFovX * znear\n left = -right\n\n P = torch.zeros(4, 4)\n\n z_sign = 1.0\n\n P[0, 0] = 2.0 * znear / (right - left)\n P[1, 1] = 2.0 * znear / (top - bottom)\n P[0, 2] = (right + left) / (right - left)\n P[1, 2] = (top + bottom) / (top - bottom)\n P[3, 2] = z_sign\n P[2, 2] = z_sign * zfar / (zfar - znear)\n P[2, 3] = -(zfar * znear) / (zfar - znear)\n return P\n\ndef fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))\n\ndef focal2fov(focal, pixels):\n return 2*math.atan(pixels/(2*focal))","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.BasicPointCloud","uri":"program://EfficientDynamic3DGaussian/class/utils.graphics_utils.BasicPointCloud#L17-L20","kind":"class","name":"BasicPointCloud","path":"utils/graphics_utils.py","language":"python","start_line":17,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport math\nimport numpy as np\nfrom typing import NamedTuple\n\nclass BasicPointCloud(NamedTuple):\n points : np.array\n colors : np.array\n normals : np.array\n\ndef geom_transform_points(points, transf_matrix):\n P, _ = points.shape\n ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)\n points_hom = torch.cat([points, ones], dim=1)\n points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))\n\n denom = points_out[..., 3:] + 0.0000001\n return (points_out[..., :3] / denom).squeeze(dim=0)\n\ndef getWorld2View(R, t):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.geom_transform_points","uri":"program://EfficientDynamic3DGaussian/function/utils.graphics_utils.geom_transform_points#L22-L29","kind":"function","name":"geom_transform_points","path":"utils/graphics_utils.py","language":"python","start_line":22,"end_line":29,"context_start_line":2,"context_end_line":49,"code":"# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport math\nimport numpy as np\nfrom typing import NamedTuple\n\nclass BasicPointCloud(NamedTuple):\n points : np.array\n colors : np.array\n normals : np.array\n\ndef geom_transform_points(points, transf_matrix):\n P, _ = points.shape\n ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)\n points_hom = torch.cat([points, ones], dim=1)\n points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))\n\n denom = points_out[..., 3:] + 0.0000001\n return (points_out[..., :3] / denom).squeeze(dim=0)\n\ndef getWorld2View(R, t):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.getWorld2View","uri":"program://EfficientDynamic3DGaussian/function/utils.graphics_utils.getWorld2View#L31-L36","kind":"function","name":"getWorld2View","path":"utils/graphics_utils.py","language":"python","start_line":31,"end_line":36,"context_start_line":11,"context_end_line":56,"code":"\nimport torch\nimport math\nimport numpy as np\nfrom typing import NamedTuple\n\nclass BasicPointCloud(NamedTuple):\n points : np.array\n colors : np.array\n normals : np.array\n\ndef geom_transform_points(points, transf_matrix):\n P, _ = points.shape\n ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)\n points_hom = torch.cat([points, ones], dim=1)\n points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))\n\n denom = points_out[..., 3:] + 0.0000001\n return (points_out[..., :3] / denom).squeeze(dim=0)\n\ndef getWorld2View(R, t):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)\n\ndef getProjectionMatrix(znear, zfar, fovX, fovY):\n tanHalfFovY = math.tan((fovY / 2))\n tanHalfFovX = math.tan((fovX / 2))\n\n top = tanHalfFovY * znear\n bottom = -top","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.getWorld2View2","uri":"program://EfficientDynamic3DGaussian/function/utils.graphics_utils.getWorld2View2#L38-L49","kind":"function","name":"getWorld2View2","path":"utils/graphics_utils.py","language":"python","start_line":38,"end_line":49,"context_start_line":18,"context_end_line":69,"code":" points : np.array\n colors : np.array\n normals : np.array\n\ndef geom_transform_points(points, transf_matrix):\n P, _ = points.shape\n ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)\n points_hom = torch.cat([points, ones], dim=1)\n points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))\n\n denom = points_out[..., 3:] + 0.0000001\n return (points_out[..., :3] / denom).squeeze(dim=0)\n\ndef getWorld2View(R, t):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)\n\ndef getProjectionMatrix(znear, zfar, fovX, fovY):\n tanHalfFovY = math.tan((fovY / 2))\n tanHalfFovX = math.tan((fovX / 2))\n\n top = tanHalfFovY * znear\n bottom = -top\n right = tanHalfFovX * znear\n left = -right\n\n P = torch.zeros(4, 4)\n\n z_sign = 1.0\n\n P[0, 0] = 2.0 * znear / (right - left)\n P[1, 1] = 2.0 * znear / (top - bottom)\n P[0, 2] = (right + left) / (right - left)\n P[1, 2] = (top + bottom) / (top - bottom)\n P[3, 2] = z_sign\n P[2, 2] = z_sign * zfar / (zfar - znear)","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.getProjectionMatrix","uri":"program://EfficientDynamic3DGaussian/function/utils.graphics_utils.getProjectionMatrix#L51-L71","kind":"function","name":"getProjectionMatrix","path":"utils/graphics_utils.py","language":"python","start_line":51,"end_line":71,"context_start_line":31,"context_end_line":77,"code":"def getWorld2View(R, t):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)\n\ndef getProjectionMatrix(znear, zfar, fovX, fovY):\n tanHalfFovY = math.tan((fovY / 2))\n tanHalfFovX = math.tan((fovX / 2))\n\n top = tanHalfFovY * znear\n bottom = -top\n right = tanHalfFovX * znear\n left = -right\n\n P = torch.zeros(4, 4)\n\n z_sign = 1.0\n\n P[0, 0] = 2.0 * znear / (right - left)\n P[1, 1] = 2.0 * znear / (top - bottom)\n P[0, 2] = (right + left) / (right - left)\n P[1, 2] = (top + bottom) / (top - bottom)\n P[3, 2] = z_sign\n P[2, 2] = z_sign * zfar / (zfar - znear)\n P[2, 3] = -(zfar * znear) / (zfar - znear)\n return P\n\ndef fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))\n\ndef focal2fov(focal, pixels):\n return 2*math.atan(pixels/(2*focal))","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.fov2focal","uri":"program://EfficientDynamic3DGaussian/function/utils.graphics_utils.fov2focal#L73-L74","kind":"function","name":"fov2focal","path":"utils/graphics_utils.py","language":"python","start_line":73,"end_line":74,"context_start_line":53,"context_end_line":77,"code":" tanHalfFovX = math.tan((fovX / 2))\n\n top = tanHalfFovY * znear\n bottom = -top\n right = tanHalfFovX * znear\n left = -right\n\n P = torch.zeros(4, 4)\n\n z_sign = 1.0\n\n P[0, 0] = 2.0 * znear / (right - left)\n P[1, 1] = 2.0 * znear / (top - bottom)\n P[0, 2] = (right + left) / (right - left)\n P[1, 2] = (top + bottom) / (top - bottom)\n P[3, 2] = z_sign\n P[2, 2] = z_sign * zfar / (zfar - znear)\n P[2, 3] = -(zfar * znear) / (zfar - znear)\n return P\n\ndef fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))\n\ndef focal2fov(focal, pixels):\n return 2*math.atan(pixels/(2*focal))","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.graphics_utils.focal2fov","uri":"program://EfficientDynamic3DGaussian/function/utils.graphics_utils.focal2fov#L76-L77","kind":"function","name":"focal2fov","path":"utils/graphics_utils.py","language":"python","start_line":76,"end_line":77,"context_start_line":56,"context_end_line":77,"code":" bottom = -top\n right = tanHalfFovX * znear\n left = -right\n\n P = torch.zeros(4, 4)\n\n z_sign = 1.0\n\n P[0, 0] = 2.0 * znear / (right - left)\n P[1, 1] = 2.0 * znear / (top - bottom)\n P[0, 2] = (right + left) / (right - left)\n P[1, 2] = (top + bottom) / (top - bottom)\n P[3, 2] = z_sign\n P[2, 2] = z_sign * zfar / (zfar - znear)\n P[2, 3] = -(zfar * znear) / (zfar - znear)\n return P\n\ndef fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))\n\ndef focal2fov(focal, pixels):\n return 2*math.atan(pixels/(2*focal))","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.image_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.image_utils#L1-L19","kind":"module","name":"utils.image_utils","path":"utils/image_utils.py","language":"python","start_line":1,"end_line":19,"context_start_line":1,"context_end_line":19,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\n\ndef mse(img1, img2):\n return (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n\ndef psnr(img1, img2):\n mse = (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n return 20 * torch.log10(1.0 / torch.sqrt(mse))","source_hash":"872a4507773b9378db9e0fefc90104dc474b27551af18ada73f000a7a00a4ba0","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.image_utils.mse","uri":"program://EfficientDynamic3DGaussian/function/utils.image_utils.mse#L14-L15","kind":"function","name":"mse","path":"utils/image_utils.py","language":"python","start_line":14,"end_line":15,"context_start_line":1,"context_end_line":19,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\n\ndef mse(img1, img2):\n return (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n\ndef psnr(img1, img2):\n mse = (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n return 20 * torch.log10(1.0 / torch.sqrt(mse))","source_hash":"872a4507773b9378db9e0fefc90104dc474b27551af18ada73f000a7a00a4ba0","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.image_utils.psnr","uri":"program://EfficientDynamic3DGaussian/function/utils.image_utils.psnr#L17-L19","kind":"function","name":"psnr","path":"utils/image_utils.py","language":"python","start_line":17,"end_line":19,"context_start_line":1,"context_end_line":19,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\n\ndef mse(img1, img2):\n return (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n\ndef psnr(img1, img2):\n mse = (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n return 20 * torch.log10(1.0 / torch.sqrt(mse))","source_hash":"872a4507773b9378db9e0fefc90104dc474b27551af18ada73f000a7a00a4ba0","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.general_utils#L1-L131","kind":"module","name":"utils.general_utils","path":"utils/general_utils.py","language":"python","start_line":1,"end_line":131,"context_start_line":1,"context_end_line":131,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport sys\nfrom datetime import datetime\nimport numpy as np\nimport random\n\ndef inverse_sigmoid(x):\n return torch.log(x/(1-x))\n\ndef PILtoTorch(pil_image, resolution):\n resized_image_PIL = pil_image.resize(resolution)\n resized_image = torch.from_numpy(np.array(resized_image_PIL)) / 255.0\n if len(resized_image.shape) == 3:\n return resized_image.permute(2, 0, 1)\n else:\n return resized_image.unsqueeze(dim=-1).permute(2, 0, 1)\n\ndef get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is\n lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n to the normal learning rate when steps>lr_delay_steps.\n :param conf: config subtree 'lr' or similar\n :param max_steps: int, the number of steps during optimization.\n :return HoF which takes step as input\n \"\"\"\n\n def helper(step):\n if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n # Disable this parameter\n return 0.0\n if lr_delay_steps > 0:\n # A kind of reverse cosine decay.\n delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper\n\ndef strip_lowerdiag(L):\n uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n uncertainty[:, 0] = L[:, 0, 0]\n uncertainty[:, 1] = L[:, 0, 1]\n uncertainty[:, 2] = L[:, 0, 2]\n uncertainty[:, 3] = L[:, 1, 1]\n uncertainty[:, 4] = L[:, 1, 2]\n uncertainty[:, 5] = L[:, 2, 2]\n return uncertainty\n\ndef strip_symmetric(sym):\n return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n \n q = r / norm[..., None]\n R = torch.zeros((q.size(0), q.size(1), 3, 3), device='cuda')\n r = q[..., 0]\n x = q[..., 1]\n y = q[..., 2]\n z = q[..., 3]\n\n R[..., 0, 0] = 1 - 2 * (y*y + z*z)\n R[..., 0, 1] = 2 * (x*y - r*z)\n R[..., 0, 2] = 2 * (x*z + r*y)\n R[..., 1, 0] = 2 * (x*y + r*z)\n R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n torch.cuda.set_device(torch.device(\"cuda:0\"))","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.inverse_sigmoid","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.inverse_sigmoid#L18-L19","kind":"function","name":"inverse_sigmoid","path":"utils/general_utils.py","language":"python","start_line":18,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport sys\nfrom datetime import datetime\nimport numpy as np\nimport random\n\ndef inverse_sigmoid(x):\n return torch.log(x/(1-x))\n\ndef PILtoTorch(pil_image, resolution):\n resized_image_PIL = pil_image.resize(resolution)\n resized_image = torch.from_numpy(np.array(resized_image_PIL)) / 255.0\n if len(resized_image.shape) == 3:\n return resized_image.permute(2, 0, 1)\n else:\n return resized_image.unsqueeze(dim=-1).permute(2, 0, 1)\n\ndef get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.PILtoTorch","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.PILtoTorch#L21-L27","kind":"function","name":"PILtoTorch","path":"utils/general_utils.py","language":"python","start_line":21,"end_line":27,"context_start_line":1,"context_end_line":47,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport sys\nfrom datetime import datetime\nimport numpy as np\nimport random\n\ndef inverse_sigmoid(x):\n return torch.log(x/(1-x))\n\ndef PILtoTorch(pil_image, resolution):\n resized_image_PIL = pil_image.resize(resolution)\n resized_image = torch.from_numpy(np.array(resized_image_PIL)) / 255.0\n if len(resized_image.shape) == 3:\n return resized_image.permute(2, 0, 1)\n else:\n return resized_image.unsqueeze(dim=-1).permute(2, 0, 1)\n\ndef get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is\n lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n to the normal learning rate when steps>lr_delay_steps.\n :param conf: config subtree 'lr' or similar\n :param max_steps: int, the number of steps during optimization.\n :return HoF which takes step as input\n \"\"\"\n\n def helper(step):","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.get_expon_lr_func","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.get_expon_lr_func#L29-L62","kind":"function","name":"get_expon_lr_func","path":"utils/general_utils.py","language":"python","start_line":29,"end_line":62,"context_start_line":9,"context_end_line":82,"code":"# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport sys\nfrom datetime import datetime\nimport numpy as np\nimport random\n\ndef inverse_sigmoid(x):\n return torch.log(x/(1-x))\n\ndef PILtoTorch(pil_image, resolution):\n resized_image_PIL = pil_image.resize(resolution)\n resized_image = torch.from_numpy(np.array(resized_image_PIL)) / 255.0\n if len(resized_image.shape) == 3:\n return resized_image.permute(2, 0, 1)\n else:\n return resized_image.unsqueeze(dim=-1).permute(2, 0, 1)\n\ndef get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is\n lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n to the normal learning rate when steps>lr_delay_steps.\n :param conf: config subtree 'lr' or similar\n :param max_steps: int, the number of steps during optimization.\n :return HoF which takes step as input\n \"\"\"\n\n def helper(step):\n if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n # Disable this parameter\n return 0.0\n if lr_delay_steps > 0:\n # A kind of reverse cosine decay.\n delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper\n\ndef strip_lowerdiag(L):\n uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n uncertainty[:, 0] = L[:, 0, 0]\n uncertainty[:, 1] = L[:, 0, 1]\n uncertainty[:, 2] = L[:, 0, 2]\n uncertainty[:, 3] = L[:, 1, 1]\n uncertainty[:, 4] = L[:, 1, 2]\n uncertainty[:, 5] = L[:, 2, 2]\n return uncertainty\n\ndef strip_symmetric(sym):\n return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n \n q = r / norm[..., None]\n R = torch.zeros((q.size(0), q.size(1), 3, 3), device='cuda')","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.strip_lowerdiag","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.strip_lowerdiag#L64-L73","kind":"function","name":"strip_lowerdiag","path":"utils/general_utils.py","language":"python","start_line":64,"end_line":73,"context_start_line":44,"context_end_line":93,"code":" :return HoF which takes step as input\n \"\"\"\n\n def helper(step):\n if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n # Disable this parameter\n return 0.0\n if lr_delay_steps > 0:\n # A kind of reverse cosine decay.\n delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper\n\ndef strip_lowerdiag(L):\n uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n uncertainty[:, 0] = L[:, 0, 0]\n uncertainty[:, 1] = L[:, 0, 1]\n uncertainty[:, 2] = L[:, 0, 2]\n uncertainty[:, 3] = L[:, 1, 1]\n uncertainty[:, 4] = L[:, 1, 2]\n uncertainty[:, 5] = L[:, 2, 2]\n return uncertainty\n\ndef strip_symmetric(sym):\n return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n \n q = r / norm[..., None]\n R = torch.zeros((q.size(0), q.size(1), 3, 3), device='cuda')\n r = q[..., 0]\n x = q[..., 1]\n y = q[..., 2]\n z = q[..., 3]\n\n R[..., 0, 0] = 1 - 2 * (y*y + z*z)\n R[..., 0, 1] = 2 * (x*y - r*z)\n R[..., 0, 2] = 2 * (x*z + r*y)\n R[..., 1, 0] = 2 * (x*y + r*z)\n R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.strip_symmetric","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.strip_symmetric#L75-L76","kind":"function","name":"strip_symmetric","path":"utils/general_utils.py","language":"python","start_line":75,"end_line":76,"context_start_line":55,"context_end_line":96,"code":" )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper\n\ndef strip_lowerdiag(L):\n uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n uncertainty[:, 0] = L[:, 0, 0]\n uncertainty[:, 1] = L[:, 0, 1]\n uncertainty[:, 2] = L[:, 0, 2]\n uncertainty[:, 3] = L[:, 1, 1]\n uncertainty[:, 4] = L[:, 1, 2]\n uncertainty[:, 5] = L[:, 2, 2]\n return uncertainty\n\ndef strip_symmetric(sym):\n return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n \n q = r / norm[..., None]\n R = torch.zeros((q.size(0), q.size(1), 3, 3), device='cuda')\n r = q[..., 0]\n x = q[..., 1]\n y = q[..., 2]\n z = q[..., 3]\n\n R[..., 0, 0] = 1 - 2 * (y*y + z*z)\n R[..., 0, 1] = 2 * (x*y - r*z)\n R[..., 0, 2] = 2 * (x*z + r*y)\n R[..., 1, 0] = 2 * (x*y + r*z)\n R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.build_rotation","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.build_rotation#L78-L97","kind":"function","name":"build_rotation","path":"utils/general_utils.py","language":"python","start_line":78,"end_line":97,"context_start_line":58,"context_end_line":117,"code":" t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper\n\ndef strip_lowerdiag(L):\n uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n uncertainty[:, 0] = L[:, 0, 0]\n uncertainty[:, 1] = L[:, 0, 1]\n uncertainty[:, 2] = L[:, 0, 2]\n uncertainty[:, 3] = L[:, 1, 1]\n uncertainty[:, 4] = L[:, 1, 2]\n uncertainty[:, 5] = L[:, 2, 2]\n return uncertainty\n\ndef strip_symmetric(sym):\n return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n \n q = r / norm[..., None]\n R = torch.zeros((q.size(0), q.size(1), 3, 3), device='cuda')\n r = q[..., 0]\n x = q[..., 1]\n y = q[..., 2]\n z = q[..., 3]\n\n R[..., 0, 0] = 1 - 2 * (y*y + z*z)\n R[..., 0, 1] = 2 * (x*y - r*z)\n R[..., 0, 2] = 2 * (x*z + r*y)\n R[..., 1, 0] = 2 * (x*y + r*z)\n R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.build_scaling_rotation","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.build_scaling_rotation#L99-L108","kind":"function","name":"build_scaling_rotation","path":"utils/general_utils.py","language":"python","start_line":99,"end_line":108,"context_start_line":79,"context_end_line":128,"code":" norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n \n q = r / norm[..., None]\n R = torch.zeros((q.size(0), q.size(1), 3, 3), device='cuda')\n r = q[..., 0]\n x = q[..., 1]\n y = q[..., 2]\n z = q[..., 3]\n\n R[..., 0, 0] = 1 - 2 * (y*y + z*z)\n R[..., 0, 1] = 2 * (x*y - r*z)\n R[..., 0, 2] = 2 * (x*z + r*y)\n R[..., 1, 0] = 2 * (x*y + r*z)\n R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.safe_state","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.safe_state#L110-L131","kind":"function","name":"safe_state","path":"utils/general_utils.py","language":"python","start_line":110,"end_line":131,"context_start_line":90,"context_end_line":131,"code":" R[..., 0, 2] = 2 * (x*z + r*y)\n R[..., 1, 0] = 2 * (x*y + r*z)\n R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n torch.cuda.set_device(torch.device(\"cuda:0\"))","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.helper","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.helper#L47-L60","kind":"function","name":"helper","path":"utils/general_utils.py","language":"python","start_line":47,"end_line":60,"context_start_line":27,"context_end_line":80,"code":" return resized_image.unsqueeze(dim=-1).permute(2, 0, 1)\n\ndef get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is\n lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n to the normal learning rate when steps>lr_delay_steps.\n :param conf: config subtree 'lr' or similar\n :param max_steps: int, the number of steps during optimization.\n :return HoF which takes step as input\n \"\"\"\n\n def helper(step):\n if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n # Disable this parameter\n return 0.0\n if lr_delay_steps > 0:\n # A kind of reverse cosine decay.\n delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper\n\ndef strip_lowerdiag(L):\n uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n uncertainty[:, 0] = L[:, 0, 0]\n uncertainty[:, 1] = L[:, 0, 1]\n uncertainty[:, 2] = L[:, 0, 2]\n uncertainty[:, 3] = L[:, 1, 1]\n uncertainty[:, 4] = L[:, 1, 2]\n uncertainty[:, 5] = L[:, 2, 2]\n return uncertainty\n\ndef strip_symmetric(sym):\n return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n norm = torch.sqrt(r[...,0]*r[...,0] + r[...,1]*r[...,1] + r[...,2]*r[...,2] + r[...,3]*r[...,3])\n ","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.F","uri":"program://EfficientDynamic3DGaussian/class/utils.general_utils.F#L112-L124","kind":"class","name":"F","path":"utils/general_utils.py","language":"python","start_line":112,"end_line":124,"context_start_line":92,"context_end_line":131,"code":" R[..., 1, 1] = 1 - 2 * (x*x + z*z)\n R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n torch.cuda.set_device(torch.device(\"cuda:0\"))","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.__init__","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.__init__#L113-L114","kind":"function","name":"__init__","path":"utils/general_utils.py","language":"python","start_line":113,"end_line":114,"context_start_line":93,"context_end_line":131,"code":" R[..., 1, 2] = 2 * (y*z - r*x)\n R[..., 2, 0] = 2 * (x*z - r*y)\n R[..., 2, 1] = 2 * (y*z + r*x)\n R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n torch.cuda.set_device(torch.device(\"cuda:0\"))","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.write","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.write#L116-L121","kind":"function","name":"write","path":"utils/general_utils.py","language":"python","start_line":116,"end_line":121,"context_start_line":96,"context_end_line":131,"code":" R[..., 2, 2] = 1 - 2 * (x*x + y*y)\n return R\n\ndef build_scaling_rotation(s, r):\n L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n R = build_rotation(r)\n\n L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n torch.cuda.set_device(torch.device(\"cuda:0\"))","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.general_utils.flush","uri":"program://EfficientDynamic3DGaussian/function/utils.general_utils.flush#L123-L124","kind":"function","name":"flush","path":"utils/general_utils.py","language":"python","start_line":123,"end_line":124,"context_start_line":103,"context_end_line":131,"code":" L[:,0,0] = s[:,0]\n L[:,1,1] = s[:,1]\n L[:,2,2] = s[:,2]\n\n L = R @ L\n return L\n\ndef safe_state(silent):\n old_f = sys.stdout\n class F:\n def __init__(self, silent):\n self.silent = silent\n\n def write(self, x):\n if not self.silent:\n if x.endswith(\"\\n\"):\n old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n else:\n old_f.write(x)\n\n def flush(self):\n old_f.flush()\n\n sys.stdout = F(silent)\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n torch.cuda.set_device(torch.device(\"cuda:0\"))","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.sh_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.sh_utils#L1-L118","kind":"module","name":"utils.sh_utils","path":"utils/sh_utils.py","language":"python","start_line":1,"end_line":118,"context_start_line":1,"context_end_line":118,"code":"# Copyright 2021 The PlenOctree Authors.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport torch\n\nC0 = 0.28209479177387814\nC1 = 0.4886025119029199\nC2 = [\n 1.0925484305920792,\n -1.0925484305920792,\n 0.31539156525252005,\n -1.0925484305920792,\n 0.5462742152960396\n]\nC3 = [\n -0.5900435899266435,\n 2.890611442640554,\n -0.4570457994644658,\n 0.3731763325901154,\n -0.4570457994644658,\n 1.445305721320277,\n -0.5900435899266435\n]\nC4 = [\n 2.5033429417967046,\n -1.7701307697799304,\n 0.9461746957575601,\n -0.6690465435572892,\n 0.10578554691520431,\n -0.6690465435572892,\n 0.47308734787878004,\n -1.7701307697799304,\n 0.6258357354491761,\n] \n\n\ndef eval_sh(deg, sh, dirs):\n \"\"\"\n Evaluate spherical harmonics at unit directions\n using hardcoded SH polynomials.\n Works with torch/np/jnp.\n ... Can be 0 or more batch dimensions.\n Args:\n deg: int SH deg. Currently, 0-3 supported\n sh: jnp.ndarray SH coeffs [..., C, (deg + 1) ** 2]\n dirs: jnp.ndarray unit directions [..., 3]\n Returns:\n [..., C]\n \"\"\"\n assert deg <= 4 and deg >= 0\n coeff = (deg + 1) ** 2\n assert sh.shape[-1] >= coeff\n\n result = C0 * sh[..., 0]\n if deg > 0:\n x, y, z = dirs[..., 0:1], dirs[..., 1:2], dirs[..., 2:3]\n result = (result -\n C1 * y * sh[..., 1] +\n C1 * z * sh[..., 2] -\n C1 * x * sh[..., 3])\n\n if deg > 1:\n xx, yy, zz = x * x, y * y, z * z\n xy, yz, xz = x * y, y * z, x * z\n result = (result +\n C2[0] * xy * sh[..., 4] +\n C2[1] * yz * sh[..., 5] +\n C2[2] * (2.0 * zz - xx - yy) * sh[..., 6] +\n C2[3] * xz * sh[..., 7] +\n C2[4] * (xx - yy) * sh[..., 8])\n\n if deg > 2:\n result = (result +\n C3[0] * y * (3 * xx - yy) * sh[..., 9] +\n C3[1] * xy * z * sh[..., 10] +\n C3[2] * y * (4 * zz - xx - yy)* sh[..., 11] +\n C3[3] * z * (2 * zz - 3 * xx - 3 * yy) * sh[..., 12] +\n C3[4] * x * (4 * zz - xx - yy) * sh[..., 13] +\n C3[5] * z * (xx - yy) * sh[..., 14] +\n C3[6] * x * (xx - 3 * yy) * sh[..., 15])\n\n if deg > 3:\n result = (result + C4[0] * xy * (xx - yy) * sh[..., 16] +\n C4[1] * yz * (3 * xx - yy) * sh[..., 17] +\n C4[2] * xy * (7 * zz - 1) * sh[..., 18] +\n C4[3] * yz * (7 * zz - 3) * sh[..., 19] +\n C4[4] * (zz * (35 * zz - 30) + 3) * sh[..., 20] +\n C4[5] * xz * (7 * zz - 3) * sh[..., 21] +\n C4[6] * (xx - yy) * (7 * zz - 1) * sh[..., 22] +\n C4[7] * xz * (xx - 3 * yy) * sh[..., 23] +\n C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) * sh[..., 24])\n return result\n\ndef RGB2SH(rgb):\n return (rgb - 0.5) / C0\n\ndef SH2RGB(sh):\n return sh * C0 + 0.5","source_hash":"7d1ff267546390635e6d1f68c4f88c4a8b052482d5c9be1d32f06bc69e9a96e7","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.sh_utils.eval_sh","uri":"program://EfficientDynamic3DGaussian/function/utils.sh_utils.eval_sh#L57-L112","kind":"function","name":"eval_sh","path":"utils/sh_utils.py","language":"python","start_line":57,"end_line":112,"context_start_line":37,"context_end_line":118,"code":" 2.890611442640554,\n -0.4570457994644658,\n 0.3731763325901154,\n -0.4570457994644658,\n 1.445305721320277,\n -0.5900435899266435\n]\nC4 = [\n 2.5033429417967046,\n -1.7701307697799304,\n 0.9461746957575601,\n -0.6690465435572892,\n 0.10578554691520431,\n -0.6690465435572892,\n 0.47308734787878004,\n -1.7701307697799304,\n 0.6258357354491761,\n] \n\n\ndef eval_sh(deg, sh, dirs):\n \"\"\"\n Evaluate spherical harmonics at unit directions\n using hardcoded SH polynomials.\n Works with torch/np/jnp.\n ... Can be 0 or more batch dimensions.\n Args:\n deg: int SH deg. Currently, 0-3 supported\n sh: jnp.ndarray SH coeffs [..., C, (deg + 1) ** 2]\n dirs: jnp.ndarray unit directions [..., 3]\n Returns:\n [..., C]\n \"\"\"\n assert deg <= 4 and deg >= 0\n coeff = (deg + 1) ** 2\n assert sh.shape[-1] >= coeff\n\n result = C0 * sh[..., 0]\n if deg > 0:\n x, y, z = dirs[..., 0:1], dirs[..., 1:2], dirs[..., 2:3]\n result = (result -\n C1 * y * sh[..., 1] +\n C1 * z * sh[..., 2] -\n C1 * x * sh[..., 3])\n\n if deg > 1:\n xx, yy, zz = x * x, y * y, z * z\n xy, yz, xz = x * y, y * z, x * z\n result = (result +\n C2[0] * xy * sh[..., 4] +\n C2[1] * yz * sh[..., 5] +\n C2[2] * (2.0 * zz - xx - yy) * sh[..., 6] +\n C2[3] * xz * sh[..., 7] +\n C2[4] * (xx - yy) * sh[..., 8])\n\n if deg > 2:\n result = (result +\n C3[0] * y * (3 * xx - yy) * sh[..., 9] +\n C3[1] * xy * z * sh[..., 10] +\n C3[2] * y * (4 * zz - xx - yy)* sh[..., 11] +\n C3[3] * z * (2 * zz - 3 * xx - 3 * yy) * sh[..., 12] +\n C3[4] * x * (4 * zz - xx - yy) * sh[..., 13] +\n C3[5] * z * (xx - yy) * sh[..., 14] +\n C3[6] * x * (xx - 3 * yy) * sh[..., 15])\n\n if deg > 3:\n result = (result + C4[0] * xy * (xx - yy) * sh[..., 16] +\n C4[1] * yz * (3 * xx - yy) * sh[..., 17] +\n C4[2] * xy * (7 * zz - 1) * sh[..., 18] +\n C4[3] * yz * (7 * zz - 3) * sh[..., 19] +\n C4[4] * (zz * (35 * zz - 30) + 3) * sh[..., 20] +\n C4[5] * xz * (7 * zz - 3) * sh[..., 21] +\n C4[6] * (xx - yy) * (7 * zz - 1) * sh[..., 22] +\n C4[7] * xz * (xx - 3 * yy) * sh[..., 23] +\n C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) * sh[..., 24])\n return result\n\ndef RGB2SH(rgb):\n return (rgb - 0.5) / C0\n\ndef SH2RGB(sh):\n return sh * C0 + 0.5","source_hash":"7d1ff267546390635e6d1f68c4f88c4a8b052482d5c9be1d32f06bc69e9a96e7","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.sh_utils.RGB2SH","uri":"program://EfficientDynamic3DGaussian/function/utils.sh_utils.RGB2SH#L114-L115","kind":"function","name":"RGB2SH","path":"utils/sh_utils.py","language":"python","start_line":114,"end_line":115,"context_start_line":94,"context_end_line":118,"code":" C3[0] * y * (3 * xx - yy) * sh[..., 9] +\n C3[1] * xy * z * sh[..., 10] +\n C3[2] * y * (4 * zz - xx - yy)* sh[..., 11] +\n C3[3] * z * (2 * zz - 3 * xx - 3 * yy) * sh[..., 12] +\n C3[4] * x * (4 * zz - xx - yy) * sh[..., 13] +\n C3[5] * z * (xx - yy) * sh[..., 14] +\n C3[6] * x * (xx - 3 * yy) * sh[..., 15])\n\n if deg > 3:\n result = (result + C4[0] * xy * (xx - yy) * sh[..., 16] +\n C4[1] * yz * (3 * xx - yy) * sh[..., 17] +\n C4[2] * xy * (7 * zz - 1) * sh[..., 18] +\n C4[3] * yz * (7 * zz - 3) * sh[..., 19] +\n C4[4] * (zz * (35 * zz - 30) + 3) * sh[..., 20] +\n C4[5] * xz * (7 * zz - 3) * sh[..., 21] +\n C4[6] * (xx - yy) * (7 * zz - 1) * sh[..., 22] +\n C4[7] * xz * (xx - 3 * yy) * sh[..., 23] +\n C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) * sh[..., 24])\n return result\n\ndef RGB2SH(rgb):\n return (rgb - 0.5) / C0\n\ndef SH2RGB(sh):\n return sh * C0 + 0.5","source_hash":"7d1ff267546390635e6d1f68c4f88c4a8b052482d5c9be1d32f06bc69e9a96e7","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.sh_utils.SH2RGB","uri":"program://EfficientDynamic3DGaussian/function/utils.sh_utils.SH2RGB#L117-L118","kind":"function","name":"SH2RGB","path":"utils/sh_utils.py","language":"python","start_line":117,"end_line":118,"context_start_line":97,"context_end_line":118,"code":" C3[3] * z * (2 * zz - 3 * xx - 3 * yy) * sh[..., 12] +\n C3[4] * x * (4 * zz - xx - yy) * sh[..., 13] +\n C3[5] * z * (xx - yy) * sh[..., 14] +\n C3[6] * x * (xx - 3 * yy) * sh[..., 15])\n\n if deg > 3:\n result = (result + C4[0] * xy * (xx - yy) * sh[..., 16] +\n C4[1] * yz * (3 * xx - yy) * sh[..., 17] +\n C4[2] * xy * (7 * zz - 1) * sh[..., 18] +\n C4[3] * yz * (7 * zz - 3) * sh[..., 19] +\n C4[4] * (zz * (35 * zz - 30) + 3) * sh[..., 20] +\n C4[5] * xz * (7 * zz - 3) * sh[..., 21] +\n C4[6] * (xx - yy) * (7 * zz - 1) * sh[..., 22] +\n C4[7] * xz * (xx - 3 * yy) * sh[..., 23] +\n C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) * sh[..., 24])\n return result\n\ndef RGB2SH(rgb):\n return (rgb - 0.5) / C0\n\ndef SH2RGB(sh):\n return sh * C0 + 0.5","source_hash":"7d1ff267546390635e6d1f68c4f88c4a8b052482d5c9be1d32f06bc69e9a96e7","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.camera_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.camera_utils#L1-L120","kind":"module","name":"utils.camera_utils","path":"utils/camera_utils.py","language":"python","start_line":1,"end_line":120,"context_start_line":1,"context_end_line":120,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\nimport os\n\nimport torch\nfrom scene.cameras import Camera, Camera2\nimport numpy as np\nfrom utils.general_utils import PILtoTorch\nfrom utils.graphics_utils import fov2focal\n\nWARNED = False\n\ndef loadCam(args, id, cam_info, resolution_scale):\n orig_w, orig_h = cam_info.image.size\n\n if args.resolution in [1, 2, 4, 8]:\n resolution = round(orig_w/(resolution_scale * args.resolution)), round(orig_h/(resolution_scale * args.resolution))\n else: # should be a type that converts to float\n if args.resolution == -1:\n if orig_w > 1600:\n global WARNED\n if not WARNED:\n print(\"[ INFO ] Encountered quite large input images (>1.6K pixels width), rescaling to 1.6K.\\n \"\n \"If this is not desired, please explicitly specify '--resolution/-r' as 1\")\n WARNED = True\n global_down = orig_w / 1600\n else:\n global_down = 1\n else:\n global_down = orig_w / args.resolution\n\n scale = float(global_down) * float(resolution_scale)\n resolution = (int(orig_w / scale), int(orig_h / scale))\n\n resized_image_rgb = PILtoTorch(cam_info.image, resolution)\n data_root = '/'.join(cam_info.image_path.split('/')[:-2])\n folder = cam_info.image_path.split('/')[-2]\n image_name = cam_info.image_path.split('/')[-1]\n fwd_flow_path = os.path.join(data_root, f'{folder}_flow', f'{os.path.splitext(image_name)[0]}_fwd.npz')\n bwd_flow_path = os.path.join(data_root, f'{folder}_flow', f'{os.path.splitext(image_name)[0]}_bwd.npz')\n # print(fwd_flow_path, bwd_flow_path)\n if os.path.exists(fwd_flow_path):\n fwd_data = np.load(fwd_flow_path)\n fwd_flow = torch.from_numpy(fwd_data['flow'])\n fwd_flow_mask = torch.from_numpy(fwd_data['mask'])\n else:\n fwd_flow, fwd_flow_mask = None, None\n if os.path.exists(bwd_flow_path):\n bwd_data = np.load(bwd_flow_path)\n bwd_flow = torch.from_numpy(bwd_data['flow'])\n bwd_flow_mask = torch.from_numpy(bwd_data['mask'])\n else:\n bwd_flow, bwd_flow_mask = None, None\n\n\n gt_image = resized_image_rgb[:3, ...]\n loaded_mask = None\n\n if resized_image_rgb.shape[1] == 4:\n loaded_mask = resized_image_rgb[3:4, ...]\n\n return Camera(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, \n image=gt_image, gt_alpha_mask=loaded_mask,\n image_name=cam_info.image_name, uid=id, time=cam_info.time, data_device=args.data_device,\n fwd_flow=fwd_flow, fwd_flow_mask=fwd_flow_mask,\n bwd_flow=bwd_flow, bwd_flow_mask=bwd_flow_mask)\n\ndef loadCam2(args, id, cam_info, resolution_scale):\n return Camera2(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, width=cam_info.width, height=cam_info.height,\n uid=id, time=cam_info.time, data_device=args.data_device)\n\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam(args, id, c, resolution_scale))\n\n return camera_list\n\ndef cameraList_from_camInfos_without_image(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam2(args, id, c, resolution_scale))\n\n return camera_list\n\n\ndef camera_to_JSON(id, camera : Camera):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = camera.R.transpose()\n Rt[:3, 3] = camera.T\n Rt[3, 3] = 1.0\n\n W2C = np.linalg.inv(Rt)\n pos = W2C[:3, 3]\n rot = W2C[:3, :3]\n serializable_array_2d = [x.tolist() for x in rot]\n camera_entry = {\n 'id' : id,\n 'img_name' : camera.image_name,\n 'width' : camera.width,\n 'height' : camera.height,\n 'position': pos.tolist(),\n 'rotation': serializable_array_2d,\n 'fy' : fov2focal(camera.FovY, camera.height),\n 'fx' : fov2focal(camera.FovX, camera.width)\n }\n return camera_entry","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.camera_utils.loadCam","uri":"program://EfficientDynamic3DGaussian/function/utils.camera_utils.loadCam#L21-L75","kind":"function","name":"loadCam","path":"utils/camera_utils.py","language":"python","start_line":21,"end_line":75,"context_start_line":1,"context_end_line":95,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\nimport os\n\nimport torch\nfrom scene.cameras import Camera, Camera2\nimport numpy as np\nfrom utils.general_utils import PILtoTorch\nfrom utils.graphics_utils import fov2focal\n\nWARNED = False\n\ndef loadCam(args, id, cam_info, resolution_scale):\n orig_w, orig_h = cam_info.image.size\n\n if args.resolution in [1, 2, 4, 8]:\n resolution = round(orig_w/(resolution_scale * args.resolution)), round(orig_h/(resolution_scale * args.resolution))\n else: # should be a type that converts to float\n if args.resolution == -1:\n if orig_w > 1600:\n global WARNED\n if not WARNED:\n print(\"[ INFO ] Encountered quite large input images (>1.6K pixels width), rescaling to 1.6K.\\n \"\n \"If this is not desired, please explicitly specify '--resolution/-r' as 1\")\n WARNED = True\n global_down = orig_w / 1600\n else:\n global_down = 1\n else:\n global_down = orig_w / args.resolution\n\n scale = float(global_down) * float(resolution_scale)\n resolution = (int(orig_w / scale), int(orig_h / scale))\n\n resized_image_rgb = PILtoTorch(cam_info.image, resolution)\n data_root = '/'.join(cam_info.image_path.split('/')[:-2])\n folder = cam_info.image_path.split('/')[-2]\n image_name = cam_info.image_path.split('/')[-1]\n fwd_flow_path = os.path.join(data_root, f'{folder}_flow', f'{os.path.splitext(image_name)[0]}_fwd.npz')\n bwd_flow_path = os.path.join(data_root, f'{folder}_flow', f'{os.path.splitext(image_name)[0]}_bwd.npz')\n # print(fwd_flow_path, bwd_flow_path)\n if os.path.exists(fwd_flow_path):\n fwd_data = np.load(fwd_flow_path)\n fwd_flow = torch.from_numpy(fwd_data['flow'])\n fwd_flow_mask = torch.from_numpy(fwd_data['mask'])\n else:\n fwd_flow, fwd_flow_mask = None, None\n if os.path.exists(bwd_flow_path):\n bwd_data = np.load(bwd_flow_path)\n bwd_flow = torch.from_numpy(bwd_data['flow'])\n bwd_flow_mask = torch.from_numpy(bwd_data['mask'])\n else:\n bwd_flow, bwd_flow_mask = None, None\n\n\n gt_image = resized_image_rgb[:3, ...]\n loaded_mask = None\n\n if resized_image_rgb.shape[1] == 4:\n loaded_mask = resized_image_rgb[3:4, ...]\n\n return Camera(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, \n image=gt_image, gt_alpha_mask=loaded_mask,\n image_name=cam_info.image_name, uid=id, time=cam_info.time, data_device=args.data_device,\n fwd_flow=fwd_flow, fwd_flow_mask=fwd_flow_mask,\n bwd_flow=bwd_flow, bwd_flow_mask=bwd_flow_mask)\n\ndef loadCam2(args, id, cam_info, resolution_scale):\n return Camera2(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, width=cam_info.width, height=cam_info.height,\n uid=id, time=cam_info.time, data_device=args.data_device)\n\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam(args, id, c, resolution_scale))\n\n return camera_list\n\ndef cameraList_from_camInfos_without_image(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam2(args, id, c, resolution_scale))","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.camera_utils.loadCam2","uri":"program://EfficientDynamic3DGaussian/function/utils.camera_utils.loadCam2#L77-L80","kind":"function","name":"loadCam2","path":"utils/camera_utils.py","language":"python","start_line":77,"end_line":80,"context_start_line":57,"context_end_line":100,"code":" bwd_data = np.load(bwd_flow_path)\n bwd_flow = torch.from_numpy(bwd_data['flow'])\n bwd_flow_mask = torch.from_numpy(bwd_data['mask'])\n else:\n bwd_flow, bwd_flow_mask = None, None\n\n\n gt_image = resized_image_rgb[:3, ...]\n loaded_mask = None\n\n if resized_image_rgb.shape[1] == 4:\n loaded_mask = resized_image_rgb[3:4, ...]\n\n return Camera(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, \n image=gt_image, gt_alpha_mask=loaded_mask,\n image_name=cam_info.image_name, uid=id, time=cam_info.time, data_device=args.data_device,\n fwd_flow=fwd_flow, fwd_flow_mask=fwd_flow_mask,\n bwd_flow=bwd_flow, bwd_flow_mask=bwd_flow_mask)\n\ndef loadCam2(args, id, cam_info, resolution_scale):\n return Camera2(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, width=cam_info.width, height=cam_info.height,\n uid=id, time=cam_info.time, data_device=args.data_device)\n\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam(args, id, c, resolution_scale))\n\n return camera_list\n\ndef cameraList_from_camInfos_without_image(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam2(args, id, c, resolution_scale))\n\n return camera_list\n\n\ndef camera_to_JSON(id, camera : Camera):","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.camera_utils.cameraList_from_camInfos","uri":"program://EfficientDynamic3DGaussian/function/utils.camera_utils.cameraList_from_camInfos#L83-L89","kind":"function","name":"cameraList_from_camInfos","path":"utils/camera_utils.py","language":"python","start_line":83,"end_line":89,"context_start_line":63,"context_end_line":109,"code":"\n gt_image = resized_image_rgb[:3, ...]\n loaded_mask = None\n\n if resized_image_rgb.shape[1] == 4:\n loaded_mask = resized_image_rgb[3:4, ...]\n\n return Camera(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, \n image=gt_image, gt_alpha_mask=loaded_mask,\n image_name=cam_info.image_name, uid=id, time=cam_info.time, data_device=args.data_device,\n fwd_flow=fwd_flow, fwd_flow_mask=fwd_flow_mask,\n bwd_flow=bwd_flow, bwd_flow_mask=bwd_flow_mask)\n\ndef loadCam2(args, id, cam_info, resolution_scale):\n return Camera2(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, width=cam_info.width, height=cam_info.height,\n uid=id, time=cam_info.time, data_device=args.data_device)\n\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam(args, id, c, resolution_scale))\n\n return camera_list\n\ndef cameraList_from_camInfos_without_image(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam2(args, id, c, resolution_scale))\n\n return camera_list\n\n\ndef camera_to_JSON(id, camera : Camera):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = camera.R.transpose()\n Rt[:3, 3] = camera.T\n Rt[3, 3] = 1.0\n\n W2C = np.linalg.inv(Rt)\n pos = W2C[:3, 3]\n rot = W2C[:3, :3]\n serializable_array_2d = [x.tolist() for x in rot]","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.camera_utils.cameraList_from_camInfos_without_image","uri":"program://EfficientDynamic3DGaussian/function/utils.camera_utils.cameraList_from_camInfos_without_image#L91-L97","kind":"function","name":"cameraList_from_camInfos_without_image","path":"utils/camera_utils.py","language":"python","start_line":91,"end_line":97,"context_start_line":71,"context_end_line":117,"code":" FoVx=cam_info.FovX, FoVy=cam_info.FovY, \n image=gt_image, gt_alpha_mask=loaded_mask,\n image_name=cam_info.image_name, uid=id, time=cam_info.time, data_device=args.data_device,\n fwd_flow=fwd_flow, fwd_flow_mask=fwd_flow_mask,\n bwd_flow=bwd_flow, bwd_flow_mask=bwd_flow_mask)\n\ndef loadCam2(args, id, cam_info, resolution_scale):\n return Camera2(colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n FoVx=cam_info.FovX, FoVy=cam_info.FovY, width=cam_info.width, height=cam_info.height,\n uid=id, time=cam_info.time, data_device=args.data_device)\n\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam(args, id, c, resolution_scale))\n\n return camera_list\n\ndef cameraList_from_camInfos_without_image(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam2(args, id, c, resolution_scale))\n\n return camera_list\n\n\ndef camera_to_JSON(id, camera : Camera):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = camera.R.transpose()\n Rt[:3, 3] = camera.T\n Rt[3, 3] = 1.0\n\n W2C = np.linalg.inv(Rt)\n pos = W2C[:3, 3]\n rot = W2C[:3, :3]\n serializable_array_2d = [x.tolist() for x in rot]\n camera_entry = {\n 'id' : id,\n 'img_name' : camera.image_name,\n 'width' : camera.width,\n 'height' : camera.height,\n 'position': pos.tolist(),\n 'rotation': serializable_array_2d,\n 'fy' : fov2focal(camera.FovY, camera.height),","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.camera_utils.camera_to_JSON","uri":"program://EfficientDynamic3DGaussian/function/utils.camera_utils.camera_to_JSON#L100-L120","kind":"function","name":"camera_to_JSON","path":"utils/camera_utils.py","language":"python","start_line":100,"end_line":120,"context_start_line":80,"context_end_line":120,"code":" uid=id, time=cam_info.time, data_device=args.data_device)\n\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam(args, id, c, resolution_scale))\n\n return camera_list\n\ndef cameraList_from_camInfos_without_image(cam_infos, resolution_scale, args):\n camera_list = []\n\n for id, c in enumerate(cam_infos):\n camera_list.append(loadCam2(args, id, c, resolution_scale))\n\n return camera_list\n\n\ndef camera_to_JSON(id, camera : Camera):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = camera.R.transpose()\n Rt[:3, 3] = camera.T\n Rt[3, 3] = 1.0\n\n W2C = np.linalg.inv(Rt)\n pos = W2C[:3, 3]\n rot = W2C[:3, :3]\n serializable_array_2d = [x.tolist() for x in rot]\n camera_entry = {\n 'id' : id,\n 'img_name' : camera.image_name,\n 'width' : camera.width,\n 'height' : camera.height,\n 'position': pos.tolist(),\n 'rotation': serializable_array_2d,\n 'fy' : fov2focal(camera.FovY, camera.height),\n 'fx' : fov2focal(camera.FovX, camera.width)\n }\n return camera_entry","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils","uri":"program://EfficientDynamic3DGaussian/module/utils.loss_utils#L1-L73","kind":"module","name":"utils.loss_utils","path":"utils/loss_utils.py","language":"python","start_line":1,"end_line":73,"context_start_line":1,"context_end_line":73,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nfrom torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)\n\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\n mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq\n sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2\n\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n if size_average:\n return ssim_map.mean()\n else:\n return ssim_map.mean(1).mean(1).mean(1)\n\n\ndef msssim(rgb, gts):\n assert (rgb.max() <= 1.05 and rgb.min() >= -0.05)\n assert (gts.max() <= 1.05 and gts.min() >= -0.05)\n return ms_ssim(rgb, gts).item()\n ","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils.l1_loss","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils.l1_loss#L20-L21","kind":"function","name":"l1_loss","path":"utils/loss_utils.py","language":"python","start_line":20,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nfrom torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils.l2_loss","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils.l2_loss#L23-L24","kind":"function","name":"l2_loss","path":"utils/loss_utils.py","language":"python","start_line":23,"end_line":24,"context_start_line":3,"context_end_line":44,"code":"# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nfrom torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils.gaussian","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils.gaussian#L26-L28","kind":"function","name":"gaussian","path":"utils/loss_utils.py","language":"python","start_line":26,"end_line":28,"context_start_line":6,"context_end_line":48,"code":"# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nfrom torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)\n\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\n mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils.create_window","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils.create_window#L30-L34","kind":"function","name":"create_window","path":"utils/loss_utils.py","language":"python","start_line":30,"end_line":34,"context_start_line":10,"context_end_line":54,"code":"#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nfrom torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)\n\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\n mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils.ssim","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils.ssim#L36-L44","kind":"function","name":"ssim","path":"utils/loss_utils.py","language":"python","start_line":36,"end_line":44,"context_start_line":16,"context_end_line":64,"code":"from torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)\n\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\n mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq\n sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2\n\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n if size_average:\n return ssim_map.mean()","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils._ssim","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils._ssim#L46-L66","kind":"function","name":"_ssim","path":"utils/loss_utils.py","language":"python","start_line":46,"end_line":66,"context_start_line":26,"context_end_line":73,"code":"def gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)\n\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\n mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq\n sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2\n\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n if size_average:\n return ssim_map.mean()\n else:\n return ssim_map.mean(1).mean(1).mean(1)\n\n\ndef msssim(rgb, gts):\n assert (rgb.max() <= 1.05 and rgb.min() >= -0.05)\n assert (gts.max() <= 1.05 and gts.min() >= -0.05)\n return ms_ssim(rgb, gts).item()\n ","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:utils.loss_utils.msssim","uri":"program://EfficientDynamic3DGaussian/function/utils.loss_utils.msssim#L69-L72","kind":"function","name":"msssim","path":"utils/loss_utils.py","language":"python","start_line":69,"end_line":72,"context_start_line":49,"context_end_line":73,"code":"\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq\n sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2\n\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n if size_average:\n return ssim_map.mean()\n else:\n return ssim_map.mean(1).mean(1).mean(1)\n\n\ndef msssim(rgb, gts):\n assert (rgb.max() <= 1.05 and rgb.min() >= -0.05)\n assert (gts.max() <= 1.05 and gts.min() >= -0.05)\n return ms_ssim(rgb, gts).item()\n ","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:gaussian_renderer.network_gui","uri":"program://EfficientDynamic3DGaussian/module/gaussian_renderer.network_gui#L1-L86","kind":"module","name":"gaussian_renderer.network_gui","path":"gaussian_renderer/network_gui.py","language":"python","start_line":1,"end_line":86,"context_start_line":1,"context_end_line":86,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport traceback\nimport socket\nimport json\nfrom scene.cameras import MiniCam\n\nhost = \"127.0.0.1\"\nport = 6009\n\nconn = None\naddr = None\n\nlistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef init(wish_host, wish_port):\n global host, port, listener\n host = wish_host\n port = wish_port\n listener.bind((host, port))\n listener.listen()\n listener.settimeout(0)\n\ndef try_connect():\n global conn, addr, listener\n try:\n conn, addr = listener.accept()\n print(f\"\\nConnected by {addr}\")\n conn.settimeout(None)\n except Exception as inst:\n pass\n \ndef read():\n global conn\n messageLength = conn.recv(4)\n messageLength = int.from_bytes(messageLength, 'little')\n message = conn.recv(messageLength)\n return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n global conn\n if message_bytes != None:\n conn.sendall(message_bytes)\n conn.sendall(len(verify).to_bytes(4, 'little'))\n conn.sendall(bytes(verify, 'ascii'))\n\ndef receive():\n message = read()\n\n width = message[\"resolution_x\"]\n height = message[\"resolution_y\"]\n\n if width != 0 and height != 0:\n try:\n do_training = bool(message[\"train\"])\n fovy = message[\"fov_y\"]\n fovx = message[\"fov_x\"]\n znear = message[\"z_near\"]\n zfar = message[\"z_far\"]\n do_shs_python = bool(message[\"shs_python\"])\n do_rot_scale_python = bool(message[\"rot_scale_python\"])\n keep_alive = bool(message[\"keep_alive\"])\n scaling_modifier = message[\"scaling_modifier\"]\n world_view_transform = torch.reshape(torch.tensor(message[\"view_matrix\"]), (4, 4)).cuda()\n world_view_transform[:,1] = -world_view_transform[:,1]\n world_view_transform[:,2] = -world_view_transform[:,2]\n full_proj_transform = torch.reshape(torch.tensor(message[\"view_projection_matrix\"]), (4, 4)).cuda()\n full_proj_transform[:,1] = -full_proj_transform[:,1]\n custom_cam = MiniCam(width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform)\n except Exception as e:\n print(\"\")\n traceback.print_exc()\n raise e\n return custom_cam, do_training, do_shs_python, do_rot_scale_python, keep_alive, scaling_modifier\n else:\n return None, None, None, None, None, None","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:gaussian_renderer.network_gui.init","uri":"program://EfficientDynamic3DGaussian/function/gaussian_renderer.network_gui.init#L26-L32","kind":"function","name":"init","path":"gaussian_renderer/network_gui.py","language":"python","start_line":26,"end_line":32,"context_start_line":6,"context_end_line":52,"code":"# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport traceback\nimport socket\nimport json\nfrom scene.cameras import MiniCam\n\nhost = \"127.0.0.1\"\nport = 6009\n\nconn = None\naddr = None\n\nlistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef init(wish_host, wish_port):\n global host, port, listener\n host = wish_host\n port = wish_port\n listener.bind((host, port))\n listener.listen()\n listener.settimeout(0)\n\ndef try_connect():\n global conn, addr, listener\n try:\n conn, addr = listener.accept()\n print(f\"\\nConnected by {addr}\")\n conn.settimeout(None)\n except Exception as inst:\n pass\n \ndef read():\n global conn\n messageLength = conn.recv(4)\n messageLength = int.from_bytes(messageLength, 'little')\n message = conn.recv(messageLength)\n return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n global conn\n if message_bytes != None:","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:gaussian_renderer.network_gui.try_connect","uri":"program://EfficientDynamic3DGaussian/function/gaussian_renderer.network_gui.try_connect#L34-L41","kind":"function","name":"try_connect","path":"gaussian_renderer/network_gui.py","language":"python","start_line":34,"end_line":41,"context_start_line":14,"context_end_line":61,"code":"import socket\nimport json\nfrom scene.cameras import MiniCam\n\nhost = \"127.0.0.1\"\nport = 6009\n\nconn = None\naddr = None\n\nlistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef init(wish_host, wish_port):\n global host, port, listener\n host = wish_host\n port = wish_port\n listener.bind((host, port))\n listener.listen()\n listener.settimeout(0)\n\ndef try_connect():\n global conn, addr, listener\n try:\n conn, addr = listener.accept()\n print(f\"\\nConnected by {addr}\")\n conn.settimeout(None)\n except Exception as inst:\n pass\n \ndef read():\n global conn\n messageLength = conn.recv(4)\n messageLength = int.from_bytes(messageLength, 'little')\n message = conn.recv(messageLength)\n return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n global conn\n if message_bytes != None:\n conn.sendall(message_bytes)\n conn.sendall(len(verify).to_bytes(4, 'little'))\n conn.sendall(bytes(verify, 'ascii'))\n\ndef receive():\n message = read()\n\n width = message[\"resolution_x\"]\n height = message[\"resolution_y\"]","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:gaussian_renderer.network_gui.read","uri":"program://EfficientDynamic3DGaussian/function/gaussian_renderer.network_gui.read#L43-L48","kind":"function","name":"read","path":"gaussian_renderer/network_gui.py","language":"python","start_line":43,"end_line":48,"context_start_line":23,"context_end_line":68,"code":"\nlistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef init(wish_host, wish_port):\n global host, port, listener\n host = wish_host\n port = wish_port\n listener.bind((host, port))\n listener.listen()\n listener.settimeout(0)\n\ndef try_connect():\n global conn, addr, listener\n try:\n conn, addr = listener.accept()\n print(f\"\\nConnected by {addr}\")\n conn.settimeout(None)\n except Exception as inst:\n pass\n \ndef read():\n global conn\n messageLength = conn.recv(4)\n messageLength = int.from_bytes(messageLength, 'little')\n message = conn.recv(messageLength)\n return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n global conn\n if message_bytes != None:\n conn.sendall(message_bytes)\n conn.sendall(len(verify).to_bytes(4, 'little'))\n conn.sendall(bytes(verify, 'ascii'))\n\ndef receive():\n message = read()\n\n width = message[\"resolution_x\"]\n height = message[\"resolution_y\"]\n\n if width != 0 and height != 0:\n try:\n do_training = bool(message[\"train\"])\n fovy = message[\"fov_y\"]\n fovx = message[\"fov_x\"]\n znear = message[\"z_near\"]","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:gaussian_renderer.network_gui.send","uri":"program://EfficientDynamic3DGaussian/function/gaussian_renderer.network_gui.send#L50-L55","kind":"function","name":"send","path":"gaussian_renderer/network_gui.py","language":"python","start_line":50,"end_line":55,"context_start_line":30,"context_end_line":75,"code":" listener.bind((host, port))\n listener.listen()\n listener.settimeout(0)\n\ndef try_connect():\n global conn, addr, listener\n try:\n conn, addr = listener.accept()\n print(f\"\\nConnected by {addr}\")\n conn.settimeout(None)\n except Exception as inst:\n pass\n \ndef read():\n global conn\n messageLength = conn.recv(4)\n messageLength = int.from_bytes(messageLength, 'little')\n message = conn.recv(messageLength)\n return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n global conn\n if message_bytes != None:\n conn.sendall(message_bytes)\n conn.sendall(len(verify).to_bytes(4, 'little'))\n conn.sendall(bytes(verify, 'ascii'))\n\ndef receive():\n message = read()\n\n width = message[\"resolution_x\"]\n height = message[\"resolution_y\"]\n\n if width != 0 and height != 0:\n try:\n do_training = bool(message[\"train\"])\n fovy = message[\"fov_y\"]\n fovx = message[\"fov_x\"]\n znear = message[\"z_near\"]\n zfar = message[\"z_far\"]\n do_shs_python = bool(message[\"shs_python\"])\n do_rot_scale_python = bool(message[\"rot_scale_python\"])\n keep_alive = bool(message[\"keep_alive\"])\n scaling_modifier = message[\"scaling_modifier\"]\n world_view_transform = torch.reshape(torch.tensor(message[\"view_matrix\"]), (4, 4)).cuda()\n world_view_transform[:,1] = -world_view_transform[:,1]","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:gaussian_renderer.network_gui.receive","uri":"program://EfficientDynamic3DGaussian/function/gaussian_renderer.network_gui.receive#L57-L86","kind":"function","name":"receive","path":"gaussian_renderer/network_gui.py","language":"python","start_line":57,"end_line":86,"context_start_line":37,"context_end_line":86,"code":" conn, addr = listener.accept()\n print(f\"\\nConnected by {addr}\")\n conn.settimeout(None)\n except Exception as inst:\n pass\n \ndef read():\n global conn\n messageLength = conn.recv(4)\n messageLength = int.from_bytes(messageLength, 'little')\n message = conn.recv(messageLength)\n return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n global conn\n if message_bytes != None:\n conn.sendall(message_bytes)\n conn.sendall(len(verify).to_bytes(4, 'little'))\n conn.sendall(bytes(verify, 'ascii'))\n\ndef receive():\n message = read()\n\n width = message[\"resolution_x\"]\n height = message[\"resolution_y\"]\n\n if width != 0 and height != 0:\n try:\n do_training = bool(message[\"train\"])\n fovy = message[\"fov_y\"]\n fovx = message[\"fov_x\"]\n znear = message[\"z_near\"]\n zfar = message[\"z_far\"]\n do_shs_python = bool(message[\"shs_python\"])\n do_rot_scale_python = bool(message[\"rot_scale_python\"])\n keep_alive = bool(message[\"keep_alive\"])\n scaling_modifier = message[\"scaling_modifier\"]\n world_view_transform = torch.reshape(torch.tensor(message[\"view_matrix\"]), (4, 4)).cuda()\n world_view_transform[:,1] = -world_view_transform[:,1]\n world_view_transform[:,2] = -world_view_transform[:,2]\n full_proj_transform = torch.reshape(torch.tensor(message[\"view_projection_matrix\"]), (4, 4)).cuda()\n full_proj_transform[:,1] = -full_proj_transform[:,1]\n custom_cam = MiniCam(width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform)\n except Exception as e:\n print(\"\")\n traceback.print_exc()\n raise e\n return custom_cam, do_training, do_shs_python, do_rot_scale_python, keep_alive, scaling_modifier\n else:\n return None, None, None, None, None, None","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks","uri":"program://EfficientDynamic3DGaussian/module/lpipsPyTorch.modules.networks#L1-L96","kind":"module","name":"lpipsPyTorch.modules.networks","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":1,"end_line":96,"context_start_line":1,"context_end_line":96,"code":"from typing import Sequence\n\nfrom itertools import chain\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\n\nfrom .utils import normalize_activation\n\n\ndef get_network(net_type: str):\n if net_type == 'alex':\n return AlexNet()\n elif net_type == 'squeeze':\n return SqueezeNet()\n elif net_type == 'vgg':\n return VGG16()\n else:\n raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')\n\n\nclass LinLayers(nn.ModuleList):\n def __init__(self, n_channels_list: Sequence[int]):\n super(LinLayers, self).__init__([\n nn.Sequential(\n nn.Identity(),\n nn.Conv2d(nc, 1, 1, 1, 0, bias=False)\n ) for nc in n_channels_list\n ])\n\n for param in self.parameters():\n param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer\n self.register_buffer(\n 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n self.register_buffer(\n 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):\n x = self.z_score(x)\n\n output = []\n for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]\n\n self.set_requires_grad(False)\n\n\nclass VGG16(BaseNet):\n def __init__(self):\n super(VGG16, self).__init__()\n\n self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features\n self.target_layers = [4, 9, 16, 23, 30]\n self.n_channels_list = [64, 128, 256, 512, 512]\n\n self.set_requires_grad(False)","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.get_network","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.networks.get_network#L12-L20","kind":"function","name":"get_network","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":12,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"from typing import Sequence\n\nfrom itertools import chain\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\n\nfrom .utils import normalize_activation\n\n\ndef get_network(net_type: str):\n if net_type == 'alex':\n return AlexNet()\n elif net_type == 'squeeze':\n return SqueezeNet()\n elif net_type == 'vgg':\n return VGG16()\n else:\n raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')\n\n\nclass LinLayers(nn.ModuleList):\n def __init__(self, n_channels_list: Sequence[int]):\n super(LinLayers, self).__init__([\n nn.Sequential(\n nn.Identity(),\n nn.Conv2d(nc, 1, 1, 1, 0, bias=False)\n ) for nc in n_channels_list\n ])\n\n for param in self.parameters():\n param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.LinLayers","uri":"program://EfficientDynamic3DGaussian/class/lpipsPyTorch.modules.networks.LinLayers#L23-L33","kind":"class","name":"LinLayers","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":23,"end_line":33,"context_start_line":3,"context_end_line":53,"code":"from itertools import chain\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\n\nfrom .utils import normalize_activation\n\n\ndef get_network(net_type: str):\n if net_type == 'alex':\n return AlexNet()\n elif net_type == 'squeeze':\n return SqueezeNet()\n elif net_type == 'vgg':\n return VGG16()\n else:\n raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')\n\n\nclass LinLayers(nn.ModuleList):\n def __init__(self, n_channels_list: Sequence[int]):\n super(LinLayers, self).__init__([\n nn.Sequential(\n nn.Identity(),\n nn.Conv2d(nc, 1, 1, 1, 0, bias=False)\n ) for nc in n_channels_list\n ])\n\n for param in self.parameters():\n param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer\n self.register_buffer(\n 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n self.register_buffer(\n 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.BaseNet","uri":"program://EfficientDynamic3DGaussian/class/lpipsPyTorch.modules.networks.BaseNet#L36-L63","kind":"class","name":"BaseNet","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":36,"end_line":63,"context_start_line":16,"context_end_line":83,"code":" return SqueezeNet()\n elif net_type == 'vgg':\n return VGG16()\n else:\n raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')\n\n\nclass LinLayers(nn.ModuleList):\n def __init__(self, n_channels_list: Sequence[int]):\n super(LinLayers, self).__init__([\n nn.Sequential(\n nn.Identity(),\n nn.Conv2d(nc, 1, 1, 1, 0, bias=False)\n ) for nc in n_channels_list\n ])\n\n for param in self.parameters():\n param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer\n self.register_buffer(\n 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n self.register_buffer(\n 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):\n x = self.z_score(x)\n\n output = []\n for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.SqueezeNet","uri":"program://EfficientDynamic3DGaussian/class/lpipsPyTorch.modules.networks.SqueezeNet#L66-L74","kind":"class","name":"SqueezeNet","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":66,"end_line":74,"context_start_line":46,"context_end_line":94,"code":" def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):\n x = self.z_score(x)\n\n output = []\n for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]\n\n self.set_requires_grad(False)\n\n\nclass VGG16(BaseNet):\n def __init__(self):\n super(VGG16, self).__init__()\n\n self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features\n self.target_layers = [4, 9, 16, 23, 30]\n self.n_channels_list = [64, 128, 256, 512, 512]","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.AlexNet","uri":"program://EfficientDynamic3DGaussian/class/lpipsPyTorch.modules.networks.AlexNet#L77-L85","kind":"class","name":"AlexNet","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":77,"end_line":85,"context_start_line":57,"context_end_line":96,"code":" for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]\n\n self.set_requires_grad(False)\n\n\nclass VGG16(BaseNet):\n def __init__(self):\n super(VGG16, self).__init__()\n\n self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features\n self.target_layers = [4, 9, 16, 23, 30]\n self.n_channels_list = [64, 128, 256, 512, 512]\n\n self.set_requires_grad(False)","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.VGG16","uri":"program://EfficientDynamic3DGaussian/class/lpipsPyTorch.modules.networks.VGG16#L88-L96","kind":"class","name":"VGG16","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":88,"end_line":96,"context_start_line":68,"context_end_line":96,"code":" super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]\n\n self.set_requires_grad(False)\n\n\nclass VGG16(BaseNet):\n def __init__(self):\n super(VGG16, self).__init__()\n\n self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features\n self.target_layers = [4, 9, 16, 23, 30]\n self.n_channels_list = [64, 128, 256, 512, 512]\n\n self.set_requires_grad(False)","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.__init__","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.networks.__init__#L89-L96","kind":"function","name":"__init__","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":89,"end_line":96,"context_start_line":69,"context_end_line":96,"code":"\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]\n\n self.set_requires_grad(False)\n\n\nclass VGG16(BaseNet):\n def __init__(self):\n super(VGG16, self).__init__()\n\n self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features\n self.target_layers = [4, 9, 16, 23, 30]\n self.n_channels_list = [64, 128, 256, 512, 512]\n\n self.set_requires_grad(False)","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.set_requires_grad","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.networks.set_requires_grad#L46-L48","kind":"function","name":"set_requires_grad","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":46,"end_line":48,"context_start_line":26,"context_end_line":68,"code":" nn.Sequential(\n nn.Identity(),\n nn.Conv2d(nc, 1, 1, 1, 0, bias=False)\n ) for nc in n_channels_list\n ])\n\n for param in self.parameters():\n param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer\n self.register_buffer(\n 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n self.register_buffer(\n 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):\n x = self.z_score(x)\n\n output = []\n for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.z_score","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.networks.z_score#L50-L51","kind":"function","name":"z_score","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":50,"end_line":51,"context_start_line":30,"context_end_line":71,"code":" ])\n\n for param in self.parameters():\n param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer\n self.register_buffer(\n 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n self.register_buffer(\n 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):\n x = self.z_score(x)\n\n output = []\n for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.networks.forward","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.networks.forward#L53-L63","kind":"function","name":"forward","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":53,"end_line":63,"context_start_line":33,"context_end_line":83,"code":" param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n def __init__(self):\n super(BaseNet, self).__init__()\n\n # register buffer\n self.register_buffer(\n 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n self.register_buffer(\n 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n def set_requires_grad(self, state: bool):\n for param in chain(self.parameters(), self.buffers()):\n param.requires_grad = state\n\n def z_score(self, x: torch.Tensor):\n return (x - self.mean) / self.std\n\n def forward(self, x: torch.Tensor):\n x = self.z_score(x)\n\n output = []\n for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n x = layer(x)\n if i in self.target_layers:\n output.append(normalize_activation(x))\n if len(output) == len(self.target_layers):\n break\n return output\n\n\nclass SqueezeNet(BaseNet):\n def __init__(self):\n super(SqueezeNet, self).__init__()\n\n self.layers = models.squeezenet1_1(True).features\n self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n def __init__(self):\n super(AlexNet, self).__init__()\n\n self.layers = models.alexnet(True).features\n self.target_layers = [2, 5, 8, 10, 12]\n self.n_channels_list = [64, 192, 384, 256, 256]","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.lpips","uri":"program://EfficientDynamic3DGaussian/module/lpipsPyTorch.modules.lpips#L1-L36","kind":"module","name":"lpipsPyTorch.modules.lpips","path":"lpipsPyTorch/modules/lpips.py","language":"python","start_line":1,"end_line":36,"context_start_line":1,"context_end_line":36,"code":"import torch\nimport torch.nn as nn\n\nfrom .networks import get_network, LinLayers\nfrom .utils import get_state_dict\n\n\nclass LPIPS(nn.Module):\n r\"\"\"Creates a criterion that measures\n Learned Perceptual Image Patch Similarity (LPIPS).\n\n Arguments:\n net_type (str): the network type to compare the features: \n 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n version (str): the version of LPIPS. Default: 0.1.\n \"\"\"\n def __init__(self, net_type: str = 'alex', version: str = '0.1'):\n\n assert version in ['0.1'], 'v0.1 is only supported now'\n\n super(LPIPS, self).__init__()\n\n # pretrained network\n self.net = get_network(net_type)\n\n # linear layers\n self.lin = LinLayers(self.net.n_channels_list)\n self.lin.load_state_dict(get_state_dict(net_type, version))\n\n def forward(self, x: torch.Tensor, y: torch.Tensor):\n feat_x, feat_y = self.net(x), self.net(y)\n\n diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]\n res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]\n\n return torch.sum(torch.cat(res, 0), 0, True)","source_hash":"3bece0b9cf9943af5b043026458819d259df9bfe7c2a1d3ffc6c905e7e5aa2b4","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.lpips.LPIPS","uri":"program://EfficientDynamic3DGaussian/class/lpipsPyTorch.modules.lpips.LPIPS#L8-L36","kind":"class","name":"LPIPS","path":"lpipsPyTorch/modules/lpips.py","language":"python","start_line":8,"end_line":36,"context_start_line":1,"context_end_line":36,"code":"import torch\nimport torch.nn as nn\n\nfrom .networks import get_network, LinLayers\nfrom .utils import get_state_dict\n\n\nclass LPIPS(nn.Module):\n r\"\"\"Creates a criterion that measures\n Learned Perceptual Image Patch Similarity (LPIPS).\n\n Arguments:\n net_type (str): the network type to compare the features: \n 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n version (str): the version of LPIPS. Default: 0.1.\n \"\"\"\n def __init__(self, net_type: str = 'alex', version: str = '0.1'):\n\n assert version in ['0.1'], 'v0.1 is only supported now'\n\n super(LPIPS, self).__init__()\n\n # pretrained network\n self.net = get_network(net_type)\n\n # linear layers\n self.lin = LinLayers(self.net.n_channels_list)\n self.lin.load_state_dict(get_state_dict(net_type, version))\n\n def forward(self, x: torch.Tensor, y: torch.Tensor):\n feat_x, feat_y = self.net(x), self.net(y)\n\n diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]\n res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]\n\n return torch.sum(torch.cat(res, 0), 0, True)","source_hash":"3bece0b9cf9943af5b043026458819d259df9bfe7c2a1d3ffc6c905e7e5aa2b4","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.lpips.__init__","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.lpips.__init__#L17-L28","kind":"function","name":"__init__","path":"lpipsPyTorch/modules/lpips.py","language":"python","start_line":17,"end_line":28,"context_start_line":1,"context_end_line":36,"code":"import torch\nimport torch.nn as nn\n\nfrom .networks import get_network, LinLayers\nfrom .utils import get_state_dict\n\n\nclass LPIPS(nn.Module):\n r\"\"\"Creates a criterion that measures\n Learned Perceptual Image Patch Similarity (LPIPS).\n\n Arguments:\n net_type (str): the network type to compare the features: \n 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n version (str): the version of LPIPS. Default: 0.1.\n \"\"\"\n def __init__(self, net_type: str = 'alex', version: str = '0.1'):\n\n assert version in ['0.1'], 'v0.1 is only supported now'\n\n super(LPIPS, self).__init__()\n\n # pretrained network\n self.net = get_network(net_type)\n\n # linear layers\n self.lin = LinLayers(self.net.n_channels_list)\n self.lin.load_state_dict(get_state_dict(net_type, version))\n\n def forward(self, x: torch.Tensor, y: torch.Tensor):\n feat_x, feat_y = self.net(x), self.net(y)\n\n diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]\n res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]\n\n return torch.sum(torch.cat(res, 0), 0, True)","source_hash":"3bece0b9cf9943af5b043026458819d259df9bfe7c2a1d3ffc6c905e7e5aa2b4","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.lpips.forward","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.lpips.forward#L30-L36","kind":"function","name":"forward","path":"lpipsPyTorch/modules/lpips.py","language":"python","start_line":30,"end_line":36,"context_start_line":10,"context_end_line":36,"code":" Learned Perceptual Image Patch Similarity (LPIPS).\n\n Arguments:\n net_type (str): the network type to compare the features: \n 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n version (str): the version of LPIPS. Default: 0.1.\n \"\"\"\n def __init__(self, net_type: str = 'alex', version: str = '0.1'):\n\n assert version in ['0.1'], 'v0.1 is only supported now'\n\n super(LPIPS, self).__init__()\n\n # pretrained network\n self.net = get_network(net_type)\n\n # linear layers\n self.lin = LinLayers(self.net.n_channels_list)\n self.lin.load_state_dict(get_state_dict(net_type, version))\n\n def forward(self, x: torch.Tensor, y: torch.Tensor):\n feat_x, feat_y = self.net(x), self.net(y)\n\n diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]\n res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]\n\n return torch.sum(torch.cat(res, 0), 0, True)","source_hash":"3bece0b9cf9943af5b043026458819d259df9bfe7c2a1d3ffc6c905e7e5aa2b4","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.utils","uri":"program://EfficientDynamic3DGaussian/module/lpipsPyTorch.modules.utils#L1-L30","kind":"module","name":"lpipsPyTorch.modules.utils","path":"lpipsPyTorch/modules/utils.py","language":"python","start_line":1,"end_line":30,"context_start_line":1,"context_end_line":30,"code":"from collections import OrderedDict\n\nimport torch\n\n\ndef normalize_activation(x, eps=1e-10):\n norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))\n return x / (norm_factor + eps)\n\n\ndef get_state_dict(net_type: str = 'alex', version: str = '0.1'):\n # build url\n url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \\\n + f'master/lpips/weights/v{version}/{net_type}.pth'\n\n # download\n old_state_dict = torch.hub.load_state_dict_from_url(\n url, progress=True,\n map_location=None if torch.cuda.is_available() else torch.device('cpu')\n )\n\n # rename keys\n new_state_dict = OrderedDict()\n for key, val in old_state_dict.items():\n new_key = key\n new_key = new_key.replace('lin', '')\n new_key = new_key.replace('model.', '')\n new_state_dict[new_key] = val\n\n return new_state_dict","source_hash":"1bd4a7d4e7b43215497675ed852936fe4f27e7ea3068afe0b0e1f7cfb6c48570","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.utils.normalize_activation","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.utils.normalize_activation#L6-L8","kind":"function","name":"normalize_activation","path":"lpipsPyTorch/modules/utils.py","language":"python","start_line":6,"end_line":8,"context_start_line":1,"context_end_line":28,"code":"from collections import OrderedDict\n\nimport torch\n\n\ndef normalize_activation(x, eps=1e-10):\n norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))\n return x / (norm_factor + eps)\n\n\ndef get_state_dict(net_type: str = 'alex', version: str = '0.1'):\n # build url\n url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \\\n + f'master/lpips/weights/v{version}/{net_type}.pth'\n\n # download\n old_state_dict = torch.hub.load_state_dict_from_url(\n url, progress=True,\n map_location=None if torch.cuda.is_available() else torch.device('cpu')\n )\n\n # rename keys\n new_state_dict = OrderedDict()\n for key, val in old_state_dict.items():\n new_key = key\n new_key = new_key.replace('lin', '')\n new_key = new_key.replace('model.', '')\n new_state_dict[new_key] = val","source_hash":"1bd4a7d4e7b43215497675ed852936fe4f27e7ea3068afe0b0e1f7cfb6c48570","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"py:lpipsPyTorch.modules.utils.get_state_dict","uri":"program://EfficientDynamic3DGaussian/function/lpipsPyTorch.modules.utils.get_state_dict#L11-L30","kind":"function","name":"get_state_dict","path":"lpipsPyTorch/modules/utils.py","language":"python","start_line":11,"end_line":30,"context_start_line":1,"context_end_line":30,"code":"from collections import OrderedDict\n\nimport torch\n\n\ndef normalize_activation(x, eps=1e-10):\n norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))\n return x / (norm_factor + eps)\n\n\ndef get_state_dict(net_type: str = 'alex', version: str = '0.1'):\n # build url\n url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \\\n + f'master/lpips/weights/v{version}/{net_type}.pth'\n\n # download\n old_state_dict = torch.hub.load_state_dict_from_url(\n url, progress=True,\n map_location=None if torch.cuda.is_available() else torch.device('cpu')\n )\n\n # rename keys\n new_state_dict = OrderedDict()\n for key, val in old_state_dict.items():\n new_key = key\n new_key = new_key.replace('lin', '')\n new_key = new_key.replace('model.', '')\n new_state_dict[new_key] = val\n\n return new_state_dict","source_hash":"1bd4a7d4e7b43215497675ed852936fe4f27e7ea3068afe0b0e1f7cfb6c48570","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:convert.py","uri":"program://EfficientDynamic3DGaussian/file/convert.py","kind":"file","name":"convert.py","path":"convert.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use\n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nimport logging\nfrom argparse import ArgumentParser\nimport shutil\n\n# This Python script is based on the shell converter script provided in the MipNerF 360 repository.\nparser = ArgumentParser(\"Colmap converter\")\nparser.add_argument(\"--no_gpu\", action='store_true')\nparser.add_argument(\"--skip_matching\", action='store_true')\nparser.add_argument(\"--source_path\", \"-s\", required=True, type=str)","source_hash":"e534a5f64425412dc7a1ae4360f8caf3421167984bbaca307916d8a40ba16b64","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:process_dynerf_dataset.py","uri":"program://EfficientDynamic3DGaussian/file/process_dynerf_dataset.py","kind":"file","name":"process_dynerf_dataset.py","path":"process_dynerf_dataset.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\ndef process_video(video_data_save, video_path, img_wh, downsample, transform):\n \"\"\"\n Load video_path data to video_data_save tensor.\n \"\"\"\n video_frames = cv2.VideoCapture(video_path)\n count = 0\n while video_frames.isOpened():\n ret, video_frame = video_frames.read()\n if ret:","source_hash":"24c7183af021e6b8f56594db6316a94c5a056735ea3327df545482b10d34e78c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:full_eval.py","uri":"program://EfficientDynamic3DGaussian/file/full_eval.py","kind":"file","name":"full_eval.py","path":"full_eval.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nfrom argparse import ArgumentParser\n\nmipnerf360_outdoor_scenes = [\"bicycle\", \"flowers\", \"garden\", \"stump\", \"treehill\"]\nmipnerf360_indoor_scenes = [\"room\", \"counter\", \"kitchen\", \"bonsai\"]\ntanks_and_temples_scenes = [\"truck\", \"train\"]\ndeep_blending_scenes = [\"drjohnson\", \"playroom\"]\n\nparser = ArgumentParser(description=\"Full evaluation script parameters\")\nparser.add_argument(\"--skip_training\", action=\"store_true\")","source_hash":"f28cca2b796b1fc5f99d63e2bd39133b1a678b607fcc55cd9051655f6540b476","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:render.py","uri":"program://EfficientDynamic3DGaussian/file/render.py","kind":"file","name":"render.py","path":"render.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser","source_hash":"77e983c44996fc119ba91d558bb3ff46d7f01aff278e417785dd00b67345a817","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:train.py","uri":"program://EfficientDynamic3DGaussian/file/train.py","kind":"file","name":"train.py","path":"train.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nimport torch\nfrom torch.utils.data import DataLoader\nfrom random import randint\nfrom utils.loss_utils import l1_loss, ssim\nfrom gaussian_renderer import render, render_flow, network_gui\nimport sys\nfrom scene import Scene, GaussianModel\nfrom utils.general_utils import safe_state\nimport uuid","source_hash":"e500724aaebaf72b9527b166018435b5dd73aa7cf2a330a2664fd89de7f7db35","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:merge_gaussians.py","uri":"program://EfficientDynamic3DGaussian/file/merge_gaussians.py","kind":"file","name":"merge_gaussians.py","path":"merge_gaussians.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import os\nimport torch\nfrom torch import nn\n\nimport sys\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nimport numpy as np\nimport quaternion\n\ndef save_ply(xyz, features_dc, features_rest, opacity, scaling, rotation, path):\n mkdir_p(os.path.dirname(path))\n\n l = []\n for t in range(xyz.shape[1]):\n l.extend([f'x{t:03}', f'y{t:03}', f'z{t:03}'])\n\n l.extend(['nx', 'ny', 'nz'])\n # All channels except the 3 DC\n for i in range(features_dc.shape[1]*features_dc.shape[2]):\n l.append('f_dc_{}'.format(i))","source_hash":"b345b5b7a18f522623cd37e9a20fade4c40c21eab4c5df09ed1b85876723151e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:neural_3D_dataset_NDC.py","uri":"program://EfficientDynamic3DGaussian/file/neural_3D_dataset_NDC.py","kind":"file","name":"neural_3D_dataset_NDC.py","path":"neural_3D_dataset_NDC.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import concurrent.futures\nimport gc\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms as T\n\nfrom .ray_utils import get_ray_directions_blender, get_rays, ndc_rays_blender\n\n\ndef normalize(v):\n \"\"\"Normalize a vector.\"\"\"\n return v / np.linalg.norm(v)\n\n\ndef average_poses(poses):","source_hash":"7b528f620311569366a960060f5f8d6e44b1c8b95a8d5e07dd3feec631dd5f1c","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:render_video.py","uri":"program://EfficientDynamic3DGaussian/file/render_video.py","kind":"file","name":"render_video.py","path":"render_video.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser","source_hash":"70a7eacbb8ed3a2576771f239b75104d7d6fd91cc271fe12cb97fea4b7002771","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:metrics.py","uri":"program://EfficientDynamic3DGaussian/file/metrics.py","kind":"file","name":"metrics.py","path":"metrics.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom pathlib import Path\nimport os\nfrom PIL import Image\nimport torch\nimport torchvision.transforms.functional as tf\nfrom utils.loss_utils import ssim, msssim\nfrom lpipsPyTorch import lpips_helper\nimport json\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr","source_hash":"4a7702c2632eed4fdf5c0d856ec269eb6d8a120343ef2da57c56ed3da688fbbc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:render_flow.py","uri":"program://EfficientDynamic3DGaussian/file/render_flow.py","kind":"file","name":"render_flow.py","path":"render_flow.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render_flow\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom utils import flow_viz","source_hash":"0828d19a18547188c42e9b4093cf65483d9c60b5bbaf72c03af3a26c8fe13f5e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:scene/colmap_loader.py","uri":"program://EfficientDynamic3DGaussian/file/scene/colmap_loader.py","kind":"file","name":"scene/colmap_loader.py","path":"scene/colmap_loader.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport numpy as np\nimport collections\nimport struct\n\nCameraModel = collections.namedtuple(\n \"CameraModel\", [\"model_id\", \"model_name\", \"num_params\"])\nCamera = collections.namedtuple(\n \"Camera\", [\"id\", \"model\", \"width\", \"height\", \"params\"])\nBaseImage = collections.namedtuple(\n \"Image\", [\"id\", \"qvec\", \"tvec\", \"camera_id\", \"name\", \"xys\", \"point3D_ids\"])","source_hash":"6948ce06366e1f727ddffc39a445bf4b6873824f02abc39df63eb0c8f0fb3f36","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:scene/cameras.py","uri":"program://EfficientDynamic3DGaussian/file/scene/cameras.py","kind":"file","name":"scene/cameras.py","path":"scene/cameras.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom utils.graphics_utils import getWorld2View2, getProjectionMatrix\n\nclass Camera(nn.Module):\n def __init__(self, colmap_id, R, T, FoVx, FoVy, image, gt_alpha_mask,\n image_name, uid, time=0,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n **kwargs):","source_hash":"69ccfa581123f12b32fb80056ddc850c630bf7fe3721c57e9e8c2c6beb20f5e9","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:scene/gaussian_model.py","uri":"program://EfficientDynamic3DGaussian/file/scene/gaussian_model.py","kind":"file","name":"scene/gaussian_model.py","path":"scene/gaussian_model.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport numpy as np\nfrom utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation\nfrom torch import nn\nimport os\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import RGB2SH\nfrom simple_knn._C import distCUDA2\nfrom utils.graphics_utils import BasicPointCloud","source_hash":"29f0800a1b09070c8bcb06e281dda0976f283085f8ec0fc9d8599f8737fc8c20","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:scene/__init__.py","uri":"program://EfficientDynamic3DGaussian/file/scene/__init__.py","kind":"file","name":"scene/__init__.py","path":"scene/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport os\nimport random\nimport torch\nimport json\nfrom PIL import Image\nimport numpy as np\nfrom utils.system_utils import searchForMaxIteration\nfrom scene.dataset_readers import sceneLoadTypeCallbacks\nfrom scene.gaussian_model import GaussianModel\nfrom scene.cameras import Camera","source_hash":"a7eee1779854013ba65a9fb6eb6dd553576b1a285b28b1e8cd51bbb04495c733","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:scene/hyper_camera.py","uri":"program://EfficientDynamic3DGaussian/file/scene/hyper_camera.py","kind":"file","name":"scene/hyper_camera.py","path":"scene/hyper_camera.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Class for handling cameras.\"\"\"\nimport pathlib\n\nimport copy\nimport json\nfrom typing import Tuple, Union, Optional, Text\n","source_hash":"9b14427faee02c4f3988bb510b302e43f2e58061c684162073f9f54f32c7ceca","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:scene/dataset_readers.py","uri":"program://EfficientDynamic3DGaussian/file/scene/dataset_readers.py","kind":"file","name":"scene/dataset_readers.py","path":"scene/dataset_readers.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\nimport torch\nimport os\nimport sys\nimport glob\nfrom PIL import Image\nfrom typing import NamedTuple\nfrom scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \\\n read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text\nfrom utils.graphics_utils import getWorld2View2, focal2fov, fov2focal\nimport numpy as np\nimport json","source_hash":"6ef6ec1b356485b356c43e844ac019ee15f8d0de8ec6d35e90674fcae096334e","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/system_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/system_utils.py","kind":"file","name":"utils/system_utils.py","path":"utils/system_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom errno import EEXIST\nfrom os import makedirs, path\nimport os\n\ndef mkdir_p(folder_path):\n # Creates a directory. equivalent to using mkdir -p on the command line\n try:\n makedirs(folder_path)\n except OSError as exc: # Python >2.5\n if exc.errno == EEXIST and path.isdir(folder_path):","source_hash":"be01c02d3118c5d53808bc04efccd00c35a705a43a87c3583ea2f4752bc48553","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/graphics_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/graphics_utils.py","kind":"file","name":"utils/graphics_utils.py","path":"utils/graphics_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport math\nimport numpy as np\nfrom typing import NamedTuple\n\nclass BasicPointCloud(NamedTuple):\n points : np.array\n colors : np.array\n normals : np.array\n","source_hash":"d6e75de8161e98b72c2691e8a944a842e1b6625d2306035d079c868ac632edfc","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/image_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/image_utils.py","kind":"file","name":"utils/image_utils.py","path":"utils/image_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":19,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\n\ndef mse(img1, img2):\n return (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n\ndef psnr(img1, img2):\n mse = (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n return 20 * torch.log10(1.0 / torch.sqrt(mse))","source_hash":"872a4507773b9378db9e0fefc90104dc474b27551af18ada73f000a7a00a4ba0","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/general_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/general_utils.py","kind":"file","name":"utils/general_utils.py","path":"utils/general_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport sys\nfrom datetime import datetime\nimport numpy as np\nimport random\n\ndef inverse_sigmoid(x):\n return torch.log(x/(1-x))\n\ndef PILtoTorch(pil_image, resolution):","source_hash":"29854c065a315f4c073b0aad1e38a21c53b400787a76d98d51d4b13f19e8aa12","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/sh_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/sh_utils.py","kind":"file","name":"utils/sh_utils.py","path":"utils/sh_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright 2021 The PlenOctree Authors.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE","source_hash":"7d1ff267546390635e6d1f68c4f88c4a8b052482d5c9be1d32f06bc69e9a96e7","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/camera_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/camera_utils.py","kind":"file","name":"utils/camera_utils.py","path":"utils/camera_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\nimport os\n\nimport torch\nfrom scene.cameras import Camera, Camera2\nimport numpy as np\nfrom utils.general_utils import PILtoTorch\nfrom utils.graphics_utils import fov2focal\n\nWARNED = False\n\ndef loadCam(args, id, cam_info, resolution_scale):","source_hash":"0245306abb69a940a75dfe135fae6dc2b55ff94fcbee39907148e90701d3bd37","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:utils/loss_utils.py","uri":"program://EfficientDynamic3DGaussian/file/utils/loss_utils.py","kind":"file","name":"utils/loss_utils.py","path":"utils/loss_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nfrom torchmetrics import MultiScaleStructuralSimilarityIndexMeasure\n\nms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0).to('cuda')\n\ndef l1_loss(network_output, gt):\n return torch.abs((network_output - gt)).mean()","source_hash":"2aacff6dbd2b182624da518172149a1cd385e8fa671d7371a15d7805ec7e824a","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:gaussian_renderer/network_gui.py","uri":"program://EfficientDynamic3DGaussian/file/gaussian_renderer/network_gui.py","kind":"file","name":"gaussian_renderer/network_gui.py","path":"gaussian_renderer/network_gui.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nimport traceback\nimport socket\nimport json\nfrom scene.cameras import MiniCam\n\nhost = \"127.0.0.1\"\nport = 6009\n\nconn = None","source_hash":"7e392b8122a8e1359b4550769eac06190806a8c2eeb7f5aa7cbd025738dedf89","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:gaussian_renderer/__init__.py","uri":"program://EfficientDynamic3DGaussian/file/gaussian_renderer/__init__.py","kind":"file","name":"gaussian_renderer/__init__.py","path":"gaussian_renderer/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\n\nimport torch\nimport math\nfrom diff_gaussian_rasterization import GaussianRasterizationSettings, GaussianRasterizer\nfrom scene.gaussian_model import GaussianModel\nfrom utils.sh_utils import eval_sh\n\ndef render(viewpoint_camera, pc : GaussianModel, pipe, bg_color : torch.Tensor, scaling_modifier = 1.0, override_color = None, itr=-1):\n \"\"\"\n Render the scene. ","source_hash":"79ed7a3ea229c78ac430d96775b5f463601e1d7ff0d72a3328a166c21cb2755b","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:lpipsPyTorch/__init__.py","uri":"program://EfficientDynamic3DGaussian/file/lpipsPyTorch/__init__.py","kind":"file","name":"lpipsPyTorch/__init__.py","path":"lpipsPyTorch/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\n\nfrom .modules.lpips import LPIPS\n\n\ndef lpips_helper(device = 'cuda', net_type: str='alex', version: str = '0.1'):\n criterion = LPIPS(net_type, version).to(device) \n\n def f(x, y):\n return criterion(x, y)\n\n return f\n\ndef lpips(x: torch.Tensor,\n y: torch.Tensor,\n net_type: str = 'alex',\n version: str = '0.1'):\n r\"\"\"Function that measures\n Learned Perceptual Image Patch Similarity (LPIPS).\n\n Arguments:","source_hash":"a561d68364943bbc0dafd4ba0e5ae56b0945597b5986b6733ef16491391558b1","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:lpipsPyTorch/modules/networks.py","uri":"program://EfficientDynamic3DGaussian/file/lpipsPyTorch/modules/networks.py","kind":"file","name":"lpipsPyTorch/modules/networks.py","path":"lpipsPyTorch/modules/networks.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from typing import Sequence\n\nfrom itertools import chain\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\n\nfrom .utils import normalize_activation\n\n\ndef get_network(net_type: str):\n if net_type == 'alex':\n return AlexNet()\n elif net_type == 'squeeze':\n return SqueezeNet()\n elif net_type == 'vgg':\n return VGG16()\n else:\n raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')\n","source_hash":"dfa6f152b0e3fbc23ac3bfaea52b46e9473e64ad539ea22ab030c57af51c7f14","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:lpipsPyTorch/modules/lpips.py","uri":"program://EfficientDynamic3DGaussian/file/lpipsPyTorch/modules/lpips.py","kind":"file","name":"lpipsPyTorch/modules/lpips.py","path":"lpipsPyTorch/modules/lpips.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nimport torch.nn as nn\n\nfrom .networks import get_network, LinLayers\nfrom .utils import get_state_dict\n\n\nclass LPIPS(nn.Module):\n r\"\"\"Creates a criterion that measures\n Learned Perceptual Image Patch Similarity (LPIPS).\n\n Arguments:\n net_type (str): the network type to compare the features: \n 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n version (str): the version of LPIPS. Default: 0.1.\n \"\"\"\n def __init__(self, net_type: str = 'alex', version: str = '0.1'):\n\n assert version in ['0.1'], 'v0.1 is only supported now'\n\n super(LPIPS, self).__init__()","source_hash":"3bece0b9cf9943af5b043026458819d259df9bfe7c2a1d3ffc6c905e7e5aa2b4","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:lpipsPyTorch/modules/utils.py","uri":"program://EfficientDynamic3DGaussian/file/lpipsPyTorch/modules/utils.py","kind":"file","name":"lpipsPyTorch/modules/utils.py","path":"lpipsPyTorch/modules/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from collections import OrderedDict\n\nimport torch\n\n\ndef normalize_activation(x, eps=1e-10):\n norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))\n return x / (norm_factor + eps)\n\n\ndef get_state_dict(net_type: str = 'alex', version: str = '0.1'):\n # build url\n url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \\\n + f'master/lpips/weights/v{version}/{net_type}.pth'\n\n # download\n old_state_dict = torch.hub.load_state_dict_from_url(\n url, progress=True,\n map_location=None if torch.cuda.is_available() else torch.device('cpu')\n )\n","source_hash":"1bd4a7d4e7b43215497675ed852936fe4f27e7ea3068afe0b0e1f7cfb6c48570","truncated":false} {"repo_id":"EfficientDynamic3DGaussian","entity_id":"file:arguments/__init__.py","uri":"program://EfficientDynamic3DGaussian/file/arguments/__init__.py","kind":"file","name":"arguments/__init__.py","path":"arguments/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nfrom argparse import ArgumentParser, Namespace\nimport sys\nimport os\n\nclass GroupParams:\n pass\n\nclass ParamGroup:\n def __init__(self, parser: ArgumentParser, name : str, fill_none = False):\n group = parser.add_argument_group(name)","source_hash":"c3ff6b4edb116cc916d8964e21e2b4f9e6e1161057b10c86ed873dc648c16b58","truncated":false}